nex-code 0.5.3 → 0.5.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/benchmark.js +1 -1
- package/dist/nex-code.js +168 -168
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`),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 rf(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function Lw(t){try{let n=require("fs").readFileSync(rf(),"utf8"),s=JSON.parse(n);if(s&&typeof s[t]=="boolean")return s[t]}catch{}return null}function Iw(t,e){try{let n=require("fs"),s=require("path"),o=rf(),r=s.dirname(o),i={};try{i=JSON.parse(n.readFileSync(o,"utf8"))}catch{}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(c=>delete i[c]),n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(o,JSON.stringify(i),"utf8")}catch{}}function Dw(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let i=e.split(";"),a=parseInt(i[i.length-1],10);if(!isNaN(a))return a<8}let n=process.env.TERM_SESSION_ID||"default",s=Lw(n);if(s!==null)return s;let o=Pw(),r=o!==null?o:!0;return Iw(n,r),r}var af=Dw(),cf={reset:sf,bold:of,dim:uo,primary:ee(80,190,255),secondary:ee(60,170,190),success:ee(80,210,120),warning:ee(245,175,50),error:ee(230,80,80),muted:uo,subtle:ee(130,130,145),tool_read:ee(80,190,255),tool_write:ee(245,165,55),tool_exec:ee(185,100,235),tool_search:ee(70,185,190),tool_git:ee(90,210,100),tool_web:ee(100,215,250),tool_sysadmin:ee(225,150,75),tool_default:ee(100,205,115),syn_keyword:ee(185,100,235),syn_string:ee(90,210,120),syn_number:ee(245,175,50),syn_comment:uo,syn_key:ee(80,190,255),diff_add:ee(80,210,120),diff_rem:ee(230,80,80),banner_logo:ee(80,200,255),banner_name:ee(80,200,255),banner_version:uo,banner_model:uo,banner_yolo:ee(245,175,50),footer_sep:uo,footer_model:ee(80,175,235),footer_branch:ee(80,210,100),footer_project:ee(130,130,145),footer_divider:ee(80,80,95),footer_mode:ee(210,150,50),white:ee(210,210,220),red:ee(220,85,85),green:ee(80,200,110),yellow:ee(230,185,60),blue:ee(70,140,230),magenta:ee(200,120,190),cyan:ee(90,200,215),gray:ee(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:ee(110,215,230),brightMagenta:ee(220,140,210),brightBlue:ee(100,160,240)},lf={reset:sf,bold:of,dim:ee(110,110,120),primary:ee(0,110,190),secondary:ee(0,125,148),success:ee(0,148,62),warning:ee(168,92,0),error:ee(188,32,32),muted:ee(110,110,120),subtle:ee(155,155,165),tool_read:ee(0,110,190),tool_write:ee(168,92,0),tool_exec:ee(128,42,188),tool_search:ee(0,122,148),tool_git:ee(0,138,62),tool_web:ee(0,112,178),tool_sysadmin:ee(168,82,0),tool_default:ee(0,138,62),syn_keyword:ee(128,42,188),syn_string:ee(0,138,62),syn_number:ee(168,92,0),syn_comment:ee(135,135,148),syn_key:ee(0,110,190),diff_add:ee(0,148,62),diff_rem:ee(188,32,32),banner_logo:ee(0,122,205),banner_name:ee(0,122,205),banner_version:ee(100,100,118),banner_model:ee(100,100,118),banner_yolo:ee(168,62,0),footer_sep:ee(168,168,178),footer_model:ee(0,102,175),footer_branch:ee(0,138,62),footer_project:ee(135,135,148),footer_divider:ee(168,168,178),footer_mode:ee(148,88,0),white:ee(40,40,52),red:ee(188,32,32),green:ee(0,148,62),yellow:ee(168,92,0),blue:ee(0,110,190),magenta:ee(128,42,188),cyan:ee(0,125,148),gray:ee(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:ee(0,158,182),brightMagenta:ee(158,52,208),brightBlue:ee(0,112,208)},jw=af?cf:lf;uf.exports={T:jw,isDark:af,DARK:cf,LIGHT:lf}});var po=K((TO,ff)=>{var{T:ue}=Rt(),Ei=5,fo=(()=>{let t=[];for(let e=0;e<Ei;e++)t.push(e);for(let e=Ei-2;e>=1;e--)t.push(e);return t})(),df=["\u273D","\u2726","\u2727","\u2726"],
|
|
2
|
+
var Cc=Object.defineProperty;var Ew=Object.getOwnPropertyDescriptor;var Tw=Object.getOwnPropertyNames;var Rw=Object.prototype.hasOwnProperty;var Cw=(t,e)=>()=>(t&&(e=t(t=0)),e);var K=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Aw=(t,e)=>{for(var n in e)Cc(t,n,{get:e[n],enumerable:!0})},Ow=(t,e,n,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Tw(e))!Rw.call(t,o)&&o!==n&&Cc(t,o,{get:()=>e[o],enumerable:!(s=Ew(e,o))||s.enumerable});return t};var Mw=t=>Ow(Cc({},"__esModule",{value:!0}),t);var lo=K((kO,Nw)=>{Nw.exports={name:"nex-code",version:"0.5.4",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-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js","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.7.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 Rt=K((EO,uf)=>{"use strict";var sf="\x1B[0m",of="\x1B[1m",uo="\x1B[2m";function ee(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function Pw(){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(`
|
|
3
|
+
`),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 rf(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function Lw(t){try{let n=require("fs").readFileSync(rf(),"utf8"),s=JSON.parse(n);if(s&&typeof s[t]=="boolean")return s[t]}catch{}return null}function Iw(t,e){try{let n=require("fs"),s=require("path"),o=rf(),r=s.dirname(o),i={};try{i=JSON.parse(n.readFileSync(o,"utf8"))}catch{}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(c=>delete i[c]),n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(o,JSON.stringify(i),"utf8")}catch{}}function Dw(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let i=e.split(";"),a=parseInt(i[i.length-1],10);if(!isNaN(a))return a<8}let n=process.env.TERM_SESSION_ID||"default",s=Lw(n);if(s!==null)return s;let o=Pw(),r=o!==null?o:!0;return Iw(n,r),r}var af=Dw(),cf={reset:sf,bold:of,dim:uo,primary:ee(80,190,255),secondary:ee(60,170,190),success:ee(80,210,120),warning:ee(245,175,50),error:ee(230,80,80),muted:uo,subtle:ee(130,130,145),tool_read:ee(80,190,255),tool_write:ee(245,165,55),tool_exec:ee(185,100,235),tool_search:ee(70,185,190),tool_git:ee(90,210,100),tool_web:ee(100,215,250),tool_sysadmin:ee(225,150,75),tool_default:ee(100,205,115),syn_keyword:ee(185,100,235),syn_string:ee(90,210,120),syn_number:ee(245,175,50),syn_comment:uo,syn_key:ee(80,190,255),diff_add:ee(80,210,120),diff_rem:ee(230,80,80),banner_logo:ee(80,200,255),banner_name:ee(80,200,255),banner_version:uo,banner_model:uo,banner_yolo:ee(245,175,50),footer_sep:uo,footer_model:ee(80,175,235),footer_branch:ee(80,210,100),footer_project:ee(130,130,145),footer_divider:ee(80,80,95),footer_mode:ee(210,150,50),white:ee(210,210,220),red:ee(220,85,85),green:ee(80,200,110),yellow:ee(230,185,60),blue:ee(70,140,230),magenta:ee(200,120,190),cyan:ee(90,200,215),gray:ee(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:ee(110,215,230),brightMagenta:ee(220,140,210),brightBlue:ee(100,160,240)},lf={reset:sf,bold:of,dim:ee(110,110,120),primary:ee(0,110,190),secondary:ee(0,125,148),success:ee(0,148,62),warning:ee(168,92,0),error:ee(188,32,32),muted:ee(110,110,120),subtle:ee(155,155,165),tool_read:ee(0,110,190),tool_write:ee(168,92,0),tool_exec:ee(128,42,188),tool_search:ee(0,122,148),tool_git:ee(0,138,62),tool_web:ee(0,112,178),tool_sysadmin:ee(168,82,0),tool_default:ee(0,138,62),syn_keyword:ee(128,42,188),syn_string:ee(0,138,62),syn_number:ee(168,92,0),syn_comment:ee(135,135,148),syn_key:ee(0,110,190),diff_add:ee(0,148,62),diff_rem:ee(188,32,32),banner_logo:ee(0,122,205),banner_name:ee(0,122,205),banner_version:ee(100,100,118),banner_model:ee(100,100,118),banner_yolo:ee(168,62,0),footer_sep:ee(168,168,178),footer_model:ee(0,102,175),footer_branch:ee(0,138,62),footer_project:ee(135,135,148),footer_divider:ee(168,168,178),footer_mode:ee(148,88,0),white:ee(40,40,52),red:ee(188,32,32),green:ee(0,148,62),yellow:ee(168,92,0),blue:ee(0,110,190),magenta:ee(128,42,188),cyan:ee(0,125,148),gray:ee(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:ee(0,158,182),brightMagenta:ee(158,52,208),brightBlue:ee(0,112,208)},jw=af?cf:lf;uf.exports={T:jw,isDark:af,DARK:cf,LIGHT:lf}});var po=K((TO,ff)=>{var{T:ue}=Rt(),Ei=5,fo=(()=>{let t=[];for(let e=0;e<Ei;e++)t.push(e);for(let e=Ei-2;e>=1;e--)t.push(e);return t})(),df=["\u273D","\u2726","\u2727","\u2726"],Ac=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=fo[this.frame%fo.length],n="";for(let o=0;o<Ei;o++)n+=o===e?`${ue.cyan}\u25CF${ue.reset}`:" ";let s="";if(this.startTime){let o=Math.floor((Date.now()-this.startTime)/1e3);if(o>=60){let r=Math.floor(o/60),i=o%60;s=` ${ue.dim}${r}m ${String(i).padStart(2,"0")}s${ue.reset}`}else o>=1&&(s=` ${ue.dim}${o}s${ue.reset}`)}process.stderr.write(`\x1B[2K\r${n} ${ue.dim}${this.text}${ue.reset}${s}`),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}},Oc=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),s=e%60;return n>0?`${n}m ${String(s).padStart(2,"0")}s`:`${s}s`}_render(){if(this._stopped)return;let e=fo[this.frame%fo.length],n=`${ue.cyan}\u25CF${ue.reset}`,s=this._formatElapsed(),o=s?` ${ue.dim}${s}${ue.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let c,u;switch(this.statuses[a]){case"done":c=`${ue.green}\u2713${ue.reset}`,u=ue.dim;break;case"error":c=`${ue.red}\u2717${ue.reset}`,u=ue.dim;break;case"retry":c=`${ue.yellow}\u21BB${ue.reset}`,u=ue.yellow;break;default:c=a===e?n:" ",u=""}let d=a===this.labels.length-1?o:"",f=r-4-(d?s.length+1:0),p=this.labels[a].length>f?this.labels[a].substring(0,Math.max(10,f-3))+"...":this.labels[a];i+=`\x1B[2K ${c} ${u}${p}${ue.reset}${d}
|
|
4
4
|
`}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let n=0;n<this.lineCount;n++)e+=`
|
|
5
5
|
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,n){e>=0&&e<this.statuses.length&&(this.statuses[e]=n)}stop(e={}){if(this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),!e.silent)this._renderFinal();else{let n="";for(let s=0;s<this.lineCount;s++)n+=`\x1B[2K
|
|
6
6
|
`;this.lineCount>0&&(n+=`\x1B[${this.lineCount}A`),process.stderr.write(n)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),n=e?` ${ue.dim}${e}${ue.reset}`:"",s=process.stderr.columns||80,o="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${ue.green}\u2713${ue.reset}`;break;case"error":i=`${ue.red}\u2717${ue.reset}`;break;case"retry":i=`${ue.yellow}\u21BB${ue.reset}`;break;default:i=`${ue.yellow}\u25CB${ue.reset}`}let a=r===this.labels.length-1?n:"",c=s-4-(a?e.length+1:0),u=this.labels[r].length>c?this.labels[r].substring(0,Math.max(10,c-3))+"...":this.labels[r];o+=`\x1B[2K ${i} ${ue.dim}${u}${ue.reset}${a}
|
|
7
|
-
`}process.stderr.write(o)}},vi={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},ki={done:ue.green,in_progress:ue.cyan,pending:ue.dim,failed:ue.red},ns=null,
|
|
7
|
+
`}process.stderr.write(o)}},vi={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},ki={done:ue.green,in_progress:ue.cyan,pending:ue.dim,failed:ue.red},ns=null,Mc=class{constructor(e,n){this.name=e,this.tasks=n.map(s=>({id:s.id,description:s.description,status:s.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),s=e%60;return n>0?`${n}m ${String(s).padStart(2,"0")}s`:`${s}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=df[this.frame%df.length],n=this._formatElapsed(),s=this._formatTokens(),o=[n,s?`\u2193 ${s} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${ue.dim}(${o})${ue.reset}`:"",i=`\x1B[2K${ue.cyan}${e}${ue.reset} ${this.name}\u2026${r}
|
|
8
8
|
`;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],u=a===0?"\u23BF":" ",d=vi[c.status]||vi.pending,f=ki[c.status]||ki.pending,p=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${ue.dim}${u}${ue.reset} ${f}${d}${ue.reset} ${p}
|
|
9
9
|
`}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let n=0;n<this.lineCount;n++)e+=`
|
|
10
10
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),ns=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,ns===this&&(ns=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let n=0;n<this.lineCount;n++)e+=`\x1B[2K
|
|
11
11
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let n=0;n<this.lineCount;n++)e+=`
|
|
12
12
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,n){let s=this.tasks.find(o=>o.id===e);s&&(s.status=n)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),n=this.tasks.filter(a=>a.status==="done").length,s=this.tasks.filter(a=>a.status==="failed").length,o=this.tasks.length,r=s>0?`${n}/${o} done, ${s} failed`:`${n}/${o} done`,i=`\x1B[2K${ue.green}\u2714${ue.reset} ${this.name} ${ue.dim}(${e} \xB7 ${r})${ue.reset}
|
|
13
13
|
`;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],u=a===0?"\u23BF":" ",d=vi[c.status]||vi.pending,f=ki[c.status]||ki.pending,p=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${ue.dim}${u}${ue.reset} ${f}${d}${ue.reset} ${ue.dim}${p}${ue.reset}
|
|
14
|
-
`}process.stderr.write(i)}},
|
|
14
|
+
`}process.stderr.write(i)}},Nc=class{constructor(e,n){this.toolName=e,this.message=n||`Running ${e}...`,this.count=0,this.total=null,this.detail="",this.frame=0,this.interval=null,this.startTime=null,this._stopped=!1}_render(){if(this._stopped||!process.stderr.isTTY)return;let e=fo[this.frame%fo.length],n="";for(let r=0;r<Ei;r++)n+=r===e?`${ue.cyan}\u25CF${ue.reset}`:" ";let s=this.message;this.count>0&&(s+=` ${ue.cyan}${this.count}${ue.reset}`,this.total&&(s+=`/${this.total}`),this.detail&&(s+=` ${ue.dim}${this.detail}${ue.reset}`));let o="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(o=` ${ue.dim}${r}s${ue.reset}`)}process.stderr.write(`\x1B[2K\r${n} ${ue.dim}${s}${ue.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 qw(t){ns=t}function Fw(){return ns}function Bw(){ns&&(ns.stop(),ns=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}ff.exports={C:ue,Spinner:Ac,MultiProgress:Oc,TaskProgress:Mc,ToolProgress:Nc,setActiveTaskProgress:qw,getActiveTaskProgress:Fw,cleanupTerminal:Bw}});var Pc=K((RO,yf)=>{"use strict";var{T:Ss}=Rt(),me={kw:Ss.syn_keyword,str:Ss.syn_string,cmt:Ss.syn_comment,num:Ss.syn_number,type:Ss.cyan,punct:Ss.magenta,reset:Ss.reset},pf={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"])},Uw={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 mf(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return Uw[e]||null}var hf=/\x1b\[[0-9;]*m/g;function Fn(t,e,n){let s=t.split(hf),o=t.match(hf)||[],r="";for(let i=0;i<s.length;i++)r+=s[i].replace(e,n),i<o.length&&(r+=o[i]);return r}function Ww(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,n=>me.type+n+me.reset),e=Fn(e,/"([^"\\]|\\.)*"/g,n=>me.str+n+me.reset),e=Fn(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,n=>me.num+n+me.reset),e=Fn(e,/\b(true|false|null)\b/g,n=>me.kw+n+me.reset),e}function Hw(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,n=>me.cmt+n+me.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(n,s,o)=>s+me.type+o+me.reset),e=Fn(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(n,s)=>" "+me.kw+s+me.reset+"="),e=Fn(e,/"([^"]*)"/g,n=>me.str+n+me.reset),e}function Yw(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,n=>me.cmt+n+me.reset),e=Fn(e,/#[0-9a-fA-F]{3,8}\b/g,n=>me.num+n+me.reset),e=Fn(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(n,s,o)=>me.num+s+me.reset+o),e=Fn(e,/([a-z][a-z-]*)(\s*:)/g,(n,s,o)=>me.type+s+me.reset+o),e=Fn(e,/"[^"]*"|'[^']*'/g,n=>me.str+n+me.reset),e}function gf(t,e,n){if(e==="json")return Ww(t);if(e==="html"||e==="xml")return Hw(t);if(e==="css")return Yw(t);if(e==="md")return t;let s=pf[e]||pf.js,o="",r=0;if(n.inBlockComment){let i=t.indexOf("*/");if(i===-1)return me.cmt+t+me.reset;if(o+=me.cmt+t.slice(0,i+2)+me.reset,n.inBlockComment=!1,r=i+2,r>=t.length)return o}if(n.inString==="`"){let i=t.indexOf("`");if(i===-1)return me.str+t+me.reset;if(o+=me.str+t.slice(0,i+1)+me.reset,n.inString=null,r=i+1,r>=t.length)return o}for(;r<t.length;){let i=t[r];if(!n.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return o+=me.cmt+t.slice(r)+me.reset,n.inBlockComment=!0,o;o+=me.cmt+t.slice(r,a+2)+me.reset,r=a+2;continue}if(!n.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return o+=me.cmt+t.slice(r)+me.reset,o;if(!n.inString&&(i==='"'||i==="'"||i==="`")){n.inString=i,o+=me.str+i,r++;continue}if(n.inString){if(i==="\\"&&r+1<t.length){o+=i+t[r+1],r+=2;continue}if(i===n.inString){o+=i+me.reset,n.inString=null,r++;continue}o+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let a="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(a.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)a+=t[r++];o+=me.num+a+me.reset;continue}if(i==="@"&&(e==="js"||e==="java"||e==="py")){let a="@";for(r++;r<t.length&&/[a-zA-Z0-9_$.]/.test(t[r]);)a+=t[r++];o+=me.punct+a+me.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];s.has(a)?o+=me.kw+a+me.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?o+=me.type+a+me.reset:o+=a;continue}o+=i,r++}return n.inString&&n.inString!=="`"&&(o+=me.reset,n.inString=null),o}function Gw(t,e){let n=mf(e);if(!n)return t.split(`
|
|
15
15
|
`);let s=t.split(`
|
|
16
|
-
`),o={inString:null,inBlockComment:!1};return s.map(r=>gf(r,n,o))}function Kw(t,e){return e?gf(t,e,{inString:null,inBlockComment:!1}):t}yf.exports={detectLang:mf,highlightLine:Kw,highlightLines:Gw}});var bf=K((CO,wf)=>{var{T:I}=Rt(),bt=I,zw={read_file:I.tool_read,list_directory:I.tool_read,write_file:I.tool_write,edit_file:I.tool_write,patch_file:I.tool_write,bash:I.tool_exec,grep:I.tool_search,search_files:I.tool_search,glob:I.tool_search,git_commit:I.tool_git,git_push:I.tool_git,git_pull:I.tool_git,git_status:I.tool_git,git_diff:I.tool_git,git_log:I.tool_git,git_branch:I.tool_git,git_stash:I.tool_git,web_fetch:I.tool_web,web_search:I.tool_web,sysadmin:I.tool_sysadmin,ssh_exec:I.tool_sysadmin,ssh_upload:I.tool_sysadmin,ssh_download:I.tool_sysadmin,deploy:I.tool_sysadmin},
|
|
16
|
+
`),o={inString:null,inBlockComment:!1};return s.map(r=>gf(r,n,o))}function Kw(t,e){return e?gf(t,e,{inString:null,inBlockComment:!1}):t}yf.exports={detectLang:mf,highlightLine:Kw,highlightLines:Gw}});var bf=K((CO,wf)=>{var{T:I}=Rt(),bt=I,zw={read_file:I.tool_read,list_directory:I.tool_read,write_file:I.tool_write,edit_file:I.tool_write,patch_file:I.tool_write,bash:I.tool_exec,grep:I.tool_search,search_files:I.tool_search,glob:I.tool_search,git_commit:I.tool_git,git_push:I.tool_git,git_pull:I.tool_git,git_status:I.tool_git,git_diff:I.tool_git,git_log:I.tool_git,git_branch:I.tool_git,git_stash:I.tool_git,web_fetch:I.tool_web,web_search:I.tool_web,sysadmin:I.tool_sysadmin,ssh_exec:I.tool_sysadmin,ssh_upload:I.tool_sysadmin,ssh_download:I.tool_sysadmin,deploy:I.tool_sysadmin},Lc={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 Ti(t,e=!1,n=null){if(e)return`${I.error}\u23FA${I.reset}`;let s=zw[t]||I.tool_default;return n==="blink"?`${s}\x1B[5m\u23FA\x1B[25m${I.reset}`:`${s}${n!==null?n:"\u23FA"}${I.reset}`}function Xw(t,e,n=!1,s=null){let o=(t||[]).filter(c=>c&&c.canExecute!==!1);if(o.length===0)return`${Ti("",n,s)} Step ${e}`;if(o.length===1){let c=o[0],u=c.args||{},d=Lc[c.fnName]||c.fnName.replace(/_/g," "),f="";u.path?f=u.path:u.command?f=String(u.command).substring(0,80):u.query?f=String(u.query).substring(0,60):u.pattern?f=String(u.pattern).substring(0,60):u.url&&(f=String(u.url).substring(0,60));let p=f?`(${bt.dim}${f}${bt.reset})`:"";return`${Ti(c.fnName,n,s)} ${bt.bold}${d}${bt.reset}${p}`}let r=o[0].fnName,i=[...new Set(o.map(c=>Lc[c.fnName]||c.fnName.replace(/_/g," ")))],a=i.length<=3?i.join(", "):`${o.length} tools`;return`${Ti(r,n,s)} ${bt.bold}${a}${bt.reset}`}function Vw(t,e){let n;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":n=e.path||"";break;case"bash":case"ssh_exec":n=(e.command||"").substring(0,80);break;case"grep":case"search_files":n=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":n=e.pattern||"";break;case"web_fetch":n=(e.url||"").substring(0,60);break;case"web_search":n=(e.query||"").substring(0,50);break;default:n=JSON.stringify(e).substring(0,80)}let s=Lc[t]||t.replace(/_/g," "),o=n?`(${bt.dim}${n}${bt.reset})`:"";return`${Ti(t)} ${bt.bold}${s}${bt.reset}${o}`}function Jw(t,e=8){let n=t.split(`
|
|
17
17
|
`),s=n.slice(0,e),o=n.length-e,r=`${I.muted} \u23BF ${I.reset}`,i=" ",a=s.map((c,u)=>`${u===0?r:i}${I.success}${c}${I.reset}`).join(`
|
|
18
18
|
`);return o>0&&(a+=`
|
|
19
|
-
${I.subtle} \u2026 +${o} lines${I.reset}`),a}var Ri=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],$f=Math.floor(Math.random()*Ri.length),
|
|
19
|
+
${I.subtle} \u2026 +${o} lines${I.reset}`),a}var Ri=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],$f=Math.floor(Math.random()*Ri.length),Ic=null;function Zw(t){Ic=t}function Qw(){let t=Ri[$f%Ri.length];$f++;let e=Ic?` \xB7 ${Ic}`:"";return`${t}${e}`}function eb(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 n=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${n}: full audit...`;case"disk_usage":return`Sysadmin${n}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${n}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${n}: network status...`;case"ssl_check":return`Sysadmin${n}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${n}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${n}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${n}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${n}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${n}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${n}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${n}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${n}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${n}: cron ${e.cron_action||""}...`;default:return`Sysadmin${n}: ${e.action}...`}}case"visual_diff":return"Comparing screenshots (pixel diff)...";case"responsive_sweep":return`Responsive sweep: ${(e.url||"").substring(0,50)}...`;case"visual_annotate":return`Annotating screenshot (${(e.annotations||[]).length} markers)...`;case"visual_watch":return`Visual watch: ${(e.url||"").substring(0,50)}...`;case"design_tokens":return"Extracting design tokens...";case"design_compare":return"Comparing against reference design...";default:return`Running: ${t}`}}function tb(t,e,n,s){let o=String(n||"");if(s){let a=o.split(`
|
|
20
20
|
`)[0];if(a.startsWith("BLOCKED:")){let f=a.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return` ${I.muted}\u23BF blocked: ${f}${I.reset}`}let c=a.replace(/^ERROR:\s*/i,"").substring(0,80),u=o.match(/\nHINT: (.+)/),d=u?`
|
|
21
21
|
${I.muted}${u[1].substring(0,100)}${I.reset}`:"";return` ${I.error}\u23BF ${c}${I.reset}${d}`}let r;switch(t){case"read_file":{let c=o.split(`
|
|
22
22
|
`).filter(Boolean).filter(g=>!/^File:\s/.test(g)&&!/^\[LARGE FILE:/.test(g)),u=c.length,d=c[c.length-1],f=d?parseInt(d.match(/^(\d+):/)?.[1]||"0"):0,p=e.line_start||e.line_end,m=e.path?require("path").basename(e.path):null,h=m?` ${I.muted}from ${m}${I.reset}`:"";p&&f>u?r=`Read lines ${e.line_start||1}\u2013${f}${h}`:r=`Read ${u} line${u!==1?"s":""}${h}`;break}case"write_file":{let c=(e.content||"").split(`
|
|
23
|
-
`).length,u=e.path?require("path").basename(e.path):null,d=u?`Wrote ${u} \xB7 ${c} line${c!==1?"s":""}`:`Wrote ${c} line${c!==1?"s":""}`,{highlightLines:f}=
|
|
23
|
+
`).length,u=e.path?require("path").basename(e.path):null,d=u?`Wrote ${u} \xB7 ${c} line${c!==1?"s":""}`:`Wrote ${c} line${c!==1?"s":""}`,{highlightLines:f}=Pc(),p=f(e.content||"",e.path||null),m=40,h=8;if(c<=m){let g=p.map($=>` ${$}`).join(`
|
|
24
24
|
`);r=`${d}
|
|
25
25
|
${g}`}else{let g=p.slice(0,h).map($=>` ${$}`).join(`
|
|
26
26
|
`);r=`${d}
|
|
27
27
|
${g}
|
|
28
28
|
${I.subtle}\u2026 +${c-h} lines${I.reset}`}break}case"edit_file":{let a=(e.old_text||"").split(`
|
|
29
29
|
`),c=(e.new_text||"").split(`
|
|
30
|
-
`),u=a.length,d=c.length,f=e.path?require("path").basename(e.path):null,p=f?` ${I.muted}${f}${I.reset}`:"",m=a.find(E=>E.trim()),h=c.find(E=>E.trim()),{highlightLine:g,detectLang:$}=
|
|
30
|
+
`),u=a.length,d=c.length,f=e.path?require("path").basename(e.path):null,p=f?` ${I.muted}${f}${I.reset}`:"",m=a.find(E=>E.trim()),h=c.find(E=>E.trim()),{highlightLine:g,detectLang:$}=Pc(),w=$(e.path||null),k=[];m&&k.push(` ${I.diff_rem}- ${I.reset}${g(m.trimEnd().substring(0,72),w)}${I.reset}`),h&&k.push(` ${I.diff_add}+ ${I.reset}${g(h.trimEnd().substring(0,72),w)}${I.reset}`),r=`${I.diff_rem}\u2212${u}${I.reset} ${I.diff_add}+${d}${I.reset}${p}`+(k.length>0?`
|
|
31
31
|
`+k.join(`
|
|
32
32
|
`):"");break}case"patch_file":{let a=e.patches||[],c=a.reduce((d,f)=>d+(f.old_text||"").split(`
|
|
33
33
|
`).length,0),u=a.reduce((d,f)=>d+(f.new_text||"").split(`
|
|
@@ -48,20 +48,20 @@ ${g}
|
|
|
48
48
|
`).filter(f=>f.trim()&&!f.startsWith("EXIT ")),d=c?`${I.error}\u2717${I.reset}`:`${I.success}\u2713${I.reset}`;if(u.length===0)r=d;else{if(u.length>2&&u.every(g=>/^\[/.test(g.trim()))){r=`${d} ${u.length} log lines`;break}let p=c?u.slice(-3):u.slice(0,3),m=u.length-3,h=p.map((g,$)=>$===0?`${d} ${I.muted}${g.substring(0,120)}${I.reset}`:` ${I.muted}${g.substring(0,120)}${I.reset}`);if(m>0){let g=c?` ${I.subtle}${m} lines above\u2026${I.reset}`:` ${I.subtle}\u2026 +${m} lines${I.reset}`;c?h.unshift(g):h.push(g)}r=h.join(`
|
|
49
49
|
`)}break}default:{let a=o.split(`
|
|
50
50
|
`).filter(c=>c.trim()&&!c.startsWith("EXIT ")&&!c.startsWith("HINT:"));if(a.length>0){let c=a[0].trim().substring(0,90),u=a.length>1?` ${I.subtle}\u2026 +${a.length-1} lines${I.reset}`:"";r=`${I.muted}${c}${I.reset}${u}`}else r="Done"}}return` ${I.muted}\u23BF ${r}${I.reset}`}function nb(t,e,n,s,o,r){let i=Math.round(s/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,c=`
|
|
51
|
-
${I.success}\u25C6${bt.reset} ${bt.bold}${t}${bt.reset}`;return c+=`${bt.dim} \xB7 ${a}`,r.size>0&&(c+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),c+=bt.reset,c}wf.exports={C:bt,formatToolCall:Vw,formatResult:Jw,getToolSpinnerText:eb,formatToolSummary:tb,formatSectionHeader:Xw,formatMilestone:nb,getThinkingVerb:Qw,setActiveModelForSpinner:Zw,THINKING_VERBS:Ri}});var Ye=K((AO,xf)=>{var{T:vs}=Rt(),
|
|
51
|
+
${I.success}\u25C6${bt.reset} ${bt.bold}${t}${bt.reset}`;return c+=`${bt.dim} \xB7 ${a}`,r.size>0&&(c+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),c+=bt.reset,c}wf.exports={C:bt,formatToolCall:Vw,formatResult:Jw,getToolSpinnerText:eb,formatToolSummary:tb,formatSectionHeader:Xw,formatMilestone:nb,getThinkingVerb:Qw,setActiveModelForSpinner:Zw,THINKING_VERBS:Ri}});var Ye=K((AO,xf)=>{var{T:vs}=Rt(),Dc=vs,_f=["01100110","01111110","01111110","01011010","01111110","00111100"];function sb(t,e){let n=[];for(let s=0;s<t.length;s+=2){let o="";for(let r=0;r<t[0].length;r++){let i=t[s][r]==="1",a=s+1<t.length&&t[s+1][r]==="1";i&&a?o+=`${e}\u2588\x1B[0m`:i&&!a?o+=`${e}\u2580\x1B[0m`:!i&&a?o+=`${e}\u2584\x1B[0m`:o+=" "}n.push(o)}return n}function ob(t,e,n={}){let s=Dc.bold,o=Dc.reset,r=sb(_f,vs.banner_logo),i=n.yolo?` ${s}${vs.banner_yolo}\u26A1 YOLO${o}`:"",a=lo().version,c=[` ${vs.banner_name}${s}nex-code${o} ${vs.banner_version}v${a}${o}`,` ${vs.banner_model}${t}${o} ${vs.muted}\xB7 /help${o}${i}`,""],u=Math.max(r.length,c.length),d=Math.floor((u-r.length)/2),f=Math.floor((u-c.length)/2),p=_f[0].length,m=[];for(let h=0;h<u;h++){let g=r[h-d]??" ".repeat(p),$=c[h-f]??"";m.push(g+$)}console.log(`
|
|
52
52
|
`+m.join(`
|
|
53
53
|
`)+`
|
|
54
|
-
`)}var{Spinner:rb,MultiProgress:ib,TaskProgress:ab,ToolProgress:cb,setActiveTaskProgress:lb,getActiveTaskProgress:ub,cleanupTerminal:db}=po(),{formatToolCall:fb,formatResult:pb,getToolSpinnerText:hb,formatToolSummary:mb,formatSectionHeader:gb,formatMilestone:yb,getThinkingVerb:$b,setActiveModelForSpinner:wb}=bf();xf.exports={C:
|
|
55
|
-
`){u(o);return}if(p==="\x1B[A"){o=(o-1+n.length)%n.length,a();return}if(p==="\x1B[B"){o=(o+1)%n.length,a();return}let m=p.toLowerCase().trim();if(m==="y"){c(!0);return}if(m==="n"){c(!1);return}if(m==="a"&&e.toolName){Ci(e.toolName),c(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",d)})}function Pb(t,e){let n=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(s=>{let o=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(Ci(e.toolName),s(!0)):s(i!=="n")};if(ks)ks.question(`${Rn.yellow}${t} ${n}${Rn.reset}`,o);else{let r=bb.createInterface({input:process.stdin,output:process.stdout});r.question(`${Rn.yellow}${t} ${n}${Rn.reset}`,i=>{r.close(),o(i)})}})}var Ci=()=>{};function Lb(t){Ci=t}Rf.exports={sanitizeBashCommand:tr,FORBIDDEN_PATTERNS:
|
|
56
|
-
`);this.buffer=n.pop()||"";for(let s of n){let o=this.parseLine(s);if(o?.done)return o}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},Ai=class extends go{constructor(e,n={}){super(e,n),this.toolCallsMap={}}parseLine(e){let n=e.trim();if(!n||!n.startsWith("data: "))return{done:!1};let s=n.slice(6);if(s==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(s)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a=i.index??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}}))}}},Oi=class extends mo{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:n,tools:s,maxTokens:o,temperature:r,stream:i}){let a={model:e,messages:n,max_tokens:o,temperature:r};return i&&(a.stream=!0),s&&s.length>0&&(a.tools=s),a}normalizeResponse(e){let n=e.choices?.[0]?.message||{},s=(n.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:n.content||"",tool_calls:s}}createStreamParser(e,n={}){return new Ai(e,n)}},Mi=class extends go{constructor(e,n={}){super(e,n),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let n=e.trim();if(!n.startsWith("data: "))return{done:!1};let s=n.slice(6),o;try{o=JSON.parse(s)}catch{return{done:!1}}switch(o.type){case"content_block_start":{let r=o.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=o.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let n={};if(e.inputJson)try{n=JSON.parse(e.inputJson)}catch{n=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:n}}})}}},Uc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",Ni=class extends mo{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:n,tools:s,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:n,max_tokens:o,temperature:r};if(i&&(c.stream=!0),a?.system){let u=a.system,d=u.indexOf(Uc);if(d!==-1){let f=u.slice(0,d).trimEnd(),p=u.slice(d+Uc.length).trimStart();c.system=[{type:"text",text:f},{type:"text",text:p,cache_control:{type:"ephemeral"}}]}else c.system=u}return s&&s.length>0&&(c.tools=s),c}formatTools(e){return!e||e.length===0?[]:e.map(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let n="",s=[];for(let o of e.content||[])o.type==="text"?n+=o.text:o.type==="tool_use"&&s.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:n,tool_calls:s}}createStreamParser(e,n={}){return new Mi(e,n)}};function Af(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 Pi=class extends go{constructor(e,n={}){super(e,n),this.toolCalls=[],this.onThinkingToken=n.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let n;try{n=JSON.parse(e)}catch{return{done:!1}}return n.message?.thinking&&this.onThinkingToken(n.message.thinking),n.message?.content&&(this.onToken(n.message.content),this.content+=n.message.content),n.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(n.message.tool_calls)),n.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,n)=>({id:e.id||`ollama-${Date.now()}-${n}`,function:{name:e.function?.name||e.name||"unknown",arguments:Af(e.function?.arguments??e.arguments)}}))}}},Li=class extends mo{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:n,tools:s,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:n,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:a?.repeat_penalty??1.05}};return s&&s.length>0&&(c.tools=s),c}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:(n.tool_calls||[]).map((s,o)=>({id:s.id||`ollama-${Date.now()}-${o}`,function:{name:s.function?.name||s.name||"unknown",arguments:Af(s.function?.arguments??s.arguments)}}))}}createStreamParser(e,n={}){return new Pi(e,n)}},Db=new Oi,jb=new Ni,qb=new Li;Of.exports={ANTHROPIC_CACHE_BOUNDARY:Uc,WireProtocol:mo,StreamParser:go,OpenAICompatibleProtocol:Oi,AnthropicProtocol:Ni,OllamaChatProtocol:Li,OpenAIStreamParser:Ai,AnthropicStreamParser:Mi,OllamaStreamParser:Pi,openaiProtocol:Db,anthropicProtocol:jb,ollamaProtocol:qb}});var Pf=K((PO,Nf)=>{var Ii=require("axios"),Fb=require("http"),Bb=require("https"),{BaseProvider:Ub,readStreamErrorBody:Wb}=ho(),{ollamaProtocol:Es}=yo(),Di=new Fb.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),ji=new Bb.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Mf={"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}},Wc=class extends Ub{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Mf,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){Ii.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Di,httpsAgent:ji}).then(e=>{let n=e.data?.models||[];for(let s of n){let o=(s.name||s.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:s.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await Ii.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Di,httpsAgent:ji})).data?.models||[];for(let s of n){let o=(s.name||s.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:s.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(n=>{if(Array.isArray(n.content)){let s=[],o=[];for(let i of n.content)i.type==="text"?s.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:n.role,content:s.join(`
|
|
57
|
-
`)};return o.length>0&&(r.images=o),n.tool_call_id&&(r.tool_call_id=n.tool_call_id),r}return n})}async chat(e,n,s={}){await this.discoverModels();let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,a=Es.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!1,extra:{repeat_penalty:s.repeat_penalty}}),c;try{c=await Ii.post(`${this.baseUrl}${Es.getEndpoint()}`,a,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Di,httpsAgent:ji})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Es.normalizeResponse(c.data)}async stream(e,n,s={}){await this.discoverModels();let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,a=s.onToken||(()=>{}),c=s.onThinkingToken||(()=>{}),u=Es.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!0,extra:{repeat_penalty:s.repeat_penalty}}),d;try{d=await Ii.post(`${this.baseUrl}${Es.getEndpoint()}`,u,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal,httpAgent:Di,httpsAgent:ji})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",h=await Wb(p,$=>$?.error),g=new Error(`API Error${m}: ${h}`);throw g.code=p.code||(p.response?.status?`HTTP_${p.response.status}`:void 0),g}let f=Es.createStreamParser(a,{onThinkingToken:c});return new Promise((p,m)=>{s.signal&&s.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",h=>{let{done:g,result:$}=f.feed(h.toString());g&&p($)}),d.data.on("error",h=>{if(s.signal?.aborted)return;let g=new Error(`Stream error: ${h.message}`);g.code=h.code||h.name,m(g)}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return Es.normalizeResponse(e)}};Nf.exports={OllamaProvider:
|
|
58
|
-
`)||JSON.stringify(e.content):n=typeof e.content=="string"?e.content:JSON.stringify(e.content),{role:"tool",content:n,tool_call_id:e.tool_call_id}}if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let s of e.content)if(s.type==="text")n.push({type:"text",text:s.text??""});else if(s.type==="image"&&s.data){let o=s.data.startsWith("data:")?s.data:`data:${s.media_type||"image/png"};base64,${s.data}`;n.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),c=Ts.buildRequestBody({model:o,messages:a,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!1}),u;try{u=await Lf.post(`${this.baseUrl}${Ts.getEndpoint()}`,c,{timeout:s.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return Ts.normalizeResponse(u.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,a=s.onToken||(()=>{}),{messages:c}=this.formatMessages(e),u=Ts.buildRequestBody({model:o,messages:c,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!0}),d;try{d=await Lf.post(`${this.baseUrl}${Ts.getEndpoint()}`,u,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",h=await Yb(p,g=>g?.error?.message||g?.error);throw new Error(`API Error${m}: ${h}`)}let f=Ts.createStreamParser(a);return new Promise((p,m)=>{s.signal&&s.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",h=>{let{done:g,result:$}=f.feed(h.toString());g&&p($)}),d.data.on("error",h=>{s.signal?.aborted||m(new Error(`Stream error: ${h.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return Ts.normalizeResponse(e)}};Df.exports={OpenAIProvider:
|
|
59
|
-
|
|
60
|
-
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){s.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,s);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}s.push(r)}}for(let o=s.length-1;o>0;o--)s[o].role==="user"&&s[o-1].role==="user"&&s.splice(o,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:s,system:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let s=[];if(e.content&&s.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)s.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:s.length>0?s:[{type:"text",text:""}]}}if(e.role==="tool"){let s=n[n.length-1],o;if(Array.isArray(e.content)){let i=[];for(let a of e.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});o=i}else o=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:o};return s&&s.role==="user"&&Array.isArray(s.content)&&s.content[0]?.type==="tool_result"?(s.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let s=[];for(let o of e.content)o.type==="text"?s.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&s.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:s}}return{role:"user",content:e.content}}formatTools(e){return ss.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=s.maxTokens||i?.maxTokens||8192,{messages:c,system:u}=this.formatMessages(e),d=this.formatTools(n),f=ss.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:s.temperature??this.temperature,stream:!1,extra:{system:u}}),p;try{p=await qf.post(`${this.baseUrl}${ss.getEndpoint()}`,f,{timeout:s.timeout||this.timeout,headers:this._getHeaders()})}catch(m){if(m.name==="CanceledError"||m.name==="AbortError"||m.code==="ERR_CANCELED")throw m;let h=m.response?.status?` [HTTP ${m.response.status}]`:"",g=m.response?.data?.error?.message||m.response?.data?.error||m.message;throw new Error(`API Error${h}: ${g}`)}return ss.normalizeResponse(p.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=s.maxTokens||i?.maxTokens||8192,c=s.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f=this.formatTools(n),p=ss.buildRequestBody({model:r,messages:u,tools:f,maxTokens:a,temperature:s.temperature??this.temperature,stream:!0,extra:{system:d}}),m;try{m=await qf.post(`${this.baseUrl}${ss.getEndpoint()}`,p,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let $=g.response?.status?` [HTTP ${g.response.status}]`:"",w=await Kb(g,k=>k?.error?.message||k?.error);throw new Error(`API Error${$}: ${w}`)}let h=ss.createStreamParser(c);return new Promise((g,$)=>{s.signal&&s.signal.addEventListener("abort",()=>{m.data.destroy(),$(new DOMException("The operation was aborted","AbortError"))},{once:!0}),m.data.on("data",w=>{let{done:k,result:E}=h.feed(w.toString());k&&g(E)}),m.data.on("error",w=>{s.signal?.aborted||$(new Error(`Stream error: ${w.message}`))}),m.data.on("end",()=>{g(h.flush())})})}normalizeResponse(e){return ss.normalizeResponse(e)}};Bf.exports={AnthropicProvider:Yc,ANTHROPIC_MODELS:Ff}});var Gf=K((DO,Yf)=>{var Wf=require("axios"),{BaseProvider:Xb,readStreamErrorBody:Vb}=ho(),{openaiProtocol:Rs}=yo(),Hf={"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}},Gc=class extends Xb{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Hf,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let s of e){if(this._messageFormatCache.has(s)){n.push(this._messageFormatCache.get(s));continue}let o=this._getMessageCacheKey(s);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(s,i),n.push(i);continue}let r=this._formatSingleMessage(s);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(s,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let s of e.content)if(s.type==="text")n.push({type:"text",text:s.text??""});else if(s.type==="image"&&s.data){let o=s.data.startsWith("data:")?s.data:`data:${s.media_type||"image/png"};base64,${s.data}`;n.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),c=Rs.buildRequestBody({model:o,messages:a,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!1}),u;try{u=await Wf.post(`${this.baseUrl}${Rs.getEndpoint()}`,c,{timeout:s.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return Rs.normalizeResponse(u.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||8192,a=s.onToken||(()=>{}),{messages:c}=this.formatMessages(e),u=Rs.buildRequestBody({model:o,messages:c,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!0}),d;try{d=await Wf.post(`${this.baseUrl}${Rs.getEndpoint()}`,u,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",h=await Vb(p,g=>g?.error?.message||g?.error);throw new Error(`API Error${m}: ${h}`)}let f=Rs.createStreamParser(a);return new Promise((p,m)=>{s.signal&&s.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",h=>{let{done:g,result:$}=f.feed(h.toString());g&&p($)}),d.data.on("error",h=>{s.signal?.aborted||m(new Error(`Stream error: ${h.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return Rs.normalizeResponse(e)}};Yf.exports={GeminiProvider:Gc,GEMINI_MODELS:Hf}});var Xf=K((jO,zf)=>{var qi=require("axios"),{BaseProvider:Jb,readStreamErrorBody:Zb}=ho(),{ollamaProtocol:Cs}=yo(),Kf="http://localhost:11434",Kc=class extends Jb{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Kf,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let n=(await qi.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let s of n){let o=s.name||s.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let a=await qi.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:s.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let s=[],o=[];for(let i of n.content)i.type==="text"?s.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:s.join(`
|
|
61
|
-
`)};return o.length>0&&(r.images=o),r}return n})}async chat(e,n,s={}){this._modelsLoaded||await this.loadModels();let o=s.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=Cs.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:s.maxTokens||8192,temperature:s.temperature??this.temperature,stream:!1}),i;try{i=await qi.post(`${this.baseUrl}${Cs.getEndpoint()}`,r,{timeout:s.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let c=a.response?.status?` [HTTP ${a.response.status}]`:"",u=a.response?.data?.error||a.message;throw new Error(`API Error${c}: ${u}`)}return Cs.normalizeResponse(i.data)}async stream(e,n,s={}){this._modelsLoaded||await this.loadModels();let o=s.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=s.onToken||(()=>{}),i=Cs.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:s.maxTokens||8192,temperature:s.temperature??this.temperature,stream:!0}),a;try{a=await qi.post(`${this.baseUrl}${Cs.getEndpoint()}`,i,{timeout:s.timeout||this.timeout,responseType:"stream",signal:s.signal})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=await Zb(u,p=>p?.error);throw new Error(`API Error${d}: ${f}`)}let c=Cs.createStreamParser(r);return new Promise((u,d)=>{s.signal&&s.signal.addEventListener("abort",()=>{a.data.destroy(),d(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",f=>{let{done:p,result:m}=c.feed(f.toString());p&&u(m)}),a.data.on("error",f=>{s.signal?.aborted||d(new Error(`Stream error: ${f.message}`))}),a.data.on("end",()=>{u(c.flush())})})}normalizeResponse(e){return Cs.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let n=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return n?parseInt(n[1],10):null}};zf.exports={LocalProvider:
|
|
62
|
-
`)}}function
|
|
63
|
-
`)}function a_(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function c_(t,e,n,s){let o=
|
|
64
|
-
`),a}catch(a){throw o.stop(),a}}async function R_(t,e){return sr.callChat(t,e)}up.exports={MODELS:x_,getActiveModel:S_,setActiveModel:v_,getModelNames:k_,callOllamaStream:T_,callOllama:R_,parseToolArgs:E_}});var pp=K((YO,fp)=>{var Bi=require("path"),{C:U}=Ye(),{T:
|
|
54
|
+
`)}var{Spinner:rb,MultiProgress:ib,TaskProgress:ab,ToolProgress:cb,setActiveTaskProgress:lb,getActiveTaskProgress:ub,cleanupTerminal:db}=po(),{formatToolCall:fb,formatResult:pb,getToolSpinnerText:hb,formatToolSummary:mb,formatSectionHeader:gb,formatMilestone:yb,getThinkingVerb:$b,setActiveModelForSpinner:wb}=bf();xf.exports={C:Dc,banner:ob,Spinner:rb,MultiProgress:ib,TaskProgress:ab,ToolProgress:cb,setActiveTaskProgress:lb,getActiveTaskProgress:ub,cleanupTerminal:db,formatToolCall:fb,formatResult:pb,getToolSpinnerText:hb,formatToolSummary:mb,formatSectionHeader:gb,formatMilestone:yb,getThinkingVerb:$b,setActiveModelForSpinner:wb}});var _t=K((OO,Rf)=>{var bb=require("readline"),{C:Rn}=Ye(),_b=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,xb=/^=([\w-]+)/;function tr(t){return typeof t!="string"?t:t.replace(_b,"").replace(xb,"$1")}var Fc=[/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/],Sf=[...Fc,/\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 Sb(t){for(let e of Sf)if(e.test(t))return e;return null}var vf=[/\.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)/],vb=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,jc=[/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 kf(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let s=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(s.length===0)return!1;let o=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>o(u)):jc.some(c=>c.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:jc.some(a=>a.test(i))};return s.every(o)}var Bc=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/,/--no-verify\b/,/git\s+reset\s+--hard\b/,/git\s+clean\s+-[a-z]*f/,/git\s+checkout\s+--\s/,/git\s+push\s+(?:--force\b|-f\b)/],Ef=[/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/],Tf=[...Bc,...Ef],Uc=!1,ks=null,qc=null;function kb(t){Uc=t}function Eb(t){qc=t}function Tb(){return Uc}function Rb(t){ks=t}function Cb(t){let e=tr(t);for(let n of Fc)if(n.test(e))return n;return null}function Ab(t){let e=tr(t);if(/ssh\s/.test(e)&&kf(e))return!1;for(let n of Tf)if(n.test(e))return!0;return!1}function Ob(t){let e=tr(t);for(let n of Bc)if(n.test(e))return!0;return!1}function Mb(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=tr(t);if(!vb.test(e))return null;for(let n of vf)if(n.test(e))return n;return null}function Nb(t,e={}){if(Uc)return Promise.resolve(!0);if(qc)return qc(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return Pb(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(s=>{let o=0;ks&&ks.pause();let r=global._nexRawWrite||(f=>process.stdout.write(f)),i=()=>{let f=process.stdout.rows||24;return Math.max(1,f-n.length-2)},a=()=>{let f=i();global._nexRawWrite&&f>1&&global._nexRawWrite(`\x1B[1;${f-1}r`);let p=`\x1B[${f};1H\x1B[2K${Rn.yellow}${t}${Rn.reset}`;for(let m=0;m<n.length;m++){let h=m===o,g=h?`${Rn.yellow}\u276F${Rn.reset}`:" ",$=h?`${Rn.yellow}${n[m]}${Rn.reset}`:n[m];p+=`\x1B[${f+1+m};1H\x1B[2K ${g} ${$}`}r(p)},c=f=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",d);let p=global._nexRawWrite||(g=>process.stdout.write(g)),m=i(),h="";for(let g=0;g<n.length+1;g++)h+=`\x1B[${m+g};1H\x1B[2K`;p(h),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),ks&&ks.resume(),s(f)},u=f=>{if(f===1){c(!1);return}f===2&&e.toolName&&Ci(e.toolName),c(!0)},d=f=>{if(f[0]===3){c(!1);return}let p=f.toString();if(p==="\r"||p===`
|
|
55
|
+
`){u(o);return}if(p==="\x1B[A"){o=(o-1+n.length)%n.length,a();return}if(p==="\x1B[B"){o=(o+1)%n.length,a();return}let m=p.toLowerCase().trim();if(m==="y"){c(!0);return}if(m==="n"){c(!1);return}if(m==="a"&&e.toolName){Ci(e.toolName),c(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",d)})}function Pb(t,e){let n=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(s=>{let o=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(Ci(e.toolName),s(!0)):s(i!=="n")};if(ks)ks.question(`${Rn.yellow}${t} ${n}${Rn.reset}`,o);else{let r=bb.createInterface({input:process.stdin,output:process.stdout});r.question(`${Rn.yellow}${t} ${n}${Rn.reset}`,i=>{r.close(),o(i)})}})}var Ci=()=>{};function Lb(t){Ci=t}Rf.exports={sanitizeBashCommand:tr,FORBIDDEN_PATTERNS:Fc,SSH_FORBIDDEN_PATTERNS:Sf,BASH_PROTECTED_PATHS:vf,SSH_SAFE_PATTERNS:jc,isSSHReadOnly:kf,DANGEROUS_BASH:Tf,CRITICAL_BASH:Bc,NOTABLE_BASH:Ef,isForbidden:Cb,isSSHForbidden:Sb,isDangerous:Ab,isCritical:Ob,isBashPathForbidden:Mb,confirm:Nb,setAutoConfirm:kb,getAutoConfirm:Tb,setConfirmHook:Eb,setReadlineInterface:Rb,setAllowAlwaysHandler:Lb}});var ho=K((MO,Cf)=>{async function Ib(t,e){if(!t.response?.data)return t.message;let n=t.response.data;if(typeof n=="object"&&n!==null&&typeof n.pipe!="function")return e(n)||t.message;try{let s=await new Promise((r,i)=>{let a=[];n.on("data",c=>a.push(c)),n.on("end",()=>r(Buffer.concat(a).toString("utf8"))),n.on("error",i)}),o=JSON.parse(s);return e(o)||s||t.message}catch{return t.message}}var Wc=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,n,s={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,n,s={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};Cf.exports={BaseProvider:Wc,readStreamErrorBody:Ib}});var yo=K((NO,Of)=>{var mo=class{buildRequestBody(e){throw new Error("buildRequestBody() not implemented")}getEndpoint(){throw new Error("getEndpoint() not implemented")}formatTools(e){return e}normalizeResponse(e){throw new Error("normalizeResponse() not implemented")}createStreamParser(e,n={}){throw new Error("createStreamParser() not implemented")}},go=class{constructor(e,n={}){this.onToken=e,this.callbacks=n,this.content="",this.buffer=""}feed(e){this.buffer+=e;let n=this.buffer.split(`
|
|
56
|
+
`);this.buffer=n.pop()||"";for(let s of n){let o=this.parseLine(s);if(o?.done)return o}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},Ai=class extends go{constructor(e,n={}){super(e,n),this.toolCallsMap={}}parseLine(e){let n=e.trim();if(!n||!n.startsWith("data: "))return{done:!1};let s=n.slice(6);if(s==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(s)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a=i.index??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}}))}}},Oi=class extends mo{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:n,tools:s,maxTokens:o,temperature:r,stream:i}){let a={model:e,messages:n,max_tokens:o,temperature:r};return i&&(a.stream=!0),s&&s.length>0&&(a.tools=s),a}normalizeResponse(e){let n=e.choices?.[0]?.message||{},s=(n.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:n.content||"",tool_calls:s}}createStreamParser(e,n={}){return new Ai(e,n)}},Mi=class extends go{constructor(e,n={}){super(e,n),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let n=e.trim();if(!n.startsWith("data: "))return{done:!1};let s=n.slice(6),o;try{o=JSON.parse(s)}catch{return{done:!1}}switch(o.type){case"content_block_start":{let r=o.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=o.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let n={};if(e.inputJson)try{n=JSON.parse(e.inputJson)}catch{n=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:n}}})}}},Hc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",Ni=class extends mo{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:n,tools:s,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:n,max_tokens:o,temperature:r};if(i&&(c.stream=!0),a?.system){let u=a.system,d=u.indexOf(Hc);if(d!==-1){let f=u.slice(0,d).trimEnd(),p=u.slice(d+Hc.length).trimStart();c.system=[{type:"text",text:f},{type:"text",text:p,cache_control:{type:"ephemeral"}}]}else c.system=u}return s&&s.length>0&&(c.tools=s),c}formatTools(e){return!e||e.length===0?[]:e.map(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let n="",s=[];for(let o of e.content||[])o.type==="text"?n+=o.text:o.type==="tool_use"&&s.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:n,tool_calls:s}}createStreamParser(e,n={}){return new Mi(e,n)}};function Af(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 Pi=class extends go{constructor(e,n={}){super(e,n),this.toolCalls=[],this.onThinkingToken=n.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let n;try{n=JSON.parse(e)}catch{return{done:!1}}return n.message?.thinking&&this.onThinkingToken(n.message.thinking),n.message?.content&&(this.onToken(n.message.content),this.content+=n.message.content),n.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(n.message.tool_calls)),n.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,n)=>({id:e.id||`ollama-${Date.now()}-${n}`,function:{name:e.function?.name||e.name||"unknown",arguments:Af(e.function?.arguments??e.arguments)}}))}}},Li=class extends mo{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:n,tools:s,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:n,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:a?.repeat_penalty??1.05}};return s&&s.length>0&&(c.tools=s),c}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:(n.tool_calls||[]).map((s,o)=>({id:s.id||`ollama-${Date.now()}-${o}`,function:{name:s.function?.name||s.name||"unknown",arguments:Af(s.function?.arguments??s.arguments)}}))}}createStreamParser(e,n={}){return new Pi(e,n)}},Db=new Oi,jb=new Ni,qb=new Li;Of.exports={ANTHROPIC_CACHE_BOUNDARY:Hc,WireProtocol:mo,StreamParser:go,OpenAICompatibleProtocol:Oi,AnthropicProtocol:Ni,OllamaChatProtocol:Li,OpenAIStreamParser:Ai,AnthropicStreamParser:Mi,OllamaStreamParser:Pi,openaiProtocol:Db,anthropicProtocol:jb,ollamaProtocol:qb}});var Pf=K((PO,Nf)=>{var Ii=require("axios"),Fb=require("http"),Bb=require("https"),{BaseProvider:Ub,readStreamErrorBody:Wb}=ho(),{ollamaProtocol:Es}=yo(),Di=new Fb.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),ji=new Bb.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Mf={"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}},Yc=class extends Ub{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Mf,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){Ii.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Di,httpsAgent:ji}).then(e=>{let n=e.data?.models||[];for(let s of n){let o=(s.name||s.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:s.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await Ii.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Di,httpsAgent:ji})).data?.models||[];for(let s of n){let o=(s.name||s.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:s.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(n=>{if(Array.isArray(n.content)){let s=[],o=[];for(let i of n.content)i.type==="text"?s.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:n.role,content:s.join(`
|
|
57
|
+
`)};return o.length>0&&(r.images=o),n.tool_call_id&&(r.tool_call_id=n.tool_call_id),r}return n})}async chat(e,n,s={}){await this.discoverModels();let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,a=Es.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!1,extra:{repeat_penalty:s.repeat_penalty}}),c;try{c=await Ii.post(`${this.baseUrl}${Es.getEndpoint()}`,a,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Di,httpsAgent:ji})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return Es.normalizeResponse(c.data)}async stream(e,n,s={}){await this.discoverModels();let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,a=s.onToken||(()=>{}),c=s.onThinkingToken||(()=>{}),u=Es.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!0,extra:{repeat_penalty:s.repeat_penalty}}),d;try{d=await Ii.post(`${this.baseUrl}${Es.getEndpoint()}`,u,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal,httpAgent:Di,httpsAgent:ji})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",h=await Wb(p,$=>$?.error),g=new Error(`API Error${m}: ${h}`);throw g.code=p.code||(p.response?.status?`HTTP_${p.response.status}`:void 0),g}let f=Es.createStreamParser(a,{onThinkingToken:c});return new Promise((p,m)=>{s.signal&&s.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",h=>{let{done:g,result:$}=f.feed(h.toString());g&&p($)}),d.data.on("error",h=>{if(s.signal?.aborted)return;let g=new Error(`Stream error: ${h.message}`);g.code=h.code||h.name,m(g)}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return Es.normalizeResponse(e)}};Nf.exports={OllamaProvider:Yc,OLLAMA_MODELS:Mf}});var jf=K((LO,Df)=>{var Lf=require("axios"),{BaseProvider:Hb,readStreamErrorBody:Yb}=ho(),{openaiProtocol:Ts}=yo(),If={"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}},Gc=class extends Hb{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||If,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let s of e){if(this._messageFormatCache.has(s)){n.push(this._messageFormatCache.get(s));continue}let o=this._getMessageCacheKey(s);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(s,i),n.push(i);continue}let r=this._formatSingleMessage(s);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(s,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool"){let n;return Array.isArray(e.content)?n=e.content.filter(o=>o.type==="text").map(o=>o.text).join(`
|
|
58
|
+
`)||JSON.stringify(e.content):n=typeof e.content=="string"?e.content:JSON.stringify(e.content),{role:"tool",content:n,tool_call_id:e.tool_call_id}}if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let s of e.content)if(s.type==="text")n.push({type:"text",text:s.text??""});else if(s.type==="image"&&s.data){let o=s.data.startsWith("data:")?s.data:`data:${s.media_type||"image/png"};base64,${s.data}`;n.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),c=Ts.buildRequestBody({model:o,messages:a,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!1}),u;try{u=await Lf.post(`${this.baseUrl}${Ts.getEndpoint()}`,c,{timeout:s.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return Ts.normalizeResponse(u.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,a=s.onToken||(()=>{}),{messages:c}=this.formatMessages(e),u=Ts.buildRequestBody({model:o,messages:c,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!0}),d;try{d=await Lf.post(`${this.baseUrl}${Ts.getEndpoint()}`,u,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",h=await Yb(p,g=>g?.error?.message||g?.error);throw new Error(`API Error${m}: ${h}`)}let f=Ts.createStreamParser(a);return new Promise((p,m)=>{s.signal&&s.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",h=>{let{done:g,result:$}=f.feed(h.toString());g&&p($)}),d.data.on("error",h=>{s.signal?.aborted||m(new Error(`Stream error: ${h.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return Ts.normalizeResponse(e)}};Df.exports={OpenAIProvider:Gc,OPENAI_MODELS:If}});var Uf=K((IO,Bf)=>{var qf=require("axios"),{BaseProvider:Gb,readStreamErrorBody:Kb}=ho(),{anthropicProtocol:ss}=yo(),Ff={"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}},zb="2023-06-01",Kc=class extends Gb{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Ff,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||zb}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n="",s=[];for(let o of e){if(o.role==="system"){n+=(n?`
|
|
59
|
+
|
|
60
|
+
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){s.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,s);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}s.push(r)}}for(let o=s.length-1;o>0;o--)s[o].role==="user"&&s[o-1].role==="user"&&s.splice(o,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:s,system:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let s=[];if(e.content&&s.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)s.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:s.length>0?s:[{type:"text",text:""}]}}if(e.role==="tool"){let s=n[n.length-1],o;if(Array.isArray(e.content)){let i=[];for(let a of e.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});o=i}else o=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:o};return s&&s.role==="user"&&Array.isArray(s.content)&&s.content[0]?.type==="tool_result"?(s.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let s=[];for(let o of e.content)o.type==="text"?s.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&s.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:s}}return{role:"user",content:e.content}}formatTools(e){return ss.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=s.maxTokens||i?.maxTokens||8192,{messages:c,system:u}=this.formatMessages(e),d=this.formatTools(n),f=ss.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:s.temperature??this.temperature,stream:!1,extra:{system:u}}),p;try{p=await qf.post(`${this.baseUrl}${ss.getEndpoint()}`,f,{timeout:s.timeout||this.timeout,headers:this._getHeaders()})}catch(m){if(m.name==="CanceledError"||m.name==="AbortError"||m.code==="ERR_CANCELED")throw m;let h=m.response?.status?` [HTTP ${m.response.status}]`:"",g=m.response?.data?.error?.message||m.response?.data?.error||m.message;throw new Error(`API Error${h}: ${g}`)}return ss.normalizeResponse(p.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=s.maxTokens||i?.maxTokens||8192,c=s.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f=this.formatTools(n),p=ss.buildRequestBody({model:r,messages:u,tools:f,maxTokens:a,temperature:s.temperature??this.temperature,stream:!0,extra:{system:d}}),m;try{m=await qf.post(`${this.baseUrl}${ss.getEndpoint()}`,p,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let $=g.response?.status?` [HTTP ${g.response.status}]`:"",w=await Kb(g,k=>k?.error?.message||k?.error);throw new Error(`API Error${$}: ${w}`)}let h=ss.createStreamParser(c);return new Promise((g,$)=>{s.signal&&s.signal.addEventListener("abort",()=>{m.data.destroy(),$(new DOMException("The operation was aborted","AbortError"))},{once:!0}),m.data.on("data",w=>{let{done:k,result:E}=h.feed(w.toString());k&&g(E)}),m.data.on("error",w=>{s.signal?.aborted||$(new Error(`Stream error: ${w.message}`))}),m.data.on("end",()=>{g(h.flush())})})}normalizeResponse(e){return ss.normalizeResponse(e)}};Bf.exports={AnthropicProvider:Kc,ANTHROPIC_MODELS:Ff}});var Gf=K((DO,Yf)=>{var Wf=require("axios"),{BaseProvider:Xb,readStreamErrorBody:Vb}=ho(),{openaiProtocol:Rs}=yo(),Hf={"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}},zc=class extends Xb{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Hf,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let s of e){if(this._messageFormatCache.has(s)){n.push(this._messageFormatCache.get(s));continue}let o=this._getMessageCacheKey(s);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(s,i),n.push(i);continue}let r=this._formatSingleMessage(s);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(s,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let s of e.content)if(s.type==="text")n.push({type:"text",text:s.text??""});else if(s.type==="image"&&s.data){let o=s.data.startsWith("data:")?s.data:`data:${s.media_type||"image/png"};base64,${s.data}`;n.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),c=Rs.buildRequestBody({model:o,messages:a,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!1}),u;try{u=await Wf.post(`${this.baseUrl}${Rs.getEndpoint()}`,c,{timeout:s.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return Rs.normalizeResponse(u.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||8192,a=s.onToken||(()=>{}),{messages:c}=this.formatMessages(e),u=Rs.buildRequestBody({model:o,messages:c,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!0}),d;try{d=await Wf.post(`${this.baseUrl}${Rs.getEndpoint()}`,u,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",h=await Vb(p,g=>g?.error?.message||g?.error);throw new Error(`API Error${m}: ${h}`)}let f=Rs.createStreamParser(a);return new Promise((p,m)=>{s.signal&&s.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",h=>{let{done:g,result:$}=f.feed(h.toString());g&&p($)}),d.data.on("error",h=>{s.signal?.aborted||m(new Error(`Stream error: ${h.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return Rs.normalizeResponse(e)}};Yf.exports={GeminiProvider:zc,GEMINI_MODELS:Hf}});var Xf=K((jO,zf)=>{var qi=require("axios"),{BaseProvider:Jb,readStreamErrorBody:Zb}=ho(),{ollamaProtocol:Cs}=yo(),Kf="http://localhost:11434",Xc=class extends Jb{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Kf,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let n=(await qi.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let s of n){let o=s.name||s.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let a=await qi.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:s.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let s=[],o=[];for(let i of n.content)i.type==="text"?s.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:s.join(`
|
|
61
|
+
`)};return o.length>0&&(r.images=o),r}return n})}async chat(e,n,s={}){this._modelsLoaded||await this.loadModels();let o=s.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=Cs.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:s.maxTokens||8192,temperature:s.temperature??this.temperature,stream:!1}),i;try{i=await qi.post(`${this.baseUrl}${Cs.getEndpoint()}`,r,{timeout:s.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let c=a.response?.status?` [HTTP ${a.response.status}]`:"",u=a.response?.data?.error||a.message;throw new Error(`API Error${c}: ${u}`)}return Cs.normalizeResponse(i.data)}async stream(e,n,s={}){this._modelsLoaded||await this.loadModels();let o=s.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=s.onToken||(()=>{}),i=Cs.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:s.maxTokens||8192,temperature:s.temperature??this.temperature,stream:!0}),a;try{a=await qi.post(`${this.baseUrl}${Cs.getEndpoint()}`,i,{timeout:s.timeout||this.timeout,responseType:"stream",signal:s.signal})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=await Zb(u,p=>p?.error);throw new Error(`API Error${d}: ${f}`)}let c=Cs.createStreamParser(r);return new Promise((u,d)=>{s.signal&&s.signal.addEventListener("abort",()=>{a.data.destroy(),d(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",f=>{let{done:p,result:m}=c.feed(f.toString());p&&u(m)}),a.data.on("error",f=>{s.signal?.aborted||d(new Error(`Stream error: ${f.message}`))}),a.data.on("end",()=>{u(c.flush())})})}normalizeResponse(e){return Cs.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let n=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return n?parseInt(n[1],10):null}};zf.exports={LocalProvider:Xc,DEFAULT_LOCAL_URL:Kf}});var Bn=K((qO,Jf)=>{"use strict";var Wt=require("fs"),Vf=require("path");function Qb(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function e_(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function t_(t,e){let n=Vf.dirname(t),s=Vf.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{Wt.existsSync(n)||Wt.mkdirSync(n,{recursive:!0,mode:448}),Wt.writeFileSync(s,e,{encoding:"utf-8",mode:384}),Wt.renameSync(s,t)}catch(o){try{Wt.unlinkSync(s)}catch{}throw o}}function n_(t,e,{timeout:n=5e3,retryMs:s=50}={}){let o=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=Wt.openSync(o,"wx"),Wt.writeSync(i,Buffer.from(String(process.pid))),Wt.closeSync(i),i=-1;try{return e()}finally{try{Wt.unlinkSync(o)}catch{}}}catch(a){if(i!==-1)try{Wt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let c=Wt.readFileSync(o,"utf-8").trim(),u=parseInt(c,10);if(!Qb(u)){try{Wt.unlinkSync(o)}catch{}continue}}catch(c){if(c.code&&c.code!=="ENOENT")throw c;continue}if(Date.now()>=r){try{Wt.unlinkSync(o)}catch{}return e()}e_(s)}}}Jf.exports={atomicWrite:t_,withFileLockSync:n_}});var wo=K((FO,rp)=>{var $o=require("fs"),Vc=require("path"),{T:Zf}=Rt(),{atomicWrite:s_,withFileLockSync:o_}=Bn(),Qf={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:{}},Fi=[],os={};function r_(t,e,n,s){if(Fi.push({provider:t,model:e,input:n,output:s}),os[t]!==void 0){let o=sp(t);o.allowed||process.stderr.write(`${Zf.yellow}\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}${Zf.reset}
|
|
62
|
+
`)}}function Jc(t,e){let n=Qf[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function ep(t){let e=Jc(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function tp(){let t={};for(let r of Fi){let i=`${r.provider}:${r.model}`;t[i]||(t[i]={provider:r.provider,model:r.model,input:0,output:0}),t[i].input+=r.input,t[i].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:ep(r)})),n=e.reduce((r,i)=>r+i.cost,0),s=e.reduce((r,i)=>r+i.input,0),o=e.reduce((r,i)=>r+i.output,0);return{totalCost:n,totalInput:s,totalOutput:o,breakdown:e}}function i_(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:s}=tp();if(s.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of s){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";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 + ${n.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
|
|
63
|
+
`)}function a_(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function c_(t,e,n,s){let o=Jc(t,e),r=(n*o.input+s*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function l_(){Fi=[]}function u_(t,e){os[t]=e}function d_(t){delete os[t]}function f_(){return{...os}}function np(t){let e=0;for(let n of Fi)n.provider===t&&(e+=ep(n));return e}function sp(t){let e=np(t),n=os[t];if(n===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let s=Math.max(0,n-e);return{allowed:e<n,spent:e,limit:n,remaining:s}}function op(){let t=Vc.join(process.cwd(),".nex","config.json");if($o.existsSync(t))try{let e=JSON.parse($o.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(os={...e.costLimits})}catch{}}function p_(){let t=Vc.join(process.cwd(),".nex"),e=Vc.join(t,"config.json");$o.existsSync(t)||$o.mkdirSync(t,{recursive:!0}),o_(e,()=>{let n={};if($o.existsSync(e))try{n=JSON.parse($o.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=os,s_(e,JSON.stringify(n,null,2))})}function h_(){os={}}op();rp.exports={PRICING:Qf,trackUsage:r_,getSessionCosts:tp,formatCosts:i_,formatCostHint:c_,resetCosts:l_,getPricing:Jc,setCostLimit:u_,removeCostLimit:d_,getCostLimits:f_,getProviderSpend:np,checkBudget:sp,loadCostLimits:op,saveCostLimits:p_,resetCostLimits:h_,estimateTokens:a_}});var nr=K((BO,ip)=>{function Zc(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var m_=Zc();function g_(...t){Zc()&&console.log(...t)}function y_(...t){Zc()&&console.warn(...t)}ip.exports={DEBUG:m_,debugLog:g_,warnLog:y_}});var lp=K((UO,cp)=>{"use strict";var $_=new Set(["read_file","grep","glob","search_files","list_directory"]),w_=new Set(["write_file","edit_file","patch_file"]),b_=new Set(["bash"]),__=new Set(["web_search","web_fetch","perplexity_search"]);function ap(t,e){let n=0,s=0,o=0,r=0,i=0;for(let[a,c]of t)i+=c,$_.has(a)&&(n+=c),w_.has(a)&&(s+=c),b_.has(a)&&(o+=c),__.has(a)&&(r+=c);return i===0?`Phase ${e}`:r/i>.5?"Research":n/i>.5?"Exploration":s/i>.3?"Implementation":o/i>.3&&s/i<.15?"Verification":`Phase ${e}`}var Qc=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,n,s,o){if(this._disabled)return null;this._stepsThisPhase++;for(let i of n)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:ap(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(s),filesModified:new Set(o)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};cp.exports={MilestoneTracker:Qc,_phaseName:ap}});var bo=K((WO,up)=>{var sr=We(),x_={"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 S_(){return sr.getActiveModel()}function v_(t){return sr.setActiveModel(t)}function k_(){return sr.getModelNames()}function E_(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let s=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(s)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let s=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(s)}catch{}let n=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)try{return JSON.parse(n[1].trim())}catch{}return null}async function T_(t,e){let{C:n}=Ye(),{Spinner:s}=Ye(),o=new s("Thinking...");o.start();let r=!0,i="";try{let a=await sr.callStream(t,e,{onToken:c=>{r&&(o.stop(),process.stdout.write(`${n.blue}`),r=!1),process.stdout.write(c),i+=c}});return r?o.stop():process.stdout.write(`${n.reset}
|
|
64
|
+
`),a}catch(a){throw o.stop(),a}}async function R_(t,e){return sr.callChat(t,e)}up.exports={MODELS:x_,getActiveModel:S_,setActiveModel:v_,getModelNames:k_,callOllamaStream:T_,callOllama:R_,parseToolArgs:E_}});var pp=K((YO,fp)=>{var Bi=require("path"),{C:U}=Ye(),{T:el,isDark:HO}=Rt(),{confirm:C_,getAutoConfirm:A_}=_t(),dp=2e3;function or(t,e){let n=t.split(`
|
|
65
65
|
`),s=e.split(`
|
|
66
66
|
`),o=[],r=n.length,i=s.length;if(r>dp||i>dp){for(let f of n)o.push({type:"remove",line:f});for(let f of s)o.push({type:"add",line:f});return o}let a=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let f=1;f<=r;f++)for(let p=1;p<=i;p++)n[f-1]===s[p-1]?a[f][p]=a[f-1][p-1]+1:a[f][p]=Math.max(a[f-1][p],a[f][p-1]);let c=r,u=i,d=[];for(;c>0||u>0;)c>0&&u>0&&n[c-1]===s[u-1]?(d.unshift({type:"same",line:n[c-1]}),c--,u--):u>0&&(c===0||a[c][u-1]>=a[c-1][u])?(d.unshift({type:"add",line:s[u-1]}),u--):(d.unshift({type:"remove",line:n[c-1]}),c--);return d}function O_(t,e,n,s=3){console.log(`
|
|
67
67
|
${U.bold}${U.cyan} Diff: ${t}${U.reset}`);let o=or(e,n),r=[];if(o.forEach((c,u)=>{c.type!=="same"&&r.push(u)}),r.length===0){console.log(`${U.gray} (no changes)${U.reset}`);return}let i=Math.max(0,r[0]-s),a=Math.min(o.length,r[r.length-1]+s+1);i>0&&console.log(`${U.gray} ...${U.reset}`);for(let c=i;c<a;c++){let u=o[c];switch(u.type){case"remove":console.log(`${U.red} - ${u.line}${U.reset}`);break;case"add":console.log(`${U.green} + ${u.line}${U.reset}`);break;default:console.log(`${U.gray} ${u.line}${U.reset}`)}}a<o.length&&console.log(`${U.gray} ...${U.reset}`),console.log()}function M_(t,e,n){console.log(`
|
|
@@ -71,42 +71,42 @@ ${U.bold}${U.cyan} New file: ${t}${U.reset}`);let n=e.split(`
|
|
|
71
71
|
${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=or(e,n),a=[],c=0;for(;c<i.length;)if(i[c].type==="same")a.push({left:i[c].line,right:i[c].line,type:"same"}),c++;else if(i[c].type==="remove"){let m=[];for(;c<i.length&&i[c].type==="remove";)m.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(m.length,h.length);for(let $=0;$<g;$++)a.push({left:$<m.length?m[$]:"",right:$<h.length?h[$]:"",type:"changed"})}else i[c].type==="add"&&(a.push({left:"",right:i[c].line,type:"changed"}),c++);let u=a.map((m,h)=>m.type!=="same"?h:-1).filter(m=>m>=0);if(u.length===0){console.log(` ${U.gray}(no changes)${U.reset}`);return}let d=Math.max(0,u[0]-2),f=Math.min(a.length,u[u.length-1]+3),p=(m,h)=>{let g=m.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=h?m.substring(0,h):m+" ".repeat(h-g.length)};d>0&&console.log(` ${U.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${U.reset}`);for(let m=d;m<f;m++){let h=a[m];if(h.type==="same")console.log(` ${U.gray}${p(h.left,r)}${U.reset}\u2502${U.gray}${p(h.right,r)}${U.reset}`);else{let g=h.left?`${U.red}${p(h.left,r)}${U.reset}`:`${p("",r)}`,$=h.right?`${U.green}${p(h.right,r)}${U.reset}`:`${p("",r)}`;console.log(` ${g}\u2502${$}`)}}f<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}
|
|
72
72
|
`)}function I_(t,e,n,s={}){let o=s.label||"Update",r=s.context||3,i=s.annotations||[],a=Bi.isAbsolute(t)?Bi.relative(process.cwd(),t):t,c=or(e,n),u=1,d=1;for(let C of c)C.type==="same"?(C.oldLine=u++,C.newLine=d++):C.type==="remove"?(C.oldLine=u++,C.newLine=null):(C.oldLine=null,C.newLine=d++);let f=0,p=0;for(let C of c)C.type==="add"?f++:C.type==="remove"&&p++;if(console.log(`
|
|
73
73
|
${U.green}\u23FA${U.reset} ${U.bold}${o}(${a})${U.reset}`),f===0&&p===0){console.log(` ${U.dim}\u23BF (no changes)${U.reset}
|
|
74
|
-
`);return}let m=[];if(f>0&&m.push(`Added ${f} line${f!==1?"s":""}`),p>0&&m.push(`removed ${p} line${p!==1?"s":""}`),i.length>0){let C=i.filter(le=>le.severity==="error").length,H=i.filter(le=>le.severity==="warn").length,q=i.filter(le=>le.severity==="info").length,ie=[];C>0&&ie.push(`${U.red}${C} error${C!==1?"s":""}${U.dim}`),H>0&&ie.push(`${U.yellow}${H} warning${H!==1?"s":""}${U.dim}`),q>0&&ie.push(`${U.cyan}${q} info${q!==1?"s":""}${U.dim}`),m.push(`found ${ie.join(", ")}`)}console.log(` ${U.dim}\u23BF ${m.join(", ")}${U.reset}`);let g=[];c.forEach((C,H)=>{C.type!=="same"&&g.push(H)});let $=[],w=null,k=null;for(let C of g){let H=Math.max(0,C-r),q=Math.min(c.length-1,C+r);w===null?(w=H,k=q):(H<=k+1||($.push([w,k]),w=H),k=q)}w!==null&&$.push([w,k]);let E=" ",S=process.stdout.columns||120;function x(C,H,q){let ie=q.replace(/\x1b\[[0-9;]*m/g,""),le=q+" ".repeat(Math.max(0,S-ie.length));return`${C}${H}${le}${U.reset}`}for(let C=0;C<$.length;C++){C>0&&console.log(`${E}${U.dim}\xB7\xB7\xB7${U.reset}`);let[H,q]=$[C];for(let ie=H;ie<=q;ie++){let le=c[ie],te=le.newLine!=null?le.newLine:le.oldLine,T=String(te).padStart(4),Te=le.type!=="remove"?i.filter(G=>G.line===le.newLine):[];le.type==="remove"?console.log(x(
|
|
74
|
+
`);return}let m=[];if(f>0&&m.push(`Added ${f} line${f!==1?"s":""}`),p>0&&m.push(`removed ${p} line${p!==1?"s":""}`),i.length>0){let C=i.filter(le=>le.severity==="error").length,H=i.filter(le=>le.severity==="warn").length,q=i.filter(le=>le.severity==="info").length,ie=[];C>0&&ie.push(`${U.red}${C} error${C!==1?"s":""}${U.dim}`),H>0&&ie.push(`${U.yellow}${H} warning${H!==1?"s":""}${U.dim}`),q>0&&ie.push(`${U.cyan}${q} info${q!==1?"s":""}${U.dim}`),m.push(`found ${ie.join(", ")}`)}console.log(` ${U.dim}\u23BF ${m.join(", ")}${U.reset}`);let g=[];c.forEach((C,H)=>{C.type!=="same"&&g.push(H)});let $=[],w=null,k=null;for(let C of g){let H=Math.max(0,C-r),q=Math.min(c.length-1,C+r);w===null?(w=H,k=q):(H<=k+1||($.push([w,k]),w=H),k=q)}w!==null&&$.push([w,k]);let E=" ",S=process.stdout.columns||120;function x(C,H,q){let ie=q.replace(/\x1b\[[0-9;]*m/g,""),le=q+" ".repeat(Math.max(0,S-ie.length));return`${C}${H}${le}${U.reset}`}for(let C=0;C<$.length;C++){C>0&&console.log(`${E}${U.dim}\xB7\xB7\xB7${U.reset}`);let[H,q]=$[C];for(let ie=H;ie<=q;ie++){let le=c[ie],te=le.newLine!=null?le.newLine:le.oldLine,T=String(te).padStart(4),Te=le.type!=="remove"?i.filter(G=>G.line===le.newLine):[];le.type==="remove"?console.log(x(el.diff_rem_bg,U.red,`${E}${T} - ${le.line}`)):le.type==="add"?console.log(x(el.diff_add_bg,U.green,`${E}${T} + ${le.line}`)):console.log(`${E}${U.dim}${T} ${U.reset}${le.line}`);for(let G of Te){let z=U.cyan,fe="\u2139";G.severity==="error"?(z=U.red,fe="\u2716"):G.severity==="warn"&&(z=U.yellow,fe="\u26A0"),console.log(`${E} ${z}${fe} ${G.message}${U.reset}`)}}}console.log()}function D_(t,e,n={}){let s=Bi.isAbsolute(t)?Bi.relative(process.cwd(),t):t,o=e.split(`
|
|
75
75
|
`),r=n.annotations||[];console.log(`
|
|
76
|
-
${U.green}\u23FA${U.reset} ${U.bold}Create(${s})${U.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let f=r.filter(g=>g.severity==="error").length,p=r.filter(g=>g.severity==="warn").length,m=r.filter(g=>g.severity==="info").length,h=[];f>0&&h.push(`${U.red}${f} error${f!==1?"s":""}${U.dim}`),p>0&&h.push(`${U.yellow}${p} warning${p!==1?"s":""}${U.dim}`),m>0&&h.push(`${U.cyan}${m} info${m!==1?"s":""}${U.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${U.dim}\u23BF ${i.join(", ")}${U.reset}`);let c=" ",u=process.stdout.columns||120,d=Math.min(o.length,20);for(let f=0;f<d;f++){let p=String(f+1).padStart(4),m=f+1,h=r.filter(k=>k.line===m),g=`${c}${p} + ${o[f]}`,$=g.replace(/\x1b\[[0-9;]*m/g,""),w=g+" ".repeat(Math.max(0,u-$.length));console.log(`${
|
|
77
|
-
`).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),s=e.substring(3);return{status:n,file:s}})}catch{return[]}}async function Wi(t=!1){return await
|
|
76
|
+
${U.green}\u23FA${U.reset} ${U.bold}Create(${s})${U.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let f=r.filter(g=>g.severity==="error").length,p=r.filter(g=>g.severity==="warn").length,m=r.filter(g=>g.severity==="info").length,h=[];f>0&&h.push(`${U.red}${f} error${f!==1?"s":""}${U.dim}`),p>0&&h.push(`${U.yellow}${p} warning${p!==1?"s":""}${U.dim}`),m>0&&h.push(`${U.cyan}${m} info${m!==1?"s":""}${U.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${U.dim}\u23BF ${i.join(", ")}${U.reset}`);let c=" ",u=process.stdout.columns||120,d=Math.min(o.length,20);for(let f=0;f<d;f++){let p=String(f+1).padStart(4),m=f+1,h=r.filter(k=>k.line===m),g=`${c}${p} + ${o[f]}`,$=g.replace(/\x1b\[[0-9;]*m/g,""),w=g+" ".repeat(Math.max(0,u-$.length));console.log(`${el.diff_add_bg}${U.green}${w}${U.reset}`);for(let k of h){let E=U.cyan,S="\u2139";k.severity==="error"?(E=U.red,S="\u2716"):k.severity==="warn"&&(E=U.yellow,S="\u26A0"),console.log(`${c} ${E}${S} ${k.message}${U.reset}`)}}o.length>20&&console.log(`${c}${U.dim} ...+${o.length-20} more lines${U.reset}`),console.log()}fp.exports={diffLines:or,showEditDiff:O_,showWriteDiff:M_,showNewFilePreview:N_,confirmFileChange:P_,showSideBySideDiff:L_,showDiff:I_,showNewFile:D_}});var rs=K((GO,gp)=>{var hp=require("util").promisify(require("child_process").exec),j_=require("util").promisify(require("child_process").execFile),{C:et}=Ye();async function tl(t){try{let{stdout:e}=await hp(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Ui(...t){try{let{stdout:e}=await j_("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function q_(){return await tl("git rev-parse --is-inside-work-tree")==="true"}async function F_(){return await tl("git branch --show-current")}async function nl(){try{let{stdout:t}=await hp("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
77
|
+
`).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),s=e.substring(3);return{status:n,file:s}})}catch{return[]}}async function Wi(t=!1){return await tl(`git diff ${t?"--cached":""}`)||""}async function sl(){return(await nl()).map(e=>e.file)}async function mp(){let t=await sl();if(t.length===0)return null;let e=await Wi(),s=await Wi(!0)||e,o=0,r=0;if(s){let d=s.split(`
|
|
78
78
|
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.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(d=>d.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 B_(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Ui("checkout","-b",n)!==null?n:null}async function U_(t){return await Ui("add","-A"),await Ui("commit","-m",t)?await Ui("rev-parse","--short","HEAD"):null}async function W_(){let t=await mp();if(!t)return`${et.dim}No changes${et.reset}`;let e=[];e.push(`
|
|
79
79
|
${et.bold}${et.cyan}Git Diff Summary:${et.reset}`),e.push(` ${et.green}+${t.stats.additions}${et.reset} ${et.red}-${t.stats.deletions}${et.reset} in ${t.files.length} file(s)`),e.push(`
|
|
80
80
|
${et.bold}${et.cyan}Files:${et.reset}`);for(let n of t.files.slice(0,20))e.push(` ${et.dim}${n}${et.reset}`);return t.files.length>20&&e.push(` ${et.dim}...+${t.files.length-20} more${et.reset}`),e.push(`
|
|
81
81
|
${et.bold}${et.cyan}Suggested message:${et.reset}`),e.push(` ${et.cyan}${t.summary}${et.reset}
|
|
82
82
|
`),e.join(`
|
|
83
|
-
`)}async function H_(){return(await
|
|
83
|
+
`)}async function H_(){return(await nl()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Y_(){let t=await sl();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let s of t.slice(0,10))e.push(` ${s}`);let n=await Wi();if(n){let s=n.length>5e3?n.substring(0,5e3)+`
|
|
84
84
|
...(truncated)`:n;e.push(`
|
|
85
85
|
DIFF:
|
|
86
86
|
${s}`)}return e.join(`
|
|
87
|
-
`)}gp.exports={isGitRepo:q_,getCurrentBranch:F_,getStatus:
|
|
88
|
-
`).map(n=>{let s=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!s)return null;let o=s[2].trim();return o.startsWith(Hi)?{index:parseInt(s[1],10),label:o,shortName:o.replace(`${Hi}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function ox(t,e=process.cwd()){try{let n=xp(e);if(n.length===0)return{ok:!1,error:"No snapshots found"};let s;return t===void 0||t==="last"?s=n[0]:typeof t=="number"?s=n.find(o=>o.index===t):s=n.find(o=>o.label===t||o.shortName===t||o.shortName.includes(String(t))),s?(wp("git",["stash","apply",`stash@{${s.index}}`],{cwd:e,timeout:15e3}),{ok:!0,label:s.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(n){return{ok:!1,error:n.message}}}Sp.exports={recordChange:z_,undo:X_,redo:V_,getHistory:J_,getUndoCount:Z_,getRedoCount:Q_,clearHistory:ex,persistEntry:_p,loadPersistedHistory:tx,pruneHistory:nx,createSnapshot:sx,listSnapshots:xp,restoreSnapshot:ox}});var Wn=K((XO,Cp)=>{var Ge=require("fs"),jt=require("path"),{atomicWrite:rx,withFileLockSync:ix}=Bn(),Ct=[];function rr(){return jt.join(process.cwd(),".nex","skills")}function vp(){return jt.join(process.cwd(),".nex","config.json")}function kp(){let t=rr();return Ge.existsSync(t)||Ge.mkdirSync(t,{recursive:!0}),t}function
|
|
89
|
-
`)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?o.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:o,body:s}}function
|
|
87
|
+
`)}gp.exports={isGitRepo:q_,getCurrentBranch:F_,getStatus:nl,getDiff:Wi,getChangedFiles:sl,analyzeDiff:mp,createBranch:B_,commit:U_,formatDiffSummary:W_,getDiffContext:Y_,getMergeConflicts:H_}});var Un=K((zO,Sp)=>{var pt=require("fs").promises,KO=require("fs"),tn=require("path"),G_=require("crypto"),{execSync:ol,execFileSync:wp}=require("child_process"),K_=100*1024,bp=50,Dt=[],_o=[];function z_(t,e,n,s){for(Dt.push({tool:t,filePath:e,oldContent:n,newContent:s,timestamp:Date.now()});Dt.length>bp;)Dt.shift();_o.length=0,_p(Dt[Dt.length-1]).catch(()=>{})}async function X_(){if(Dt.length===0)return null;let t=Dt.pop();if(t.oldContent===null)try{await pt.unlink(t.filePath)}catch{}else await pt.writeFile(t.filePath,t.oldContent,"utf-8");return _o.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function V_(){if(_o.length===0)return null;let t=_o.pop();return await pt.writeFile(t.filePath,t.newContent,"utf-8"),Dt.push(t),{tool:t.tool,filePath:t.filePath}}function J_(t=10){return Dt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Z_(){return Dt.length}function Q_(){return _o.length}function ex({diskToo:t=!0}={}){if(Dt.length=0,_o.length=0,t){let e=Yi();pt.readdir(e).then(n=>{for(let s of n)s.endsWith(".json")&&pt.unlink(tn.join(e,s)).catch(()=>{})}).catch(()=>{})}}function Yi(){return tn.join(process.cwd(),".nex","history")}async function yp(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=K_)return{inline:!0,content:t};let n=G_.createHash("sha256").update(t,"utf-8").digest("hex"),s=tn.join(e,"blobs");return await pt.mkdir(s,{recursive:!0}),await pt.writeFile(tn.join(s,n),t,"utf-8"),{inline:!1,hash:n}}async function _p(t){let e=Yi();await pt.mkdir(e,{recursive:!0});let n=tn.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),s=`${t.timestamp}-${n}.json`,o=await yp(t.oldContent,e),r=await yp(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 pt.writeFile(tn.join(e,s),JSON.stringify(i),"utf-8")}async function $p(t,e){if(!t)return null;if(t.inline)return t.content;let n=tn.join(e,"blobs",t.hash);return pt.readFile(n,"utf-8")}async function tx(){let t=Yi(),e;try{e=await pt.readdir(t)}catch{return 0}let n=e.filter(o=>o.endsWith(".json")).sort(),s=0;for(let o of n)try{let r=await pt.readFile(tn.join(t,o),"utf-8"),i=JSON.parse(r),a=await $p(i.oldContent,t),c=await $p(i.newContent,t);Dt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:c}),s++}catch{}for(;Dt.length>bp;)Dt.shift();return s}async function nx(t=7){let e=Yi(),n;try{n=await pt.readdir(e)}catch{return 0}let s=Date.now()-t*24*60*60*1e3,o=n.filter(u=>u.endsWith(".json")),r=0,i=new Set,a=[];for(let u of o)try{let d=await pt.readFile(tn.join(e,u),"utf-8"),f=JSON.parse(d);f.timestamp<s?(a.push(u),r++):(f.oldContent&&!f.oldContent.inline&&f.oldContent.hash&&i.add(f.oldContent.hash),f.newContent&&!f.newContent.inline&&f.newContent.hash&&i.add(f.newContent.hash))}catch{}for(let u of a)try{await pt.unlink(tn.join(e,u))}catch{}let c=tn.join(e,"blobs");try{let u=await pt.readdir(c);for(let d of u)if(!i.has(d))try{await pt.unlink(tn.join(c,d))}catch{}}catch{}return r}var Hi="nex-snapshot";function sx(t,e=process.cwd()){let n=t?`${Hi}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Hi}-${Date.now()}`;try{return ol("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(wp("git",["stash","push","-u","-m",n],{cwd:e,timeout:15e3}),ol("git stash pop",{cwd:e,timeout:1e4}),{name:n,label:n,ok:!0}):{name:n,label:n,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(s){return{name:n,label:n,ok:!1,error:s.message}}}function xp(t=process.cwd()){try{let e=ol("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
|
|
88
|
+
`).map(n=>{let s=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!s)return null;let o=s[2].trim();return o.startsWith(Hi)?{index:parseInt(s[1],10),label:o,shortName:o.replace(`${Hi}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function ox(t,e=process.cwd()){try{let n=xp(e);if(n.length===0)return{ok:!1,error:"No snapshots found"};let s;return t===void 0||t==="last"?s=n[0]:typeof t=="number"?s=n.find(o=>o.index===t):s=n.find(o=>o.label===t||o.shortName===t||o.shortName.includes(String(t))),s?(wp("git",["stash","apply",`stash@{${s.index}}`],{cwd:e,timeout:15e3}),{ok:!0,label:s.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(n){return{ok:!1,error:n.message}}}Sp.exports={recordChange:z_,undo:X_,redo:V_,getHistory:J_,getUndoCount:Z_,getRedoCount:Q_,clearHistory:ex,persistEntry:_p,loadPersistedHistory:tx,pruneHistory:nx,createSnapshot:sx,listSnapshots:xp,restoreSnapshot:ox}});var Wn=K((XO,Cp)=>{var Ge=require("fs"),jt=require("path"),{atomicWrite:rx,withFileLockSync:ix}=Bn(),Ct=[];function rr(){return jt.join(process.cwd(),".nex","skills")}function vp(){return jt.join(process.cwd(),".nex","config.json")}function kp(){let t=rr();return Ge.existsSync(t)||Ge.mkdirSync(t,{recursive:!0}),t}function al(){let t=vp();if(!Ge.existsSync(t))return[];try{let e=JSON.parse(Ge.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Ep(t){let e=vp(),n=jt.dirname(e);Ge.existsSync(n)||Ge.mkdirSync(n,{recursive:!0}),ix(e,()=>{let s={};if(Ge.existsSync(e))try{s=JSON.parse(Ge.readFileSync(e,"utf-8"))}catch{s={}}s.skills||(s.skills={}),s.skills.disabled=t,rx(e,JSON.stringify(s,null,2))})}function Tp(t,e){let n=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&n.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&n.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&n.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))n.push("commands must be an array");else for(let s=0;s<t.commands.length;s++){let o=t.commands[s];(!o.cmd||typeof o.cmd!="string")&&n.push(`commands[${s}].cmd must be a non-empty string`),o.handler!==void 0&&typeof o.handler!="function"&&n.push(`commands[${s}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))n.push("tools must be an array");else for(let s=0;s<t.tools.length;s++){let o=t.tools[s];(!o.function||!o.function.name||typeof o.function.name!="string")&&n.push(`tools[${s}].function.name must be a non-empty string`),o.execute!==void 0&&typeof o.execute!="function"&&n.push(`tools[${s}].execute must be a function`)}return{valid:n.length===0,errors:n}}function Rp(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let n=e[1],s=e[2].trim(),o=[],r=!1;for(let i of n.split(`
|
|
89
|
+
`)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?o.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:o,body:s}}function rl(t){try{let e=Ge.readFileSync(t,"utf-8").trim();if(!e)return null;let n=jt.basename(t,".md"),{triggers:s,body:o}=Rp(e);return{name:n,type:"prompt",filePath:t,instructions:o||e,triggers:s,commands:[],tools:[]}}catch{return null}}function il(t){try{let e=require(t),{valid:n,errors:s}=Tp(e,t);return n?{name:e.name||jt.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}
|
|
90
90
|
${s.join(`
|
|
91
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
91
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function cl(){Ct=[];let t=al(),e=rr(),n=[];if(Ge.existsSync(e))try{n=Ge.readdirSync(e)}catch{n=[]}for(let o of n){let r=jt.join(e,o),i;try{i=Ge.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;o.endsWith(".md")?a=rl(r):o.endsWith(".js")&&(a=il(r)),a&&(a.enabled=!t.includes(a.name),Ct.push(a))}let s=jt.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Ge.existsSync(s)){let o;try{o=Ge.readdirSync(s).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{o=[]}for(let r of o){let i=jt.join(s,r),a=jt.basename(r,jt.extname(r));if(Ct.some(d=>d.name===a))continue;let c;try{c=Ge.statSync(i)}catch{continue}if(!c.isFile())continue;let u=r.endsWith(".md")?rl(i):il(i);u&&(u._builtin=!0,u.enabled=!t.includes(u.name),Ct.push(u))}}return Ct}function ax(){let t=[];for(let e of Ct)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
92
92
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
93
93
|
${t.join(`
|
|
94
94
|
|
|
95
|
-
`)}`}function cx(){let t=[];for(let e of Ct)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function lx(){let t=[];for(let e of Ct)if(e.enabled)for(let n of e.tools)t.push({type:"function",function:{name:`skill_${n.function.name}`,description:`[Skill:${e.name}] ${n.function.description}`,parameters:n.function.parameters}});return t}async function ux(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let s of Ct)if(s.enabled){for(let o of s.tools)if(o.function.name===n&&o.execute)try{let r=await o.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${n}' failed: ${r.message}`}}return`ERROR: Skill tool '${n}' not found`}function dx(t){let[e,...n]=t.split(/\s+/),s=n.join(" ").trim();for(let o of Ct)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(s);if(typeof i=="string"&&i.length>0)return{handled:!0,agentPrompt:i}}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return{handled:!0}}}return!1}function fx(){return Ct.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 px(t){let e=Ct.find(s=>s.name===t);if(!e)return!1;e.enabled=!0;let n=
|
|
95
|
+
`)}`}function cx(){let t=[];for(let e of Ct)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function lx(){let t=[];for(let e of Ct)if(e.enabled)for(let n of e.tools)t.push({type:"function",function:{name:`skill_${n.function.name}`,description:`[Skill:${e.name}] ${n.function.description}`,parameters:n.function.parameters}});return t}async function ux(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let s of Ct)if(s.enabled){for(let o of s.tools)if(o.function.name===n&&o.execute)try{let r=await o.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${n}' failed: ${r.message}`}}return`ERROR: Skill tool '${n}' not found`}function dx(t){let[e,...n]=t.split(/\s+/),s=n.join(" ").trim();for(let o of Ct)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(s);if(typeof i=="string"&&i.length>0)return{handled:!0,agentPrompt:i}}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return{handled:!0}}}return!1}function fx(){return Ct.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 px(t){let e=Ct.find(s=>s.name===t);if(!e)return!1;e.enabled=!0;let n=al().filter(s=>s!==t);return Ep(n),!0}function hx(t){let e=Ct.find(s=>s.name===t);if(!e)return!1;e.enabled=!1;let n=al();return n.includes(t)||(n.push(t),Ep(n)),!0}function mx(){return Ct}async function gx(t,e={}){let{execFileSync:n}=require("child_process"),s=kp(),o=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(o=`https://github.com/${t}.git`);let r=e.name||jt.basename(o,".git").replace(/^nex-skill-/,""),i=jt.join(s,r);if(Ge.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:.@]+$/.test(o))throw new Error(`Invalid git URL: ${o}`);n("git",["clone","--depth","1",o,i],{timeout:3e4,stdio:"pipe"})}catch(d){return{ok:!1,name:r,error:`Git clone failed: ${d.stderr?.toString().trim()||d.message}`}}let a=jt.join(i,"skill.json"),c=Ge.existsSync(a),u=Ge.readdirSync(i).some(d=>(d.endsWith(".md")||d.endsWith(".js"))&&!d.startsWith("."));if(!c&&!u){try{Ge.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(c)try{let d=JSON.parse(Ge.readFileSync(a,"utf-8"));d.name||(d.name=r)}catch{try{Ge.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return cl(),{ok:!0,name:r}}async function yx(t){let e=require("axios");try{let n=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(o=>({name:o.name.replace(/^nex-skill-/,""),description:o.description||"(no description)",url:o.clone_url,stars:o.stargazers_count,owner:o.owner.login}))}catch(n){return[{name:"error",description:`Search failed: ${n.message}`,url:"",stars:0,owner:""}]}}function $x(t){let e=jt.join(rr(),t);if(!Ge.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${rr()}`};try{return Ge.rmSync(e,{recursive:!0,force:!0}),cl(),{ok:!0}}catch(n){return{ok:!1,error:n.message}}}function wx(t){if(!t)return[];let e=t.toLowerCase(),n=[];for(let s of Ct){if(!s.enabled||!s.triggers||s.triggers.length===0)continue;if(s.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(s.instructions||"").split(`
|
|
96
96
|
`).slice(0,3).join(`
|
|
97
|
-
`);n.push({name:s.name,instructions:r})}}return n}Cp.exports={initSkillsDir:kp,loadAllSkills:
|
|
97
|
+
`);n.push({name:s.name,instructions:r})}}return n}Cp.exports={initSkillsDir:kp,loadAllSkills:cl,getSkillInstructions:ax,getSkillCommands:cx,getSkillToolDefinitions:lx,routeSkillCall:ux,handleSkillCommand:dx,listSkills:fx,enableSkill:px,disableSkill:hx,getLoadedSkills:mx,installSkill:gx,searchSkills:yx,removeSkill:$x,matchSkillTriggers:wx,_getSkillsDir:rr,_validateScriptSkill:Tp,_loadMarkdownSkill:rl,_loadScriptSkill:il,_parseFrontmatter:Rp}});var Ki=K((VO,Lp)=>{var{spawn:bx}=require("child_process"),_x=require("path"),Ap=require("fs"),Hn=new Map;function xx(){return _x.join(process.cwd(),".nex","config.json")}function ll(){let t=xx();if(!Ap.existsSync(t))return{};try{return JSON.parse(Ap.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Gi(t,e,n={},s=1e4){return new Promise((o,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:n})+`
|
|
98
98
|
`,c="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},s);function d(p){c+=p.toString();let m=c.split(`
|
|
99
99
|
`);for(let h of m)if(h.trim())try{let g=JSON.parse(h);if(g.id===i){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):o(g.result);return}}catch{}c=m[m.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(a)}catch(p){f(),r(new Error(`MCP write failed: ${p.message}`))}})}async function Op(t,e){if(Hn.has(t))return Hn.get(t);let n=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],s={};for(let i of n)process.env[i]&&(s[i]=process.env[i]);let o=bx(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...s,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await Gi(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await Gi(o,"tools/list",{});return r.tools=i&&i.tools||[],Hn.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Mp(t){let e=Hn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Hn.delete(t),!0}function Sx(){for(let[t]of Hn)Mp(t)}async function Np(t,e,n={}){let s=Hn.get(t);if(!s)throw new Error(`MCP server not connected: ${t}`);let o=await Gi(s.proc,"tools/call",{name:e,arguments:n});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
100
|
-
`):JSON.stringify(o)}function Pp(){let t=[];for(let[e,n]of Hn)for(let s of n.tools)t.push({server:e,name:s.name,description:s.description||"",inputSchema:s.inputSchema||{type:"object",properties:{}}});return t}function vx(){return Pp().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function kx(t,e){if(!t.startsWith("mcp_"))return null;let n=t.substring(4).split("_");if(n.length<2)return null;let s=n[0],o=n.slice(1).join("_");return Np(s,o,e)}function Ex(){let t=
|
|
100
|
+
`):JSON.stringify(o)}function Pp(){let t=[];for(let[e,n]of Hn)for(let s of n.tools)t.push({server:e,name:s.name,description:s.description||"",inputSchema:s.inputSchema||{type:"object",properties:{}}});return t}function vx(){return Pp().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function kx(t,e){if(!t.startsWith("mcp_"))return null;let n=t.substring(4).split("_");if(n.length<2)return null;let s=n[0],o=n.slice(1).join("_");return Np(s,o,e)}function Ex(){let t=ll();return Object.entries(t).map(([e,n])=>{let s=Hn.get(e);return{name:e,command:n.command,connected:!!s,toolCount:s?s.tools.length:0}})}async function Tx(){let t=ll(),e=[];for(let[n,s]of Object.entries(t))try{let o=await Op(n,s);e.push({name:n,tools:o.tools.length})}catch(o){e.push({name:n,tools:0,error:o.message})}return e}Lp.exports={loadMCPConfig:ll,sendRequest:Gi,connectServer:Op,disconnectServer:Mp,disconnectAll:Sx,callTool:Np,getAllTools:Pp,getMCPToolDefinitions:vx,routeMCPCall:kx,listServers:Ex,connectAll:Tx}});var Xi=K((JO,qp)=>{var Ip=require("fs"),ul=require("path"),zi=[],ir=[],As={},ar=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function Dp(t,e){if(!t||!t.function||!t.function.name)return{ok:!1,error:"Tool definition must have function.name"};if(typeof e!="function")return{ok:!1,error:"Handler must be a function"};let n=t.function.name;return ir.some(s=>s.definition.function.name===n)?{ok:!1,error:`Tool "${n}" is already registered`}:(ir.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function jp(t,e){return ar.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(As[t]||(As[t]=[]),As[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${ar.join(", ")}`}}async function dl(t,e){let n=As[t]||[],s=e;for(let o of n)try{let r=await o(s);r!==void 0&&(s=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return s}function Rx(){let t=ul.join(process.cwd(),".nex","plugins"),e=[];if(!Ip.existsSync(t))return{loaded:0,errors:[]};let n=Ip.readdirSync(t).filter(o=>o.endsWith(".js")),s={registerTool:Dp,registerHook:jp,EVENTS:ar};for(let o of n){let r=ul.join(t,o);try{let i=require(r);if(typeof i=="function")i(s);else if(typeof i.setup=="function")i.setup(s);else{e.push(`${o}: Plugin must export a function or { setup: function }`);continue}zi.push({name:i.name||ul.basename(o,".js"),filePath:r})}catch(i){e.push(`${o}: ${i.message}`)}}return{loaded:zi.length,errors:e}}function Cx(){return ir.map(t=>t.definition)}async function Ax(t,e,n={}){let s=ir.find(a=>a.definition.function.name===t);if(!s)return null;let o=await dl("beforeToolExec",{name:t,args:e,options:n}),r=await s.handler(o.args||e,n);return(await dl("afterToolExec",{name:t,args:e,result:r})).result||r}function Ox(){return[...zi]}function Mx(){let t={};for(let e of ar)t[e]=(As[e]||[]).length;return t}function Nx(){zi.length=0,ir.length=0;for(let t of Object.keys(As))delete As[t]}qp.exports={registerTool:Dp,registerHook:jp,emit:dl,loadPlugins:Rx,getPluginToolDefinitions:Cx,executePluginTool:Ax,getLoadedPlugins:Ox,getHookCounts:Mx,clearPlugins:Nx,EVENTS:ar}});var fl=K((ZO,Wp)=>{var{getSkillToolDefinitions:Px}=Wn(),{getMCPToolDefinitions:Lx}=Ki(),{getPluginToolDefinitions:Ix}=Xi(),Vi=new Map;function Fp(){let{TOOL_DEFINITIONS:t}=fn();return[...t,...Px(),...Lx(),...Ix()]}function Bp(t){if(Vi.has(t))return Vi.get(t);let n=Fp().find(o=>o.function.name===t);if(!n)return null;let s=n.function.parameters;return Vi.set(t,s),s}function Dx(){Vi.clear()}function Ji(t,e){if(!t||e.length===0)return null;let n=null,s=1/0;for(let o of e){let r=Up(t.toLowerCase(),o.toLowerCase());r<s&&(s=r,n=o)}return s<=Math.ceil(t.length/2)?n:null}function Up(t,e){let n=t.length,s=e.length,o=Array.from({length:n+1},()=>Array(s+1).fill(0));for(let r=0;r<=n;r++)o[r][0]=r;for(let r=0;r<=s;r++)o[0][r]=r;for(let r=1;r<=n;r++)for(let i=1;i<=s;i++)o[r][i]=t[r-1]===e[i-1]?o[r-1][i-1]:1+Math.min(o[r-1][i],o[r][i-1],o[r-1][i-1]);return o[n][s]}function jx(t,e){let n=Bp(t);if(n===null){let f=Fp().map(m=>m.function.name),p=Ji(t,f);return{valid:!1,error:`Unknown tool "${t}".${p?` Did you mean "${p}"?`:""}
|
|
101
101
|
Available tools: ${f.join(", ")}`}}if(!n||!n.properties)return{valid:!0};let s=n.required||[],o=Object.keys(n.properties),r=Object.keys(e),i=[],a={...e},c=!1;for(let d of s)if(!(d in e)||e[d]===void 0||e[d]===null){let f=Ji(d,r);f&&!o.includes(f)?(a[d]=e[f],delete a[f],c=!0):i.push(`Missing required parameter "${d}" (${n.properties[d]?.description||n.properties[d]?.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(n.properties||{})&&(a.ignore_case=!0,delete a["-i"],delete a["--ignore-case"],c=!0),("-r"in a||"--recursive"in a)&&(delete a["-r"],delete a["--recursive"],c=!0)),t==="read_file"&&("offset"in a&&!("line_start"in a)&&(a.line_start=a.offset,delete a.offset,c=!0),"start_line"in a&&!("line_start"in a)&&(a.line_start=a.start_line,delete a.start_line,c=!0),"end_line"in a&&!("line_end"in a)&&(a.line_end=a.end_line,delete a.end_line,c=!0));for(let d of Object.keys(a))if(!o.includes(d)){let f=Ji(d,o);if(f&&!(f in a))a[f]=a[d],delete a[d],c=!0;else if(!c){let p=f?` Did you mean "${f}"?`:"";i.push(`Unknown parameter "${d}".${p}`)}}for(let d of Object.keys(a)){if(!n.properties[d])continue;let f=n.properties[d].type,p=typeof a[d];f==="string"&&p==="number"?(a[d]=String(a[d]),c=!0):f==="number"&&p==="string"&&!isNaN(a[d])?(a[d]=Number(a[d]),c=!0):f==="boolean"&&p==="string"&&(a[d]=a[d]==="true",c=!0)}return i.length>0&&!c?{valid:!1,error:`Tool "${t}" argument errors:
|
|
102
102
|
`+i.map(d=>` - ${d}`).join(`
|
|
103
103
|
`)+`
|
|
104
104
|
|
|
105
|
-
Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:c?a:null}}function qx(t,e){let n=[],s={...t};if(!s.function&&!s.name)return n.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:s,errors:n};if(!s.function&&s.name&&(s.function={name:s.name,arguments:s.arguments||s.args||{}},delete s.name,delete s.args),s.function&&s.function.args!==void 0&&s.function.arguments===void 0&&(s.function.arguments=s.function.args,delete s.function.args),s.function&&(s.function.arguments===void 0||s.function.arguments===null)&&(s.function.arguments={}),s.function&&typeof s.function.arguments=="string"){let o=s.function.arguments;if(o.trim()==="")s.function.arguments={};else try{s.function.arguments=JSON.parse(o)}catch(r){return n.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:s,errors:n}}}return s.function&&typeof s.function.arguments!="object"?(n.push(`Arguments must be an object, got ${typeof s.function.arguments}`),{valid:!1,normalized:s,errors:n}):!s.function.name||typeof s.function.name!="string"?(n.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:s,errors:n}):{valid:n.length===0,normalized:s,errors:n}}Wp.exports={validateToolArgs:jx,validateToolCallFormat:qx,closestMatch:Ji,levenshtein:Up,getCachedSchema:Bp,clearSchemaCache:Dx}});var Kp=K((QO,Gp)=>{var{levenshtein:Zi}=
|
|
105
|
+
Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:c?a:null}}function qx(t,e){let n=[],s={...t};if(!s.function&&!s.name)return n.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:s,errors:n};if(!s.function&&s.name&&(s.function={name:s.name,arguments:s.arguments||s.args||{}},delete s.name,delete s.args),s.function&&s.function.args!==void 0&&s.function.arguments===void 0&&(s.function.arguments=s.function.args,delete s.function.args),s.function&&(s.function.arguments===void 0||s.function.arguments===null)&&(s.function.arguments={}),s.function&&typeof s.function.arguments=="string"){let o=s.function.arguments;if(o.trim()==="")s.function.arguments={};else try{s.function.arguments=JSON.parse(o)}catch(r){return n.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:s,errors:n}}}return s.function&&typeof s.function.arguments!="object"?(n.push(`Arguments must be an object, got ${typeof s.function.arguments}`),{valid:!1,normalized:s,errors:n}):!s.function.name||typeof s.function.name!="string"?(n.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:s,errors:n}):{valid:n.length===0,normalized:s,errors:n}}Wp.exports={validateToolArgs:jx,validateToolCallFormat:qx,closestMatch:Ji,levenshtein:Up,getCachedSchema:Bp,clearSchemaCache:Dx}});var Kp=K((QO,Gp)=>{var{levenshtein:Zi}=fl(),Fx=200,Bx=.3,Ux=2;function pl(t){return t.replace(/\r\n/g,`
|
|
106
106
|
`).replace(/\r/g,`
|
|
107
107
|
`).replace(/\t/g," ".repeat(Ux)).split(`
|
|
108
108
|
`).map(e=>{let n=e.replace(/\s+$/,""),s=n.match(/^(\s*)(.*)/);if(!s)return n;let[,o,r]=s;return o+r.replace(/ {2,}/g," ")}).join(`
|
|
109
|
-
`)}function Wx(t,e){if(t.includes(e))return e;if(e.length<10)return null;let n=
|
|
109
|
+
`)}function Wx(t,e){if(t.includes(e))return e;if(e.length<10)return null;let n=pl(t),s=pl(e);if(!n.includes(s))return null;let o=t.split(`
|
|
110
110
|
`),r=n.split(`
|
|
111
111
|
`),i=s.split(`
|
|
112
112
|
`),a=i[0],c=i[i.length-1];for(let u=0;u<=r.length-i.length;u++){let d=!0;for(let f=0;f<i.length;f++)if(r[u+f]!==i[f]){d=!1;break}if(d)return o.slice(u,u+i.length).join(`
|
|
@@ -114,20 +114,20 @@ Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,correcte
|
|
|
114
114
|
`),o=e.split(`
|
|
115
115
|
`).length;return n.length===0||o===0?null:o===1?Yx(n,e):Kx(n,e,o)}function Hp(t){return Math.max(1,Math.floor(t/Fx))}function Yp(t,e){return t<=Math.ceil(e*Bx)}function Yx(t,e){let n=e.trim(),s=Hp(t.length),o=null,r=1/0;for(let i=0;i<t.length;i+=s){let a=t[i];if(!a.trim())continue;let c=Zi(a.trim(),n);c<r&&(r=c,o={text:a,distance:c,line:i+1})}return o&&s>1&&(o=Gx(t,n,o,s)||o,r=o.distance),Yp(r,e.length)?o:null}function Gx(t,e,n,s){let o=n.line-1,r=Math.max(0,o-s),i=Math.min(t.length-1,o+s),a=n.distance,c=null;for(let u=r;u<=i;u++){let d=t[u];if(!d.trim())continue;let f=Zi(d.trim(),e);f<a&&(a=f,c={text:d,distance:f,line:u+1})}return c}function Kx(t,e,n){let s=t.length-n+1;if(s<=0)return null;let o=Hp(s),r=null,i=1/0;for(let a=0;a<s;a+=o){let c=t.slice(a,a+n).join(`
|
|
116
116
|
`),u=Zi(c,e);u<i&&(i=u,r={text:c,distance:u,line:a+1})}return r&&o>1&&(r=zx(t,e,r,o,n,s)||r,i=r.distance),Yp(i,e.length)?r:null}function zx(t,e,n,s,o,r){let i=n.line-1,a=Math.max(0,i-s),c=Math.min(r-1,i+s),u=n.distance,d=null;for(let f=a;f<=c;f++){let p=t.slice(f,f+o).join(`
|
|
117
|
-
`),m=Zi(p,e);m<u&&(u=m,d={text:p,distance:m,line:f+1})}return d}Gp.exports={normalizeWhitespace:
|
|
118
|
-
`),s=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],a=r+1;for(let c of Xx)c.regex.test(i)&&s.push({line:a,message:`Potential secret detected: ${c.name}`,severity:"error"});for(let c of Vx)c.ext&&!c.ext.includes(o)||c.regex.test(i)&&s.push({line:a,message:c.message||`Found ${c.name}`,severity:c.severity||"warn"})}return n.length>500&&s.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),s}function Zx(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}zp.exports={runDiagnostics:Jx,getMemoryUsage:Zx}});var
|
|
119
|
-
`).filter(Boolean),
|
|
120
|
-
`);for(let o=0;o<s.length;o++){let r=s[o],i=o+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let c=r.match(/(?:export\s+)?class\s+(\w+)/);c&&n.push({type:"class",name:c[1],line:i});let u=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);u&&n.push({type:"function",name:u[1],line:i});let d=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(d){let p=d[1].split(",").map(m=>m.trim().split(":")[0].trim()).filter(Boolean);for(let m of p)/^\w+$/.test(m)&&n.push({type:"export",name:m,line:i})}let f=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(f){let p=f[1]||f[2];n.push({type:"import",name:p,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let c=r.match(/^class\s+(\w+)/);c&&n.push({type:"class",name:c[1],line:i});let u=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);u&&n.push({type:"import",name:u[1]||u[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let c=r.match(/^type\s+(\w+)\s+struct/);c&&n.push({type:"class",name:c[1],line:i})}}return n}async function eh(t){t=t||process.cwd();let e=So.join(t,".nex","index","content-index.json"),n={};if(
|
|
117
|
+
`),m=Zi(p,e);m<u&&(u=m,d={text:p,distance:m,line:f+1})}return d}Gp.exports={normalizeWhitespace:pl,fuzzyFindText:Wx,findMostSimilar:Hx}});var Xp=K((tM,zp)=>{var{C:eM}=Ye(),Xx=[{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}],Vx=[{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 Jx(t,e){let n=e.split(`
|
|
118
|
+
`),s=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],a=r+1;for(let c of Xx)c.regex.test(i)&&s.push({line:a,message:`Potential secret detected: ${c.name}`,severity:"error"});for(let c of Vx)c.ext&&!c.ext.includes(o)||c.regex.test(i)&&s.push({line:a,message:c.message||`Found ${c.name}`,severity:c.severity||"warn"})}return n.length>500&&s.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),s}function Zx(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}zp.exports={runDiagnostics:Jx,getMemoryUsage:Zx}});var $l=K((nM,th)=>{var xo=require("fs").promises,So=require("path"),{exec:Qx}=require("util").promisify(require("child_process").exec),vo=[],yl=null,Qi=!1,ml=0,eS=6e4;function Jp(t){return!(vo.length===0||yl!==t||Date.now()-ml>eS)}async function Zp(t){if(!Qi&&!Jp(t)){Qi=!0,yl=t;try{try{let{stdout:s}=await Qx("rg --files",{cwd:t,timeout:5e3});vo=s.split(`
|
|
119
|
+
`).filter(Boolean),ml=Date.now(),Qi=!1;return}catch{}let e=[],n=async(s,o)=>{let r;try{r=await xo.readdir(s,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=o?`${o}/${i.name}`:i.name;i.isDirectory()?await n(So.join(s,i.name),a):e.push(a)}};await n(t,""),vo=e,ml=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Qi=!1}}}function gl(){return vo}function tS(){return yl}function nS(t){return vo.filter(e=>So.basename(e)===t)}function sS(t){let e=t.toLowerCase();return vo.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}var hl=null,Vp=0,oS=12e4,rS=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Qp(t,e){let n=[],s=t.split(`
|
|
120
|
+
`);for(let o=0;o<s.length;o++){let r=s[o],i=o+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let c=r.match(/(?:export\s+)?class\s+(\w+)/);c&&n.push({type:"class",name:c[1],line:i});let u=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);u&&n.push({type:"function",name:u[1],line:i});let d=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(d){let p=d[1].split(",").map(m=>m.trim().split(":")[0].trim()).filter(Boolean);for(let m of p)/^\w+$/.test(m)&&n.push({type:"export",name:m,line:i})}let f=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(f){let p=f[1]||f[2];n.push({type:"import",name:p,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let c=r.match(/^class\s+(\w+)/);c&&n.push({type:"class",name:c[1],line:i});let u=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);u&&n.push({type:"import",name:u[1]||u[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let c=r.match(/^type\s+(\w+)\s+struct/);c&&n.push({type:"class",name:c[1],line:i})}}return n}async function eh(t){t=t||process.cwd();let e=So.join(t,".nex","index","content-index.json"),n={};if(hl&&Date.now()-Vp<oS)return hl;try{let i=await xo.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}gl().length===0&&await Zp(t);let o={files:{}},r=!1;for(let i of gl()){let a=So.extname(i);if(!rS.has(a))continue;let c=So.join(t,i);try{let d=(await xo.stat(c)).mtimeMs;if(n.files[i]&&n.files[i].mtime===d){o.files[i]=n.files[i];continue}let f=await xo.readFile(c,"utf-8"),p=Qp(f,a);o.files[i]={defs:p,mtime:d},r=!0}catch{}}if(r){let i=So.join(t,".nex","index");await xo.mkdir(i,{recursive:!0}),await xo.writeFile(e,JSON.stringify(o),"utf-8")}return hl=o,Vp=Date.now(),o}async function iS(t,e){let n=await eh(),s=[],o=t.toLowerCase();for(let[r,i]of Object.entries(n.files))for(let a of i.defs)e&&a.type!==e||a.name.toLowerCase().includes(o)&&s.push({file:r,type:a.type,name:a.name,line:a.line});return s.sort((r,i)=>{let a=r.name.toLowerCase()===o?0:1,c=i.name.toLowerCase()===o?0:1;if(a!==c)return a-c;let u=r.name.toLowerCase().startsWith(o)?0:1,d=i.name.toLowerCase().startsWith(o)?0:1;return u-d}),s.slice(0,50)}th.exports={refreshIndex:Zp,getFileIndex:gl,getIndexedCwd:tS,findFileInIndex:nS,searchIndex:sS,isIndexValid:Jp,buildContentIndex:eh,searchContentIndex:iS,extractDefinitions:Qp}});var ko=K((sM,rh)=>{var ea=require("fs"),na=require("path"),sa=require("os"),{execFile:aS}=require("child_process"),{promisify:cS}=require("util"),wl=cS(aS),lS=na.join(sa.homedir(),".nex","servers.json"),ta=na.join(sa.tmpdir(),"nex-ssh-sockets");function uS(){return na.join(process.cwd(),".nex","servers.json")}function nh(){let t=s=>{if(!ea.existsSync(s))return{};try{return JSON.parse(ea.readFileSync(s,"utf-8"))}catch{return{}}},e=t(lS),n=t(uS());return{...e,...n}}function dS(t){let e=nh();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:o}}let n=Object.keys(e),s=n.length?`Available profiles: ${n.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${s}`)}function fS(){ea.existsSync(ta)||ea.mkdirSync(ta,{recursive:!0})}function sh(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,sa.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),fS();let n=t.user?`${t.user}@${t.host}`:t.host,s=na.join(ta,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${s}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function oh(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,sa.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function pS(t,e,{timeout:n=3e4,sudo:s=!1}={}){let{args:o}=sh(t),r=s&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await wl("ssh",[...o,r],{timeout:n,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,c=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:c,exitCode:a,error:oa(c,t)}}}async function hS(t,e,n,{timeout:s=12e4}={}){let o=oh(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${n}`);try{let{stdout:i,stderr:a}=await wl("scp",o,{timeout:s,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(oa(a,t)||a)}}async function mS(t,e,n,{timeout:s=12e4}={}){let o=oh(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,n);try{let{stdout:i,stderr:a}=await wl("scp",o,{timeout:s,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(oa(a,t)||a)}}function oa(t,e){if(!t)return"";if(/connection refused/i.test(t)){let n=e.port||22;return`${t}
|
|
121
121
|
HINT: Connection refused on ${e.host}:${n}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${n} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let n=e.key?`key: ${e.key}`:"SSH agent";return`${t}
|
|
122
122
|
HINT: Auth failed using ${n} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
|
|
123
123
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
124
124
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
125
125
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
126
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function gS(t,e){let n=e.user?`${e.user}@${e.host}`:e.host,s=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${n}${s}${o}${r}${i}`}rh.exports={loadServerProfiles:nh,resolveProfile:dS,buildSSHArgs:sh,sshExec:pS,scpUpload:hS,scpDownload:mS,enrichSSHError:oa,formatProfile:gS,SSH_SOCKET_DIR:ta}});var
|
|
127
|
-
`,"utf-8")}ah.exports={loadDeployConfigs:ih,resolveDeployConfig:$S,saveDeployConfigs:wS,getDeployConfigPath:
|
|
126
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function gS(t,e){let n=e.user?`${e.user}@${e.host}`:e.host,s=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${n}${s}${o}${r}${i}`}rh.exports={loadServerProfiles:nh,resolveProfile:dS,buildSSHArgs:sh,sshExec:pS,scpUpload:hS,scpDownload:mS,enrichSSHError:oa,formatProfile:gS,SSH_SOCKET_DIR:ta}});var xl=K((oM,ah)=>{var cr=require("fs"),bl=require("path"),yS=bl.join(".nex","deploy.json");function _l(){return bl.join(process.cwd(),yS)}function ih(){let t=_l();if(!cr.existsSync(t))return{};try{return JSON.parse(cr.readFileSync(t,"utf-8"))}catch{return{}}}function $S(t){let e=ih();if(e[t])return{...e[t],_name:t};let n=Object.keys(e),s=n.length?`Available: ${n.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${s}`)}function wS(t){let e=bl.join(process.cwd(),".nex");cr.existsSync(e)||cr.mkdirSync(e,{recursive:!0}),cr.writeFileSync(_l(),JSON.stringify(t,null,2)+`
|
|
127
|
+
`,"utf-8")}ah.exports={loadDeployConfigs:ih,resolveDeployConfig:$S,saveDeployConfigs:wS,getDeployConfigPath:_l}});var fr=K((rM,uh)=>{var{getActiveModel:bS,getActiveProviderName:_S}=We(),lr={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},ur={"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"},dr={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Cn={};function lh(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(Cn=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{Cn={}}}lh();function Sl(){let e=bS()?.id,n=_S();return e&&Cn[e]?Cn[e]:n&&Cn[`${n}:*`]?Cn[`${n}:*`]:e&&ur[e]?ur[e]:n&&dr[n]?dr[n]:"full"}var xS=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"]),ch={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function SS(t,e){return t&&(xS.has(t)||t.startsWith("claude-"))?"strict":e&&ch[e]?ch[e]:"fuzzy"}function vS(t,e){return t&&Cn[t]?Cn[t]:e&&Cn[`${e}:*`]?Cn[`${e}:*`]:t&&ur[t]?ur[t]:e&&dr[e]?dr[e]:"full"}function kS(t,e){let n=e||Sl();if(n==="full"||!lr[n])return t;let s=new Set(lr[n]);return t.filter(o=>s.has(o.function.name))}function ES(){let t=Sl(),e=lr[t]?lr[t].length:"all";return{tier:t,toolCount:e}}uh.exports={filterToolsForModel:kS,getActiveTier:Sl,getModelTier:vS,getEditMode:SS,getTierInfo:ES,TIERS:lr,MODEL_TIERS:ur,PROVIDER_DEFAULT_TIER:dr,loadConfigOverrides:lh}});var Gn=K((iM,ph)=>{var vl=null,Yn=null,pr=null,dh=`Playwright is not installed. Install with:
|
|
128
128
|
npm install playwright && npx playwright install chromium
|
|
129
|
-
Then restart nex-code.`;function fh(){if(pr!==null)return pr;try{require("playwright"),pr=!0}catch{pr=!1}return pr}async function ra(){if(!fh())throw new Error(dh);return
|
|
130
|
-
...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function CS(t,{width:e=1280,height:n=800,fullPage:s=!1,timeout:o=3e4}={}){let i=await(await ra()).newPage();try{await i.setViewportSize({width:e,height:n}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let a=await i.screenshot({type:"png",fullPage:s}),c=require("os"),u=require("path"),d=require("fs"),f=u.join(c.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(f,a,{mode:384}),{path:f,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function AS(t,{selector:e,text:n,timeout:s=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await ra()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:s}),n?await r.getByText(n,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function OS(t,{selector:e,value:n,submit:s=!1,timeout:o=3e4}={}){if(!e||n===void 0)throw new Error("selector and value are required");let i=await(await ra()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(n)),s&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${s?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}ph.exports={isPlaywrightAvailable:fh,browserNavigate:RS,browserScreenshot:CS,browserClick:AS,browserFill:OS,closeBrowser:TS,INSTALL_MSG:dh}});var Sl=K((aM,mh)=>{"use strict";var MS=require("util"),hh=require("stream"),pn=mh.exports=function(){hh.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};MS.inherits(pn,hh);pn.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))};pn.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};pn.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()))};pn.prototype.destroySoon=pn.prototype.end;pn.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};pn.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};pn.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))};pn.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,s=Buffer.alloc(t.length);for(;e<t.length;){let o=this._buffers[n++],r=Math.min(o.length,t.length-e);o.copy(s,e,0,r),e+=r,r!==o.length&&(this._buffers[--n]=o.slice(r))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,s)};pn.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 kl=K(vl=>{"use strict";var is=[{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]}];vl.getImagePasses=function(t,e){let n=[],s=t%8,o=e%8,r=(t-s)/8,i=(e-o)/8;for(let a=0;a<is.length;a++){let c=is[a],u=r*c.x.length,d=i*c.y.length;for(let f=0;f<c.x.length&&c.x[f]<s;f++)u++;for(let f=0;f<c.y.length&&c.y[f]<o;f++)d++;u>0&&d>0&&n.push({width:u,height:d,index:a})}return n};vl.getInterlaceIterator=function(t){return function(e,n,s){let o=e%is[s].x.length,r=(e-o)/is[s].x.length*8+is[s].x[o],i=n%is[s].y.length,a=(n-i)/is[s].y.length*8+is[s].y[i];return r*4+a*t*4}}});var El=K((lM,gh)=>{"use strict";gh.exports=function(e,n,s){let o=e+n-s,r=Math.abs(o-e),i=Math.abs(o-n),a=Math.abs(o-s);return r<=i&&r<=a?e:i<=a?n:s}});var Tl=K((uM,$h)=>{"use strict";var NS=kl(),PS=El();function yh(t,e,n){let s=t*e;return n!==8&&(s=Math.ceil(s/(8/n))),s}var Eo=$h.exports=function(t,e){let n=t.width,s=t.height,o=t.interlace,r=t.bpp,i=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],o){let a=NS.getImagePasses(n,s);for(let c=0;c<a.length;c++)this._images.push({byteWidth:yh(a[c].width,r,i),height:a[c].height,lineIndex:0})}else this._images.push({byteWidth:yh(n,r,i),height:s,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Eo.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Eo.prototype._unFilterType1=function(t,e,n){let s=this._xComparison,o=s-1;for(let r=0;r<n;r++){let i=t[1+r],a=r>o?e[r-s]:0;e[r]=i+a}};Eo.prototype._unFilterType2=function(t,e,n){let s=this._lastLine;for(let o=0;o<n;o++){let r=t[1+o],i=s?s[o]:0;e[o]=r+i}};Eo.prototype._unFilterType3=function(t,e,n){let s=this._xComparison,o=s-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],c=r?r[i]:0,u=i>o?e[i-s]:0,d=Math.floor((u+c)/2);e[i]=a+d}};Eo.prototype._unFilterType4=function(t,e,n){let s=this._xComparison,o=s-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],c=r?r[i]:0,u=i>o?e[i-s]:0,d=i>o&&r?r[i-s]:0,f=PS(u,c,d);e[i]=a+f}};Eo.prototype._reverseFilterLine=function(t){let e=t[0],n,s=this._images[this._imageIndex],o=s.byteWidth;if(e===0)n=t.slice(1,o+1);else switch(n=Buffer.alloc(o),e){case 1:this._unFilterType1(t,n,o);break;case 2:this._unFilterType2(t,n,o);break;case 3:this._unFilterType3(t,n,o);break;case 4:this._unFilterType4(t,n,o);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),s.lineIndex++,s.lineIndex>=s.height?(this._lastLine=null,this._imageIndex++,s=this._images[this._imageIndex]):this._lastLine=n,s?this.read(s.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var _h=K((dM,bh)=>{"use strict";var LS=require("util"),wh=Sl(),IS=Tl(),DS=bh.exports=function(t){wh.call(this);let e=[],n=this;this._filter=new IS(t,{read:this.read.bind(this),write:function(s){e.push(s)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};LS.inherits(DS,wh)});var To=K((fM,xh)=>{"use strict";xh.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 Al=K((pM,Sh)=>{"use strict";var Rl=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;Rl[t]=e}})();var Cl=Sh.exports=function(){this._crc=-1};Cl.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Rl[(this._crc^t[e])&255]^this._crc>>>8;return!0};Cl.prototype.crc32=function(){return this._crc^-1};Cl.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Rl[(e^t[n])&255]^e>>>8;return e^-1}});var Ol=K((hM,vh)=>{"use strict";var it=To(),jS=Al(),lt=vh.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[it.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[it.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[it.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[it.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[it.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[it.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(){}};lt.prototype.start=function(){this.read(it.PNG_SIGNATURE.length,this._parseSignature.bind(this))};lt.prototype._parseSignature=function(t){let e=it.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};lt.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),s="";for(let r=4;r<8;r++)s+=String.fromCharCode(t[r]);let o=!!(t[4]&32);if(!this._hasIHDR&&n!==it.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new jS,this._crc.write(Buffer.from(s)),this._chunks[n])return this._chunks[n](e);if(!o){this.error(new Error("Unsupported critical chunk type "+s));return}this.read(e+4,this._skipChunk.bind(this))};lt.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};lt.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};lt.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};lt.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};lt.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),s=t[8],o=t[9],r=t[10],i=t[11],a=t[12];if(s!==8&&s!==4&&s!==2&&s!==1&&s!==16){this.error(new Error("Unsupported bit depth "+s));return}if(!(o in it.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=it.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:s,interlace:!!a,palette:!!(o&it.COLORTYPE_PALETTE),color:!!(o&it.COLORTYPE_COLOR),alpha:!!(o&it.COLORTYPE_ALPHA),bpp:c,colorType:o}),this._handleChunkEnd()};lt.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};lt.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};lt.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};lt.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===it.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===it.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===it.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};lt.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};lt.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/it.GAMMA_DIVISION),this._handleChunkEnd()};lt.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};lt.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===it.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};lt.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};lt.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Ml=K(Eh=>{"use strict";var kh=kl(),qS=[function(){},function(t,e,n,s){if(s===e.length)throw new Error("Ran out of data");let o=e[s];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=255},function(t,e,n,s){if(s+1>=e.length)throw new Error("Ran out of data");let o=e[s];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=e[s+1]},function(t,e,n,s){if(s+2>=e.length)throw new Error("Ran out of data");t[n]=e[s],t[n+1]=e[s+1],t[n+2]=e[s+2],t[n+3]=255},function(t,e,n,s){if(s+3>=e.length)throw new Error("Ran out of data");t[n]=e[s],t[n+1]=e[s+1],t[n+2]=e[s+2],t[n+3]=e[s+3]}],FS=[function(){},function(t,e,n,s){let o=e[0];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=s},function(t,e,n){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[1]},function(t,e,n,s){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=s},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function BS(t,e){let n=[],s=0;function o(){if(s===t.length)throw new Error("Ran out of data");let r=t[s];s++;let i,a,c,u,d,f,p,m;switch(e){default:throw new Error("unrecognised depth");case 16:p=t[s],s++,n.push((r<<8)+p);break;case 4:p=r&15,m=r>>4,n.push(m,p);break;case 2:d=r&3,f=r>>2&3,p=r>>4&3,m=r>>6&3,n.push(m,p,f,d);break;case 1:i=r&1,a=r>>1&1,c=r>>2&1,u=r>>3&1,d=r>>4&1,f=r>>5&1,p=r>>6&1,m=r>>7&1,n.push(m,p,f,d,u,c,a,i);break}}return{get:function(r){for(;n.length<r;)o();let i=n.slice(0,r);return n=n.slice(r),i},resetAfterLine:function(){n.length=0},end:function(){if(s!==t.length)throw new Error("extra data found")}}}function US(t,e,n,s,o,r){let i=t.width,a=t.height,c=t.index;for(let u=0;u<a;u++)for(let d=0;d<i;d++){let f=n(d,u,c);qS[s](e,o,f,r),r+=s}return r}function WS(t,e,n,s,o,r){let i=t.width,a=t.height,c=t.index;for(let u=0;u<a;u++){for(let d=0;d<i;d++){let f=o.get(s),p=n(d,u,c);FS[s](e,f,p,r)}o.resetAfterLine()}}Eh.dataToBitMap=function(t,e){let n=e.width,s=e.height,o=e.depth,r=e.bpp,i=e.interlace,a;o!==8&&(a=BS(t,o));let c;o<=8?c=Buffer.alloc(n*s*4):c=new Uint16Array(n*s*4);let u=Math.pow(2,o)-1,d=0,f,p;if(i)f=kh.getImagePasses(n,s),p=kh.getInterlaceIterator(n,s);else{let m=0;p=function(){let h=m;return m+=4,h},f=[{width:n,height:s}]}for(let m=0;m<f.length;m++)o===8?d=US(f[m],c,p,r,t,d):WS(f[m],c,p,r,a,u);if(o===8){if(d!==t.length)throw new Error("extra data found")}else a.end();return c}});var Nl=K((gM,Th)=>{"use strict";function HS(t,e,n,s,o){let r=0;for(let i=0;i<s;i++)for(let a=0;a<n;a++){let c=o[t[r]];if(!c)throw new Error("index "+t[r]+" not in palette");for(let u=0;u<4;u++)e[r+u]=c[u];r+=4}}function YS(t,e,n,s,o){let r=0;for(let i=0;i<s;i++)for(let a=0;a<n;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 u=0;u<4;u++)e[r+u]=0;r+=4}}function GS(t,e,n,s,o){let r=255,i=Math.pow(2,o)-1,a=0;for(let c=0;c<s;c++)for(let u=0;u<n;u++){for(let d=0;d<4;d++)e[a+d]=Math.floor(t[a+d]*r/i+.5);a+=4}}Th.exports=function(t,e,n=!1){let s=e.depth,o=e.width,r=e.height,i=e.colorType,a=e.transColor,c=e.palette,u=t;return i===3?HS(t,u,o,r,c):(a&&YS(t,u,o,r,a),s!==8&&!n&&(s===16&&(u=Buffer.alloc(o*r*4)),GS(t,u,o,r,s))),u}});var Ah=K((yM,Ch)=>{"use strict";var KS=require("util"),Pl=require("zlib"),Rh=Sl(),zS=_h(),XS=Ol(),VS=Ml(),JS=Nl(),An=Ch.exports=function(t){Rh.call(this),this._parser=new XS(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()};KS.inherits(An,Rh);An.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};An.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Pl.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,s=Math.max(n,Pl.Z_MIN_CHUNK);this._inflate=Pl.createInflate({chunkSize:s});let o=n,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){o&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){o&&(a.length>o&&(a=a.slice(0,o)),o-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};An.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new zS(this._bitmapInfo)};An.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};An.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};An.prototype._simpleTransparency=function(){this._metaData.alpha=!0};An.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};An.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};An.prototype._complete=function(t){if(this.errord)return;let e;try{let n=VS.dataToBitMap(t,this._bitmapInfo);e=JS(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Mh=K(($M,Oh)=>{"use strict";var nn=To();Oh.exports=function(t,e,n,s){let o=[nn.COLORTYPE_COLOR_ALPHA,nn.COLORTYPE_ALPHA].indexOf(s.colorType)!==-1;if(s.colorType===s.inputColorType){let h=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(s.bitDepth===8||s.bitDepth===16&&h)return t}let r=s.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=nn.COLORTYPE_TO_BPP_MAP[s.inputColorType];a===4&&!s.inputHasAlpha&&(a=3);let c=nn.COLORTYPE_TO_BPP_MAP[s.colorType];s.bitDepth===16&&(i=65535,c*=2);let u=Buffer.alloc(e*n*c),d=0,f=0,p=s.bgColor||{};p.red===void 0&&(p.red=i),p.green===void 0&&(p.green=i),p.blue===void 0&&(p.blue=i);function m(){let h,g,$,w=i;switch(s.inputColorType){case nn.COLORTYPE_COLOR_ALPHA:w=r[d+3],h=r[d],g=r[d+1],$=r[d+2];break;case nn.COLORTYPE_COLOR:h=r[d],g=r[d+1],$=r[d+2];break;case nn.COLORTYPE_ALPHA:w=r[d+1],h=r[d],g=h,$=h;break;case nn.COLORTYPE_GRAYSCALE:h=r[d],g=h,$=h;break;default:throw new Error("input color type:"+s.inputColorType+" is not supported at present")}return s.inputHasAlpha&&(o||(w/=i,h=Math.min(Math.max(Math.round((1-w)*p.red+w*h),0),i),g=Math.min(Math.max(Math.round((1-w)*p.green+w*g),0),i),$=Math.min(Math.max(Math.round((1-w)*p.blue+w*$),0),i))),{red:h,green:g,blue:$,alpha:w}}for(let h=0;h<n;h++)for(let g=0;g<e;g++){let $=m(r,d);switch(s.colorType){case nn.COLORTYPE_COLOR_ALPHA:case nn.COLORTYPE_COLOR:s.bitDepth===8?(u[f]=$.red,u[f+1]=$.green,u[f+2]=$.blue,o&&(u[f+3]=$.alpha)):(u.writeUInt16BE($.red,f),u.writeUInt16BE($.green,f+2),u.writeUInt16BE($.blue,f+4),o&&u.writeUInt16BE($.alpha,f+6));break;case nn.COLORTYPE_ALPHA:case nn.COLORTYPE_GRAYSCALE:{let w=($.red+$.green+$.blue)/3;s.bitDepth===8?(u[f]=w,o&&(u[f+1]=$.alpha)):(u.writeUInt16BE(w,f),o&&u.writeUInt16BE($.alpha,f+2));break}default:throw new Error("unrecognised color Type "+s.colorType)}d+=a,f+=c}return u}});var Lh=K((wM,Ph)=>{"use strict";var Nh=El();function ZS(t,e,n,s,o){for(let r=0;r<n;r++)s[o+r]=t[e+r]}function QS(t,e,n){let s=0,o=e+n;for(let r=e;r<o;r++)s+=Math.abs(t[r]);return s}function ev(t,e,n,s,o,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,c=t[e+i]-a;s[o+i]=c}}function tv(t,e,n,s){let o=0;for(let r=0;r<n;r++){let i=r>=s?t[e+r-s]:0,a=t[e+r]-i;o+=Math.abs(a)}return o}function nv(t,e,n,s,o){for(let r=0;r<n;r++){let i=e>0?t[e+r-n]:0,a=t[e+r]-i;s[o+r]=a}}function sv(t,e,n){let s=0,o=e+n;for(let r=e;r<o;r++){let i=e>0?t[r-n]:0,a=t[r]-i;s+=Math.abs(a)}return s}function ov(t,e,n,s,o,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,c=e>0?t[e+i-n]:0,u=t[e+i]-(a+c>>1);s[o+i]=u}}function rv(t,e,n,s){let o=0;for(let r=0;r<n;r++){let i=r>=s?t[e+r-s]:0,a=e>0?t[e+r-n]:0,c=t[e+r]-(i+a>>1);o+=Math.abs(c)}return o}function iv(t,e,n,s,o,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,c=e>0?t[e+i-n]:0,u=e>0&&i>=r?t[e+i-(n+r)]:0,d=t[e+i]-Nh(a,c,u);s[o+i]=d}}function av(t,e,n,s){let o=0;for(let r=0;r<n;r++){let i=r>=s?t[e+r-s]:0,a=e>0?t[e+r-n]:0,c=e>0&&r>=s?t[e+r-(n+s)]:0,u=t[e+r]-Nh(i,a,c);o+=Math.abs(u)}return o}var cv={0:ZS,1:ev,2:nv,3:ov,4:iv},lv={0:QS,1:tv,2:sv,3:rv,4:av};Ph.exports=function(t,e,n,s,o){let r;if(!("filterType"in s)||s.filterType===-1)r=[0,1,2,3,4];else if(typeof s.filterType=="number")r=[s.filterType];else throw new Error("unrecognised filter types");s.bitDepth===16&&(o*=2);let i=e*o,a=0,c=0,u=Buffer.alloc((i+1)*n),d=r[0];for(let f=0;f<n;f++){if(r.length>1){let p=1/0;for(let m=0;m<r.length;m++){let h=lv[r[m]](t,c,i,o);h<p&&(d=r[m],p=h)}}u[a]=d,a++,cv[d](t,c,i,u,a,o),a+=i,c+=i}return u}});var Ll=K((bM,Ih)=>{"use strict";var xt=To(),uv=Al(),dv=Mh(),fv=Lh(),pv=require("zlib"),as=Ih.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||pv.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:xt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:xt.COLORTYPE_COLOR_ALPHA,[xt.COLORTYPE_GRAYSCALE,xt.COLORTYPE_COLOR,xt.COLORTYPE_COLOR_ALPHA,xt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([xt.COLORTYPE_GRAYSCALE,xt.COLORTYPE_COLOR,xt.COLORTYPE_COLOR_ALPHA,xt.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")};as.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};as.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};as.prototype.filterData=function(t,e,n){let s=dv(t,e,n,this._options),o=xt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return fv(s,e,n,this._options,o)};as.prototype._packChunk=function(t,e){let n=e?e.length:0,s=Buffer.alloc(n+12);return s.writeUInt32BE(n,0),s.writeUInt32BE(t,4),e&&e.copy(s,8),s.writeInt32BE(uv.crc32(s.slice(4,s.length-4)),s.length-4),s};as.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*xt.GAMMA_DIVISION),0),this._packChunk(xt.TYPE_gAMA,e)};as.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(xt.TYPE_IHDR,n)};as.prototype.packIDAT=function(t){return this._packChunk(xt.TYPE_IDAT,t)};as.prototype.packIEND=function(){return this._packChunk(xt.TYPE_IEND,null)}});var Fh=K((_M,qh)=>{"use strict";var hv=require("util"),Dh=require("stream"),mv=To(),gv=Ll(),jh=qh.exports=function(t){Dh.call(this);let e=t||{};this._packer=new gv(e),this._deflate=this._packer.createDeflate(),this.readable=!0};hv.inherits(jh,Dh);jh.prototype.pack=function(t,e,n,s){this.emit("data",Buffer.from(mv.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),s&&this.emit("data",this._packer.packGAMA(s));let o=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(r){this.emit("data",this._packer.packIDAT(r))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(o)}});var Gh=K((hr,Yh)=>{"use strict";var Bh=require("assert").ok,Ro=require("zlib"),yv=require("util"),Uh=require("buffer").kMaxLength;function Os(t){if(!(this instanceof Os))return new Os(t);t&&t.chunkSize<Ro.Z_MIN_CHUNK&&(t.chunkSize=Ro.Z_MIN_CHUNK),Ro.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 $v(t){return new Os(t)}function Wh(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Os.prototype._processChunk=function(t,e,n){if(typeof n=="function")return Ro.Inflate._processChunk.call(this,t,e,n);let s=this,o=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,c=[],u=0,d;this.on("error",function(h){d=h});function f(h,g){if(s._hadError)return;let $=r-g;if(Bh($>=0,"have should not go down"),$>0){let w=s._buffer.slice(s._offset,s._offset+$);if(s._offset+=$,w.length>i&&(w=w.slice(0,i)),c.push(w),u+=w.length,i-=w.length,i===0)return!1}return(g===0||s._offset>=s._chunkSize)&&(r=s._chunkSize,s._offset=0,s._buffer=Buffer.allocUnsafe(s._chunkSize)),g===0?(a+=o-h,o=h,!0):!1}Bh(this._handle,"zlib binding closed");let p;do p=this._handle.writeSync(e,t,a,o,this._buffer,this._offset,r),p=p||this._writeState;while(!this._hadError&&f(p[0],p[1]));if(this._hadError)throw d;if(u>=Uh)throw Wh(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Uh.toString(16)+" bytes");let m=Buffer.concat(c,u);return Wh(this),m};yv.inherits(Os,Ro.Inflate);function wv(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=Ro.Z_FINISH),t._processChunk(e,n)}function Hh(t,e){return wv(new Os(e),t)}Yh.exports=hr=Hh;hr.Inflate=Os;hr.createInflate=$v;hr.inflateSync=Hh});var Il=K((xM,zh)=>{"use strict";var Kh=zh.exports=function(t){this._buffer=t,this._reads=[]};Kh.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Kh.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 Vh=K(Xh=>{"use strict";var bv=Il(),_v=Tl();Xh.process=function(t,e){let n=[],s=new bv(t);return new _v(e,{read:s.read.bind(s),write:function(r){n.push(r)},complete:function(){}}).start(),s.process(),Buffer.concat(n)}});var em=K((vM,Qh)=>{"use strict";var Jh=!0,Zh=require("zlib"),xv=Gh();Zh.deflateSync||(Jh=!1);var Sv=Il(),vv=Vh(),kv=Ol(),Ev=Ml(),Tv=Nl();Qh.exports=function(t,e){if(!Jh)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function s(S){n=S}let o;function r(S){o=S}function i(S){o.transColor=S}function a(S){o.palette=S}function c(){o.alpha=!0}let u;function d(S){u=S}let f=[];function p(S){f.push(S)}let m=new Sv(t);if(new kv(e,{read:m.read.bind(m),error:s,metadata:r,gamma:d,palette:a,transColor:i,inflateData:p,simpleTransparency:c}).start(),m.process(),n)throw n;let g=Buffer.concat(f);f.length=0;let $;if(o.interlace)$=Zh.inflateSync(g);else{let x=((o.width*o.bpp*o.depth+7>>3)+1)*o.height;$=xv(g,{chunkSize:x,maxLength:x})}if(g=null,!$||!$.length)throw new Error("bad png - invalid inflate data response");let w=vv.process($,o);g=null;let k=Ev.dataToBitMap(w,o);w=null;let E=Tv(k,o,e.skipRescale);return o.data=E,o.gamma=u||0,o}});var om=K((kM,sm)=>{"use strict";var tm=!0,nm=require("zlib");nm.deflateSync||(tm=!1);var Rv=To(),Cv=Ll();sm.exports=function(t,e){if(!tm)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},s=new Cv(n),o=[];o.push(Buffer.from(Rv.PNG_SIGNATURE)),o.push(s.packIHDR(t.width,t.height)),t.gamma&&o.push(s.packGAMA(t.gamma));let r=s.filterData(t.data,t.width,t.height),i=nm.deflateSync(r,s.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return o.push(s.packIDAT(i)),o.push(s.packIEND()),Buffer.concat(o)}});var rm=K(Dl=>{"use strict";var Av=em(),Ov=om();Dl.read=function(t,e){return Av(t,e||{})};Dl.write=function(t,e){return Ov(t,e)}});var cm=K(am=>{"use strict";var Mv=require("util"),im=require("stream"),Nv=Ah(),Pv=Fh(),Lv=rm(),At=am.PNG=function(t){im.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 Nv(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 Pv(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"))};Mv.inherits(At,im);At.sync=Lv;At.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)};At.prototype.parse=function(t,e){if(e){let n,s;n=function(o){this.removeListener("error",s),this.data=o,e(null,this)}.bind(this),s=function(o){this.removeListener("parsed",n),e(o,null)}.bind(this),this.once("parsed",n),this.once("error",s)}return this.end(t),this};At.prototype.write=function(t){return this._parser.write(t),!0};At.prototype.end=function(t){this._parser.end(t)};At.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};At.prototype._gamma=function(t){this.gamma=t};At.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};At.bitblt=function(t,e,n,s,o,r,i,a){if(n|=0,s|=0,o|=0,r|=0,i|=0,a|=0,n>t.width||s>t.height||n+o>t.width||s+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+o>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let c=0;c<r;c++)t.data.copy(e.data,(a+c)*e.width+i<<2,(s+c)*t.width+n<<2,(s+c)*t.width+n+o<<2)};At.prototype.bitblt=function(t,e,n,s,o,r,i){return At.bitblt(this,t,e,n,s,o,r,i),this};At.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let s=t.width*e+n<<2;for(let o=0;o<3;o++){let r=t.data[s+o]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[s+o]=Math.round(r*255)}}t.gamma=0}};At.prototype.adjustGamma=function(){At.adjustGamma(this)}});var pm={};Aw(pm,{default:()=>dm});function dm(t,e,n,s,o,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:c=[255,255,0],diffColor:u=[255,0,0],includeAA:d,diffColorAlt:f,diffMask:p}=r;if(!jl(t)||!jl(e)||n&&!jl(n))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||n&&n.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==s*o*4)throw new Error("Image data size does not match width/height.");let m=s*o,h=new Uint32Array(t.buffer,t.byteOffset,m),g=new Uint32Array(e.buffer,e.byteOffset,m),$=!0;for(let T=0;T<m;T++)if(h[T]!==g[T]){$=!1;break}if($){if(n&&!p)for(let T=0;T<m;T++)um(t,4*T,a,n);return 0}let w=35215*i*i,[k,E,S]=c,[x,C,H]=u,[q,ie,le]=f||u,te=0;for(let T=0;T<o;T++)for(let Te=0;Te<s;Te++){let G=T*s+Te,z=G*4,fe=h[G]===g[G]?0:fm(t,e,z,z,!1);if(Math.abs(fe)>w){let Ee=lm(t,Te,T,s,o,h,g)||lm(e,Te,T,s,o,g,h);!d&&Ee?n&&!p&&aa(n,z,k,E,S):(n&&(fe<0?aa(n,z,q,ie,le):aa(n,z,x,C,H)),te++)}else n&&!p&&um(t,z,a,n)}return te}function jl(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function lm(t,e,n,s,o,r,i){let a=Math.max(e-1,0),c=Math.max(n-1,0),u=Math.min(e+1,s-1),d=Math.min(n+1,o-1),f=n*s+e,p=e===a||e===u||n===c||n===d?1:0,m=0,h=0,g=0,$=0,w=0,k=0;for(let E=a;E<=u;E++)for(let S=c;S<=d;S++){if(E===e&&S===n)continue;let x=fm(t,t,f*4,(S*s+E)*4,!0);if(x===0){if(p++,p>2)return!1}else x<m?(m=x,g=E,$=S):x>h&&(h=x,w=E,k=S)}return m===0||h===0?!1:ia(r,g,$,s,o)&&ia(i,g,$,s,o)||ia(r,w,k,s,o)&&ia(i,w,k,s,o)}function ia(t,e,n,s,o){let r=Math.max(e-1,0),i=Math.max(n-1,0),a=Math.min(e+1,s-1),c=Math.min(n+1,o-1),u=t[n*s+e],d=e===r||e===a||n===i||n===c?1:0;for(let f=r;f<=a;f++)for(let p=i;p<=c;p++)if(!(f===e&&p===n)&&(d+=+(u===t[p*s+f]),d>2))return!0;return!1}function fm(t,e,n,s,o){let r=t[n],i=t[n+1],a=t[n+2],c=t[n+3],u=e[s],d=e[s+1],f=e[s+2],p=e[s+3],m=r-u,h=i-d,g=a-f,$=c-p;if(!m&&!h&&!g&&!$)return 0;if(c<255||p<255){let x=48+159*(n%2),C=48+159*((n/1.618033988749895|0)%2),H=48+159*((n/2.618033988749895|0)%2);m=(r*c-u*p-x*$)/255,h=(i*c-d*p-C*$)/255,g=(a*c-f*p-H*$)/255}let w=m*.29889531+h*.58662247+g*.11448223;if(o)return w;let k=m*.59597799-h*.2741761-g*.32180189,E=m*.21147017-h*.52261711+g*.31114694,S=.5053*w*w+.299*k*k+.1957*E*E;return w>0?-S:S}function aa(t,e,n,s,o){t[e+0]=n,t[e+1]=s,t[e+2]=o,t[e+3]=255}function um(t,e,n,s){let o=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*n*t[e+3]/255;aa(s,e,o,o,o)}var hm=Cw(()=>{});var Ms=K((RM,wm)=>{var Kn=require("fs"),Iv=require("path"),Dv=require("os"),jv="nex-visual-";function gm(t){return Iv.join(Dv.tmpdir(),`${jv}${Date.now()}-${t}`)}var ql=null;function ca(){return ql||(ql=cm().PNG),ql}var Fl=null;function qv(){if(!Fl){let t=(hm(),Mw(pm));Fl=t.default||t}return Fl}function Wl(t,e,{threshold:n=.1}={}){let s=ca(),o=qv(),r=s.sync.read(Kn.readFileSync(t)),i=s.sync.read(Kn.readFileSync(e)),a=Math.max(r.width,i.width),c=Math.max(r.height,i.height),u=mm(r,a,c),d=mm(i,a,c),f=new s({width:a,height:c}),p=o(u,d,f.data,a,c,{threshold:n,includeAA:!1}),m=a*c,h=(p/m*100).toFixed(1),g=Fv(f.data,a,c,3,3),$=gm("diff.png");return Kn.writeFileSync($,s.sync.write(f),{mode:384}),{diffPath:$,diffPercent:parseFloat(h),totalPixels:m,changedPixels:p,regionSummary:g,beforePath:t,afterPath:e,width:a,height:c}}function mm(t,e,n){if(t.width===e&&t.height===n)return t.data;let s=Buffer.alloc(e*n*4,0);for(let o=0;o<t.height;o++){let r=o*t.width*4,i=o*e*4;t.data.copy(s,i,r,r+t.width*4)}return s}function Fv(t,e,n,s,o){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/s),a=Math.ceil(n/o),c=[];for(let u=0;u<o;u++)for(let d=0;d<s;d++){let f=0,p=0,m=d*i,h=u*a,g=Math.min(m+i,e),$=Math.min(h+a,n);for(let w=h;w<$;w++)for(let k=m;k<g;k++){p++;let E=(w*e+k)*4;(t[E]>0||t[E+1]>0)&&f++}if(f>0){let w=(f/p*100).toFixed(1),k=r[u]&&r[u][d]?r[u][d]:`row${u}-col${d}`;c.push({name:k,changedPercent:parseFloat(w),changed:f,total:p})}}return c.sort((u,d)=>d.changedPercent-u.changedPercent),c}var ym=[{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 Bv(t,{viewports:e=ym,height:n=800,fullPage:s=!1,timeout:o=3e4}={}){let{browserScreenshot:r}=Gn(),i=[];for(let a of e){let c=await r(t,{width:a.width,height:n,fullPage:s,timeout:o});i.push({label:a.label,width:a.width,path:c.path,base64:c.base64,media_type:c.media_type})}return i}function $m(t,e=[]){let n=ca(),s=n.sync.read(Kn.readFileSync(t));for(let i of e){let a=Uv(i.color||"#FF0000");i.type==="box"?(Wv(s,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&Ul(s,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(Hv(s,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&Ul(s,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(Yv(s,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&Ul(s,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let o=gm("annotated.png");Kn.writeFileSync(o,n.sync.write(s),{mode:384});let r=Kn.readFileSync(o).toString("base64");return{path:o,base64:r,media_type:"image/png"}}function Uv(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,n,s){if(e<0||n<0||e>=t.width||n>=t.height)return;let o=(n*t.width+e)*4;t.data[o]=s.r,t.data[o+1]=s.g,t.data[o+2]=s.b,t.data[o+3]=s.a}function Wv(t,e,n,s,o,r,i=3){for(let a=0;a<i;a++){for(let c=0;c<s;c++)On(t,e+c,n+a,r),On(t,e+c,n+o-1-a,r);for(let c=0;c<o;c++)On(t,e+a,n+c,r),On(t,e+s-1-a,n+c,r)}}function Bl(t,e,n,s,o,r,i=3){let a=Math.abs(s-e),c=Math.abs(o-n),u=e<s?1:-1,d=n<o?1:-1,f=a-c,p=e,m=n;for(;;){let h=Math.floor(i/2);for(let $=-h;$<=h;$++)for(let w=-h;w<=h;w++)On(t,p+$,m+w,r);if(p===s&&m===o)break;let g=2*f;g>-c&&(f-=c,p+=u),g<a&&(f+=a,m+=d)}}function Hv(t,e,n,s,o,r,i=3){Bl(t,e,n,s,o,r,i);let a=Math.atan2(o-n,s-e),c=15,u=a+Math.PI*.8,d=a-Math.PI*.8;Bl(t,s,o,Math.round(s+c*Math.cos(u)),Math.round(o+c*Math.sin(u)),r,i),Bl(t,s,o,Math.round(s+c*Math.cos(d)),Math.round(o+c*Math.sin(d)),r,i)}function Yv(t,e,n,s,o,r=3){for(let i=0;i<r;i++){let a=s-i;for(let c=0;c<360;c+=.5){let u=c*Math.PI/180,d=Math.round(e+a*Math.cos(u)),f=Math.round(n+a*Math.sin(u));On(t,d,f,o)}}}function Ul(t,e,n,s,o){let i=s.length*6+4,a=12;for(let c=0;c<a;c++)for(let u=0;u<i;u++)On(t,e+u,n+c,{r:0,g:0,b:0,a:200});for(let c=0;c<i;c++)On(t,e+c,n+a-1,o),On(t,e+c,n+a-2,o);for(let c=0;c<s.length;c++){let u=e+2+c*6;for(let d=2;d<9;d++)for(let f=0;f<4;f++)On(t,u+f,n+d,o)}}async function*Gv(t,e,{maxIterations:n=20,hmrDelay:s=1500,width:o=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=Gn(),c=Kv("chokidar"),u=await a(t,{width:o,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:u.path,base64:u.base64,media_type:u.media_type},!c){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let d=0,f=!1,p=c.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});p.on("change",()=>{f=!0});try{for(;d<n;){await Xv(()=>f,3e5),f=!1,d++,await zv(s);let m=await a(t,{width:o,height:r,timeout:i}),h=null;try{h=Wl(u.path,m.path)}catch{}u=m,yield{iteration:d,type:"change",path:m.path,base64:m.base64,media_type:m.media_type,diff:h?{diffPath:h.diffPath,diffPercent:h.diffPercent,changedPixels:h.changedPixels,regions:h.regionSummary}:null}}}finally{await p.close()}}function Kv(t){try{return require(t)}catch{return null}}function zv(t){return new Promise(e=>setTimeout(e,t))}function Xv(t,e=6e4){return new Promise((n,s)=>{let o=setInterval(()=>{t()&&(clearInterval(o),clearTimeout(r),n())},200),r=setTimeout(()=>{clearInterval(o),s(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function Vv(t,{sampleRate:e=4}={}){let s=ca().sync.read(Kn.readFileSync(t)),o=new Map;for(let u=0;u<s.height;u+=e)for(let d=0;d<s.width;d+=e){let f=(u*s.width+d)*4,p=s.data[f],m=s.data[f+1],h=s.data[f+2];if(s.data[f+3]<128)continue;let $=Math.round(p/8)*8,w=Math.round(m/8)*8,k=Math.round(h/8)*8,E=`${$},${w},${k}`;o.set(E,(o.get(E)||0)+1)}let r=[...o.entries()].sort((u,d)=>d[1]-u[1]).slice(0,20),i=r.reduce((u,d)=>u+d[1],0),a=r.map(([u,d])=>{let[f,p,m]=u.split(",").map(Number);return{hex:Jv(f,p,m),rgb:`rgb(${f}, ${p}, ${m})`,frequency:parseFloat((d/i*100).toFixed(1)),category:Zv(f,p,m)}}),c=Qv(s);return{colors:a,spacing:c,dimensions:{width:s.width,height:s.height},imagePath:t}}function Jv(t,e,n){return"#"+[t,e,n].map(s=>Math.min(255,s).toString(16).padStart(2,"0")).join("")}function Zv(t,e,n){let s=(t*299+e*587+n*114)/1e3;return s>240?"white/background":s<30?"black/text":s<80?"dark":t>200&&e<100&&n<100?"red/danger":t<100&&e>150&&n<100?"green/success":t<100&&e<100&&n>200?"blue/primary":t>200&&e>200&&n<100?"yellow/warning":t>200&&e>100&&n<50?"orange/accent":s>200?"light/subtle":"midtone"}function Qv(t){let e=[],n=!1,s=0,o=ek(t);for(let i=0;i<t.height;i++){let a=!0;for(let c=0;c<t.width;c+=4){let u=(i*t.width+c)*4;if(Math.abs(t.data[u]-o.r)>20||Math.abs(t.data[u+1]-o.g)>20||Math.abs(t.data[u+2]-o.b)>20){a=!1;break}}if(a&&n)n=!1,s=i;else if(!a&&!n&&(n=!0,s>0)){let c=i-s;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 ek(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],n=0,s=0,o=0;for(let[r,i]of e){let a=(i*t.width+r)*4;n+=t.data[a],s+=t.data[a+1],o+=t.data[a+2]}return{r:Math.round(n/4),g:Math.round(s/4),b:Math.round(o/4)}}async function tk(t,e,{width:n,height:s=800,fullPage:o=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=Gn(),u=ca().sync.read(Kn.readFileSync(e)),d=n||u.width,f=s||u.height,p=await a(t,{width:d,height:f,fullPage:o,timeout:i}),m=Wl(e,p.path,{threshold:r}),h=$m(p.path,m.regionSummary.filter(g=>g.changedPercent>1).map((g,$)=>{let E=Math.ceil(m.width/3),S=Math.ceil(m.height/3),x=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],C=0,H=0;for(let q=0;q<3;q++)for(let ie=0;ie<3;ie++)x[q][ie]===g.name&&(C=ie,H=q);return{type:"box",x:C*E+2,y:H*S+2,width:E-4,height:S-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:p.path,referencePath:e,diffPath:m.diffPath,annotatedPath:h.path,diffPercent:m.diffPercent,changedPixels:m.changedPixels,totalPixels:m.totalPixels,regions:m.regionSummary,liveBase64:p.base64,diffBase64:Kn.readFileSync(m.diffPath).toString("base64"),annotatedBase64:h.base64}}wm.exports={pixelDiff:Wl,responsiveSweep:Bv,annotateImage:$m,visualWatch:Gv,extractDesignTokens:Vv,designCompare:tk,DEFAULT_VIEWPORTS:ym}});var la=K((CM,bm)=>{var{C:Ke}=Ye(),gr="",Ot=[],mr=0,Ns=null;function nk(t){Ns=t}function sk(t,e){gr=t,Ot=[],mr=0;for(let s of e){mr++;let o=`t${mr}`;Ot.push({id:o,description:s.description||s.title||s.name||s.task||`Task ${mr}`,status:"pending",dependsOn:s.depends_on||[],result:null})}let n=Ot.map(s=>({...s}));return Ns&&Ns("create",{name:t,tasks:n}),n}function ok(t,e,n){let s=Ot.find(o=>o.id===t);return s?(s.status=e,n!==void 0&&(s.result=n),Ns&&Ns("update",{id:t,status:e,result:n}),{...s}):null}function rk(){return{name:gr,tasks:Ot.map(t=>({...t}))}}function ik(){gr="",Ot=[],mr=0,Ns&&Ns("clear",{})}function ak(){return Ot.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=Ot.find(s=>s.id===e);return n&&n.status==="done"}))}function ck(){if(Ot.length===0)return`${Ke.dim}No active tasks${Ke.reset}`;let t=[];gr&&(t.push(` ${Ke.bold}${Ke.cyan}Tasks: ${gr}${Ke.reset}`),t.push(` ${Ke.dim}${"\u2500".repeat(40)}${Ke.reset}`));for(let o of Ot){let r,i;switch(o.status){case"done":r="\u2713",i=Ke.green;break;case"in_progress":r="\u2192",i=Ke.cyan;break;case"failed":r="\u2717",i=Ke.red;break;default:r="\xB7",i=Ke.dim}let a=o.dependsOn.length>0?` ${Ke.dim}(after: ${o.dependsOn.join(", ")})${Ke.reset}`:"",c=`[${o.status}]`,u=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Ke.reset} ${Ke.bold}${o.id}${Ke.reset} ${u.padEnd(40)} ${i}${c}${Ke.reset}${a}`),o.result&&o.status==="done"){let d=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Ke.dim}\u2192 ${d}${Ke.reset}`)}}let e=Ot.filter(o=>o.status==="done").length,n=Ot.filter(o=>o.status==="failed").length,s=Ot.length;return t.push(` ${Ke.dim}${"\u2500".repeat(40)}${Ke.reset}`),t.push(` ${Ke.dim}${e}/${s} done${n>0?`, ${n} failed`:""}${Ke.reset}`),t.join(`
|
|
129
|
+
Then restart nex-code.`;function fh(){if(pr!==null)return pr;try{require("playwright"),pr=!0}catch{pr=!1}return pr}async function ra(){if(!fh())throw new Error(dh);return vl||(vl=require("playwright")),(!Yn||!Yn.isConnected())&&(Yn=await vl.chromium.launch({headless:!0})),Yn}async function TS(){if(Yn){try{await Yn.close()}catch{}Yn=null}}process.on("exit",()=>{if(Yn)try{Yn.close()}catch{}});async function RS(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let o=await(await ra()).newPage();try{await o.goto(t,{waitUntil:n,timeout:e});let r=await o.title(),i=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.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?`
|
|
130
|
+
...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function CS(t,{width:e=1280,height:n=800,fullPage:s=!1,timeout:o=3e4}={}){let i=await(await ra()).newPage();try{await i.setViewportSize({width:e,height:n}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let a=await i.screenshot({type:"png",fullPage:s}),c=require("os"),u=require("path"),d=require("fs"),f=u.join(c.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(f,a,{mode:384}),{path:f,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function AS(t,{selector:e,text:n,timeout:s=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await ra()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:s}),n?await r.getByText(n,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function OS(t,{selector:e,value:n,submit:s=!1,timeout:o=3e4}={}){if(!e||n===void 0)throw new Error("selector and value are required");let i=await(await ra()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(n)),s&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${s?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}ph.exports={isPlaywrightAvailable:fh,browserNavigate:RS,browserScreenshot:CS,browserClick:AS,browserFill:OS,closeBrowser:TS,INSTALL_MSG:dh}});var kl=K((aM,mh)=>{"use strict";var MS=require("util"),hh=require("stream"),pn=mh.exports=function(){hh.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};MS.inherits(pn,hh);pn.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))};pn.prototype.write=function(t,e){if(!this.writable)return this.emit("error",new Error("Stream not writable")),!1;let n;return Buffer.isBuffer(t)?n=t:n=Buffer.from(t,e||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused};pn.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()))};pn.prototype.destroySoon=pn.prototype.end;pn.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};pn.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};pn.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))};pn.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,s=Buffer.alloc(t.length);for(;e<t.length;){let o=this._buffers[n++],r=Math.min(o.length,t.length-e);o.copy(s,e,0,r),e+=r,r!==o.length&&(this._buffers[--n]=o.slice(r))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,s)};pn.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let t=this._reads[0];if(t.allowLess)this._processReadAllowingLess(t);else if(this._buffered>=t.length)this._processRead(t);else break}this._buffers&&!this.writable&&this._end()}catch(t){this.emit("error",t)}}});var Tl=K(El=>{"use strict";var is=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];El.getImagePasses=function(t,e){let n=[],s=t%8,o=e%8,r=(t-s)/8,i=(e-o)/8;for(let a=0;a<is.length;a++){let c=is[a],u=r*c.x.length,d=i*c.y.length;for(let f=0;f<c.x.length&&c.x[f]<s;f++)u++;for(let f=0;f<c.y.length&&c.y[f]<o;f++)d++;u>0&&d>0&&n.push({width:u,height:d,index:a})}return n};El.getInterlaceIterator=function(t){return function(e,n,s){let o=e%is[s].x.length,r=(e-o)/is[s].x.length*8+is[s].x[o],i=n%is[s].y.length,a=(n-i)/is[s].y.length*8+is[s].y[i];return r*4+a*t*4}}});var Rl=K((lM,gh)=>{"use strict";gh.exports=function(e,n,s){let o=e+n-s,r=Math.abs(o-e),i=Math.abs(o-n),a=Math.abs(o-s);return r<=i&&r<=a?e:i<=a?n:s}});var Cl=K((uM,$h)=>{"use strict";var NS=Tl(),PS=Rl();function yh(t,e,n){let s=t*e;return n!==8&&(s=Math.ceil(s/(8/n))),s}var Eo=$h.exports=function(t,e){let n=t.width,s=t.height,o=t.interlace,r=t.bpp,i=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],o){let a=NS.getImagePasses(n,s);for(let c=0;c<a.length;c++)this._images.push({byteWidth:yh(a[c].width,r,i),height:a[c].height,lineIndex:0})}else this._images.push({byteWidth:yh(n,r,i),height:s,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Eo.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Eo.prototype._unFilterType1=function(t,e,n){let s=this._xComparison,o=s-1;for(let r=0;r<n;r++){let i=t[1+r],a=r>o?e[r-s]:0;e[r]=i+a}};Eo.prototype._unFilterType2=function(t,e,n){let s=this._lastLine;for(let o=0;o<n;o++){let r=t[1+o],i=s?s[o]:0;e[o]=r+i}};Eo.prototype._unFilterType3=function(t,e,n){let s=this._xComparison,o=s-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],c=r?r[i]:0,u=i>o?e[i-s]:0,d=Math.floor((u+c)/2);e[i]=a+d}};Eo.prototype._unFilterType4=function(t,e,n){let s=this._xComparison,o=s-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],c=r?r[i]:0,u=i>o?e[i-s]:0,d=i>o&&r?r[i-s]:0,f=PS(u,c,d);e[i]=a+f}};Eo.prototype._reverseFilterLine=function(t){let e=t[0],n,s=this._images[this._imageIndex],o=s.byteWidth;if(e===0)n=t.slice(1,o+1);else switch(n=Buffer.alloc(o),e){case 1:this._unFilterType1(t,n,o);break;case 2:this._unFilterType2(t,n,o);break;case 3:this._unFilterType3(t,n,o);break;case 4:this._unFilterType4(t,n,o);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),s.lineIndex++,s.lineIndex>=s.height?(this._lastLine=null,this._imageIndex++,s=this._images[this._imageIndex]):this._lastLine=n,s?this.read(s.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var _h=K((dM,bh)=>{"use strict";var LS=require("util"),wh=kl(),IS=Cl(),DS=bh.exports=function(t){wh.call(this);let e=[],n=this;this._filter=new IS(t,{read:this.read.bind(this),write:function(s){e.push(s)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};LS.inherits(DS,wh)});var To=K((fM,xh)=>{"use strict";xh.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 Ml=K((pM,Sh)=>{"use strict";var Al=[];(function(){for(let t=0;t<256;t++){let e=t;for(let n=0;n<8;n++)e&1?e=3988292384^e>>>1:e=e>>>1;Al[t]=e}})();var Ol=Sh.exports=function(){this._crc=-1};Ol.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Al[(this._crc^t[e])&255]^this._crc>>>8;return!0};Ol.prototype.crc32=function(){return this._crc^-1};Ol.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Al[(e^t[n])&255]^e>>>8;return e^-1}});var Nl=K((hM,vh)=>{"use strict";var it=To(),jS=Ml(),lt=vh.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[it.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[it.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[it.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[it.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[it.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[it.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(){}};lt.prototype.start=function(){this.read(it.PNG_SIGNATURE.length,this._parseSignature.bind(this))};lt.prototype._parseSignature=function(t){let e=it.PNG_SIGNATURE;for(let n=0;n<e.length;n++)if(t[n]!==e[n]){this.error(new Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};lt.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),s="";for(let r=4;r<8;r++)s+=String.fromCharCode(t[r]);let o=!!(t[4]&32);if(!this._hasIHDR&&n!==it.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new jS,this._crc.write(Buffer.from(s)),this._chunks[n])return this._chunks[n](e);if(!o){this.error(new Error("Unsupported critical chunk type "+s));return}this.read(e+4,this._skipChunk.bind(this))};lt.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};lt.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};lt.prototype._parseChunkEnd=function(t){let e=t.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==e){this.error(new Error("Crc error - "+e+" - "+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))};lt.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};lt.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),s=t[8],o=t[9],r=t[10],i=t[11],a=t[12];if(s!==8&&s!==4&&s!==2&&s!==1&&s!==16){this.error(new Error("Unsupported bit depth "+s));return}if(!(o in it.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=it.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:s,interlace:!!a,palette:!!(o&it.COLORTYPE_PALETTE),color:!!(o&it.COLORTYPE_COLOR),alpha:!!(o&it.COLORTYPE_ALPHA),bpp:c,colorType:o}),this._handleChunkEnd()};lt.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};lt.prototype._parsePLTE=function(t){this._crc.write(t);let e=Math.floor(t.length/3);for(let n=0;n<e;n++)this._palette.push([t[n*3],t[n*3+1],t[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};lt.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};lt.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===it.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===it.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===it.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};lt.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};lt.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/it.GAMMA_DIVISION),this._handleChunkEnd()};lt.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};lt.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===it.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw new Error("Expected palette not found");this.inflateData(e);let n=t-e.length;n>0?this._handleIDAT(n):this._handleChunkEnd()};lt.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};lt.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var Pl=K(Eh=>{"use strict";var kh=Tl(),qS=[function(){},function(t,e,n,s){if(s===e.length)throw new Error("Ran out of data");let o=e[s];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=255},function(t,e,n,s){if(s+1>=e.length)throw new Error("Ran out of data");let o=e[s];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=e[s+1]},function(t,e,n,s){if(s+2>=e.length)throw new Error("Ran out of data");t[n]=e[s],t[n+1]=e[s+1],t[n+2]=e[s+2],t[n+3]=255},function(t,e,n,s){if(s+3>=e.length)throw new Error("Ran out of data");t[n]=e[s],t[n+1]=e[s+1],t[n+2]=e[s+2],t[n+3]=e[s+3]}],FS=[function(){},function(t,e,n,s){let o=e[0];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=s},function(t,e,n){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[1]},function(t,e,n,s){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=s},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function BS(t,e){let n=[],s=0;function o(){if(s===t.length)throw new Error("Ran out of data");let r=t[s];s++;let i,a,c,u,d,f,p,m;switch(e){default:throw new Error("unrecognised depth");case 16:p=t[s],s++,n.push((r<<8)+p);break;case 4:p=r&15,m=r>>4,n.push(m,p);break;case 2:d=r&3,f=r>>2&3,p=r>>4&3,m=r>>6&3,n.push(m,p,f,d);break;case 1:i=r&1,a=r>>1&1,c=r>>2&1,u=r>>3&1,d=r>>4&1,f=r>>5&1,p=r>>6&1,m=r>>7&1,n.push(m,p,f,d,u,c,a,i);break}}return{get:function(r){for(;n.length<r;)o();let i=n.slice(0,r);return n=n.slice(r),i},resetAfterLine:function(){n.length=0},end:function(){if(s!==t.length)throw new Error("extra data found")}}}function US(t,e,n,s,o,r){let i=t.width,a=t.height,c=t.index;for(let u=0;u<a;u++)for(let d=0;d<i;d++){let f=n(d,u,c);qS[s](e,o,f,r),r+=s}return r}function WS(t,e,n,s,o,r){let i=t.width,a=t.height,c=t.index;for(let u=0;u<a;u++){for(let d=0;d<i;d++){let f=o.get(s),p=n(d,u,c);FS[s](e,f,p,r)}o.resetAfterLine()}}Eh.dataToBitMap=function(t,e){let n=e.width,s=e.height,o=e.depth,r=e.bpp,i=e.interlace,a;o!==8&&(a=BS(t,o));let c;o<=8?c=Buffer.alloc(n*s*4):c=new Uint16Array(n*s*4);let u=Math.pow(2,o)-1,d=0,f,p;if(i)f=kh.getImagePasses(n,s),p=kh.getInterlaceIterator(n,s);else{let m=0;p=function(){let h=m;return m+=4,h},f=[{width:n,height:s}]}for(let m=0;m<f.length;m++)o===8?d=US(f[m],c,p,r,t,d):WS(f[m],c,p,r,a,u);if(o===8){if(d!==t.length)throw new Error("extra data found")}else a.end();return c}});var Ll=K((gM,Th)=>{"use strict";function HS(t,e,n,s,o){let r=0;for(let i=0;i<s;i++)for(let a=0;a<n;a++){let c=o[t[r]];if(!c)throw new Error("index "+t[r]+" not in palette");for(let u=0;u<4;u++)e[r+u]=c[u];r+=4}}function YS(t,e,n,s,o){let r=0;for(let i=0;i<s;i++)for(let a=0;a<n;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 u=0;u<4;u++)e[r+u]=0;r+=4}}function GS(t,e,n,s,o){let r=255,i=Math.pow(2,o)-1,a=0;for(let c=0;c<s;c++)for(let u=0;u<n;u++){for(let d=0;d<4;d++)e[a+d]=Math.floor(t[a+d]*r/i+.5);a+=4}}Th.exports=function(t,e,n=!1){let s=e.depth,o=e.width,r=e.height,i=e.colorType,a=e.transColor,c=e.palette,u=t;return i===3?HS(t,u,o,r,c):(a&&YS(t,u,o,r,a),s!==8&&!n&&(s===16&&(u=Buffer.alloc(o*r*4)),GS(t,u,o,r,s))),u}});var Ah=K((yM,Ch)=>{"use strict";var KS=require("util"),Il=require("zlib"),Rh=kl(),zS=_h(),XS=Nl(),VS=Pl(),JS=Ll(),An=Ch.exports=function(t){Rh.call(this),this._parser=new XS(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()};KS.inherits(An,Rh);An.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};An.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=Il.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,s=Math.max(n,Il.Z_MIN_CHUNK);this._inflate=Il.createInflate({chunkSize:s});let o=n,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){o&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){o&&(a.length>o&&(a=a.slice(0,o)),o-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};An.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new zS(this._bitmapInfo)};An.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};An.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};An.prototype._simpleTransparency=function(){this._metaData.alpha=!0};An.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};An.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};An.prototype._complete=function(t){if(this.errord)return;let e;try{let n=VS.dataToBitMap(t,this._bitmapInfo);e=JS(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Mh=K(($M,Oh)=>{"use strict";var nn=To();Oh.exports=function(t,e,n,s){let o=[nn.COLORTYPE_COLOR_ALPHA,nn.COLORTYPE_ALPHA].indexOf(s.colorType)!==-1;if(s.colorType===s.inputColorType){let h=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(s.bitDepth===8||s.bitDepth===16&&h)return t}let r=s.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=nn.COLORTYPE_TO_BPP_MAP[s.inputColorType];a===4&&!s.inputHasAlpha&&(a=3);let c=nn.COLORTYPE_TO_BPP_MAP[s.colorType];s.bitDepth===16&&(i=65535,c*=2);let u=Buffer.alloc(e*n*c),d=0,f=0,p=s.bgColor||{};p.red===void 0&&(p.red=i),p.green===void 0&&(p.green=i),p.blue===void 0&&(p.blue=i);function m(){let h,g,$,w=i;switch(s.inputColorType){case nn.COLORTYPE_COLOR_ALPHA:w=r[d+3],h=r[d],g=r[d+1],$=r[d+2];break;case nn.COLORTYPE_COLOR:h=r[d],g=r[d+1],$=r[d+2];break;case nn.COLORTYPE_ALPHA:w=r[d+1],h=r[d],g=h,$=h;break;case nn.COLORTYPE_GRAYSCALE:h=r[d],g=h,$=h;break;default:throw new Error("input color type:"+s.inputColorType+" is not supported at present")}return s.inputHasAlpha&&(o||(w/=i,h=Math.min(Math.max(Math.round((1-w)*p.red+w*h),0),i),g=Math.min(Math.max(Math.round((1-w)*p.green+w*g),0),i),$=Math.min(Math.max(Math.round((1-w)*p.blue+w*$),0),i))),{red:h,green:g,blue:$,alpha:w}}for(let h=0;h<n;h++)for(let g=0;g<e;g++){let $=m(r,d);switch(s.colorType){case nn.COLORTYPE_COLOR_ALPHA:case nn.COLORTYPE_COLOR:s.bitDepth===8?(u[f]=$.red,u[f+1]=$.green,u[f+2]=$.blue,o&&(u[f+3]=$.alpha)):(u.writeUInt16BE($.red,f),u.writeUInt16BE($.green,f+2),u.writeUInt16BE($.blue,f+4),o&&u.writeUInt16BE($.alpha,f+6));break;case nn.COLORTYPE_ALPHA:case nn.COLORTYPE_GRAYSCALE:{let w=($.red+$.green+$.blue)/3;s.bitDepth===8?(u[f]=w,o&&(u[f+1]=$.alpha)):(u.writeUInt16BE(w,f),o&&u.writeUInt16BE($.alpha,f+2));break}default:throw new Error("unrecognised color Type "+s.colorType)}d+=a,f+=c}return u}});var Lh=K((wM,Ph)=>{"use strict";var Nh=Rl();function ZS(t,e,n,s,o){for(let r=0;r<n;r++)s[o+r]=t[e+r]}function QS(t,e,n){let s=0,o=e+n;for(let r=e;r<o;r++)s+=Math.abs(t[r]);return s}function ev(t,e,n,s,o,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,c=t[e+i]-a;s[o+i]=c}}function tv(t,e,n,s){let o=0;for(let r=0;r<n;r++){let i=r>=s?t[e+r-s]:0,a=t[e+r]-i;o+=Math.abs(a)}return o}function nv(t,e,n,s,o){for(let r=0;r<n;r++){let i=e>0?t[e+r-n]:0,a=t[e+r]-i;s[o+r]=a}}function sv(t,e,n){let s=0,o=e+n;for(let r=e;r<o;r++){let i=e>0?t[r-n]:0,a=t[r]-i;s+=Math.abs(a)}return s}function ov(t,e,n,s,o,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,c=e>0?t[e+i-n]:0,u=t[e+i]-(a+c>>1);s[o+i]=u}}function rv(t,e,n,s){let o=0;for(let r=0;r<n;r++){let i=r>=s?t[e+r-s]:0,a=e>0?t[e+r-n]:0,c=t[e+r]-(i+a>>1);o+=Math.abs(c)}return o}function iv(t,e,n,s,o,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,c=e>0?t[e+i-n]:0,u=e>0&&i>=r?t[e+i-(n+r)]:0,d=t[e+i]-Nh(a,c,u);s[o+i]=d}}function av(t,e,n,s){let o=0;for(let r=0;r<n;r++){let i=r>=s?t[e+r-s]:0,a=e>0?t[e+r-n]:0,c=e>0&&r>=s?t[e+r-(n+s)]:0,u=t[e+r]-Nh(i,a,c);o+=Math.abs(u)}return o}var cv={0:ZS,1:ev,2:nv,3:ov,4:iv},lv={0:QS,1:tv,2:sv,3:rv,4:av};Ph.exports=function(t,e,n,s,o){let r;if(!("filterType"in s)||s.filterType===-1)r=[0,1,2,3,4];else if(typeof s.filterType=="number")r=[s.filterType];else throw new Error("unrecognised filter types");s.bitDepth===16&&(o*=2);let i=e*o,a=0,c=0,u=Buffer.alloc((i+1)*n),d=r[0];for(let f=0;f<n;f++){if(r.length>1){let p=1/0;for(let m=0;m<r.length;m++){let h=lv[r[m]](t,c,i,o);h<p&&(d=r[m],p=h)}}u[a]=d,a++,cv[d](t,c,i,u,a,o),a+=i,c+=i}return u}});var Dl=K((bM,Ih)=>{"use strict";var xt=To(),uv=Ml(),dv=Mh(),fv=Lh(),pv=require("zlib"),as=Ih.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||pv.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:xt.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:xt.COLORTYPE_COLOR_ALPHA,[xt.COLORTYPE_GRAYSCALE,xt.COLORTYPE_COLOR,xt.COLORTYPE_COLOR_ALPHA,xt.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([xt.COLORTYPE_GRAYSCALE,xt.COLORTYPE_COLOR,xt.COLORTYPE_COLOR_ALPHA,xt.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")};as.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};as.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};as.prototype.filterData=function(t,e,n){let s=dv(t,e,n,this._options),o=xt.COLORTYPE_TO_BPP_MAP[this._options.colorType];return fv(s,e,n,this._options,o)};as.prototype._packChunk=function(t,e){let n=e?e.length:0,s=Buffer.alloc(n+12);return s.writeUInt32BE(n,0),s.writeUInt32BE(t,4),e&&e.copy(s,8),s.writeInt32BE(uv.crc32(s.slice(4,s.length-4)),s.length-4),s};as.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*xt.GAMMA_DIVISION),0),this._packChunk(xt.TYPE_gAMA,e)};as.prototype.packIHDR=function(t,e){let n=Buffer.alloc(13);return n.writeUInt32BE(t,0),n.writeUInt32BE(e,4),n[8]=this._options.bitDepth,n[9]=this._options.colorType,n[10]=0,n[11]=0,n[12]=0,this._packChunk(xt.TYPE_IHDR,n)};as.prototype.packIDAT=function(t){return this._packChunk(xt.TYPE_IDAT,t)};as.prototype.packIEND=function(){return this._packChunk(xt.TYPE_IEND,null)}});var Fh=K((_M,qh)=>{"use strict";var hv=require("util"),Dh=require("stream"),mv=To(),gv=Dl(),jh=qh.exports=function(t){Dh.call(this);let e=t||{};this._packer=new gv(e),this._deflate=this._packer.createDeflate(),this.readable=!0};hv.inherits(jh,Dh);jh.prototype.pack=function(t,e,n,s){this.emit("data",Buffer.from(mv.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),s&&this.emit("data",this._packer.packGAMA(s));let o=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(r){this.emit("data",this._packer.packIDAT(r))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(o)}});var Gh=K((hr,Yh)=>{"use strict";var Bh=require("assert").ok,Ro=require("zlib"),yv=require("util"),Uh=require("buffer").kMaxLength;function Os(t){if(!(this instanceof Os))return new Os(t);t&&t.chunkSize<Ro.Z_MIN_CHUNK&&(t.chunkSize=Ro.Z_MIN_CHUNK),Ro.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 $v(t){return new Os(t)}function Wh(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Os.prototype._processChunk=function(t,e,n){if(typeof n=="function")return Ro.Inflate._processChunk.call(this,t,e,n);let s=this,o=t&&t.length,r=this._chunkSize-this._offset,i=this._maxLength,a=0,c=[],u=0,d;this.on("error",function(h){d=h});function f(h,g){if(s._hadError)return;let $=r-g;if(Bh($>=0,"have should not go down"),$>0){let w=s._buffer.slice(s._offset,s._offset+$);if(s._offset+=$,w.length>i&&(w=w.slice(0,i)),c.push(w),u+=w.length,i-=w.length,i===0)return!1}return(g===0||s._offset>=s._chunkSize)&&(r=s._chunkSize,s._offset=0,s._buffer=Buffer.allocUnsafe(s._chunkSize)),g===0?(a+=o-h,o=h,!0):!1}Bh(this._handle,"zlib binding closed");let p;do p=this._handle.writeSync(e,t,a,o,this._buffer,this._offset,r),p=p||this._writeState;while(!this._hadError&&f(p[0],p[1]));if(this._hadError)throw d;if(u>=Uh)throw Wh(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Uh.toString(16)+" bytes");let m=Buffer.concat(c,u);return Wh(this),m};yv.inherits(Os,Ro.Inflate);function wv(t,e){if(typeof e=="string"&&(e=Buffer.from(e)),!(e instanceof Buffer))throw new TypeError("Not a string or buffer");let n=t._finishFlushFlag;return n==null&&(n=Ro.Z_FINISH),t._processChunk(e,n)}function Hh(t,e){return wv(new Os(e),t)}Yh.exports=hr=Hh;hr.Inflate=Os;hr.createInflate=$v;hr.inflateSync=Hh});var jl=K((xM,zh)=>{"use strict";var Kh=zh.exports=function(t){this._buffer=t,this._reads=[]};Kh.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Kh.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 Vh=K(Xh=>{"use strict";var bv=jl(),_v=Cl();Xh.process=function(t,e){let n=[],s=new bv(t);return new _v(e,{read:s.read.bind(s),write:function(r){n.push(r)},complete:function(){}}).start(),s.process(),Buffer.concat(n)}});var em=K((vM,Qh)=>{"use strict";var Jh=!0,Zh=require("zlib"),xv=Gh();Zh.deflateSync||(Jh=!1);var Sv=jl(),vv=Vh(),kv=Nl(),Ev=Pl(),Tv=Ll();Qh.exports=function(t,e){if(!Jh)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function s(S){n=S}let o;function r(S){o=S}function i(S){o.transColor=S}function a(S){o.palette=S}function c(){o.alpha=!0}let u;function d(S){u=S}let f=[];function p(S){f.push(S)}let m=new Sv(t);if(new kv(e,{read:m.read.bind(m),error:s,metadata:r,gamma:d,palette:a,transColor:i,inflateData:p,simpleTransparency:c}).start(),m.process(),n)throw n;let g=Buffer.concat(f);f.length=0;let $;if(o.interlace)$=Zh.inflateSync(g);else{let x=((o.width*o.bpp*o.depth+7>>3)+1)*o.height;$=xv(g,{chunkSize:x,maxLength:x})}if(g=null,!$||!$.length)throw new Error("bad png - invalid inflate data response");let w=vv.process($,o);g=null;let k=Ev.dataToBitMap(w,o);w=null;let E=Tv(k,o,e.skipRescale);return o.data=E,o.gamma=u||0,o}});var om=K((kM,sm)=>{"use strict";var tm=!0,nm=require("zlib");nm.deflateSync||(tm=!1);var Rv=To(),Cv=Dl();sm.exports=function(t,e){if(!tm)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},s=new Cv(n),o=[];o.push(Buffer.from(Rv.PNG_SIGNATURE)),o.push(s.packIHDR(t.width,t.height)),t.gamma&&o.push(s.packGAMA(t.gamma));let r=s.filterData(t.data,t.width,t.height),i=nm.deflateSync(r,s.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return o.push(s.packIDAT(i)),o.push(s.packIEND()),Buffer.concat(o)}});var rm=K(ql=>{"use strict";var Av=em(),Ov=om();ql.read=function(t,e){return Av(t,e||{})};ql.write=function(t,e){return Ov(t,e)}});var cm=K(am=>{"use strict";var Mv=require("util"),im=require("stream"),Nv=Ah(),Pv=Fh(),Lv=rm(),At=am.PNG=function(t){im.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 Nv(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 Pv(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"))};Mv.inherits(At,im);At.sync=Lv;At.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)};At.prototype.parse=function(t,e){if(e){let n,s;n=function(o){this.removeListener("error",s),this.data=o,e(null,this)}.bind(this),s=function(o){this.removeListener("parsed",n),e(o,null)}.bind(this),this.once("parsed",n),this.once("error",s)}return this.end(t),this};At.prototype.write=function(t){return this._parser.write(t),!0};At.prototype.end=function(t){this._parser.end(t)};At.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};At.prototype._gamma=function(t){this.gamma=t};At.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};At.bitblt=function(t,e,n,s,o,r,i,a){if(n|=0,s|=0,o|=0,r|=0,i|=0,a|=0,n>t.width||s>t.height||n+o>t.width||s+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+o>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let c=0;c<r;c++)t.data.copy(e.data,(a+c)*e.width+i<<2,(s+c)*t.width+n<<2,(s+c)*t.width+n+o<<2)};At.prototype.bitblt=function(t,e,n,s,o,r,i){return At.bitblt(this,t,e,n,s,o,r,i),this};At.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let s=t.width*e+n<<2;for(let o=0;o<3;o++){let r=t.data[s+o]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[s+o]=Math.round(r*255)}}t.gamma=0}};At.prototype.adjustGamma=function(){At.adjustGamma(this)}});var pm={};Aw(pm,{default:()=>dm});function dm(t,e,n,s,o,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:c=[255,255,0],diffColor:u=[255,0,0],includeAA:d,diffColorAlt:f,diffMask:p}=r;if(!Fl(t)||!Fl(e)||n&&!Fl(n))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||n&&n.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==s*o*4)throw new Error("Image data size does not match width/height.");let m=s*o,h=new Uint32Array(t.buffer,t.byteOffset,m),g=new Uint32Array(e.buffer,e.byteOffset,m),$=!0;for(let T=0;T<m;T++)if(h[T]!==g[T]){$=!1;break}if($){if(n&&!p)for(let T=0;T<m;T++)um(t,4*T,a,n);return 0}let w=35215*i*i,[k,E,S]=c,[x,C,H]=u,[q,ie,le]=f||u,te=0;for(let T=0;T<o;T++)for(let Te=0;Te<s;Te++){let G=T*s+Te,z=G*4,fe=h[G]===g[G]?0:fm(t,e,z,z,!1);if(Math.abs(fe)>w){let Ee=lm(t,Te,T,s,o,h,g)||lm(e,Te,T,s,o,g,h);!d&&Ee?n&&!p&&aa(n,z,k,E,S):(n&&(fe<0?aa(n,z,q,ie,le):aa(n,z,x,C,H)),te++)}else n&&!p&&um(t,z,a,n)}return te}function Fl(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function lm(t,e,n,s,o,r,i){let a=Math.max(e-1,0),c=Math.max(n-1,0),u=Math.min(e+1,s-1),d=Math.min(n+1,o-1),f=n*s+e,p=e===a||e===u||n===c||n===d?1:0,m=0,h=0,g=0,$=0,w=0,k=0;for(let E=a;E<=u;E++)for(let S=c;S<=d;S++){if(E===e&&S===n)continue;let x=fm(t,t,f*4,(S*s+E)*4,!0);if(x===0){if(p++,p>2)return!1}else x<m?(m=x,g=E,$=S):x>h&&(h=x,w=E,k=S)}return m===0||h===0?!1:ia(r,g,$,s,o)&&ia(i,g,$,s,o)||ia(r,w,k,s,o)&&ia(i,w,k,s,o)}function ia(t,e,n,s,o){let r=Math.max(e-1,0),i=Math.max(n-1,0),a=Math.min(e+1,s-1),c=Math.min(n+1,o-1),u=t[n*s+e],d=e===r||e===a||n===i||n===c?1:0;for(let f=r;f<=a;f++)for(let p=i;p<=c;p++)if(!(f===e&&p===n)&&(d+=+(u===t[p*s+f]),d>2))return!0;return!1}function fm(t,e,n,s,o){let r=t[n],i=t[n+1],a=t[n+2],c=t[n+3],u=e[s],d=e[s+1],f=e[s+2],p=e[s+3],m=r-u,h=i-d,g=a-f,$=c-p;if(!m&&!h&&!g&&!$)return 0;if(c<255||p<255){let x=48+159*(n%2),C=48+159*((n/1.618033988749895|0)%2),H=48+159*((n/2.618033988749895|0)%2);m=(r*c-u*p-x*$)/255,h=(i*c-d*p-C*$)/255,g=(a*c-f*p-H*$)/255}let w=m*.29889531+h*.58662247+g*.11448223;if(o)return w;let k=m*.59597799-h*.2741761-g*.32180189,E=m*.21147017-h*.52261711+g*.31114694,S=.5053*w*w+.299*k*k+.1957*E*E;return w>0?-S:S}function aa(t,e,n,s,o){t[e+0]=n,t[e+1]=s,t[e+2]=o,t[e+3]=255}function um(t,e,n,s){let o=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*n*t[e+3]/255;aa(s,e,o,o,o)}var hm=Cw(()=>{});var Ms=K((RM,wm)=>{var Kn=require("fs"),Iv=require("path"),Dv=require("os"),jv="nex-visual-";function gm(t){return Iv.join(Dv.tmpdir(),`${jv}${Date.now()}-${t}`)}var Bl=null;function ca(){return Bl||(Bl=cm().PNG),Bl}var Ul=null;function qv(){if(!Ul){let t=(hm(),Mw(pm));Ul=t.default||t}return Ul}function Yl(t,e,{threshold:n=.1}={}){let s=ca(),o=qv(),r=s.sync.read(Kn.readFileSync(t)),i=s.sync.read(Kn.readFileSync(e)),a=Math.max(r.width,i.width),c=Math.max(r.height,i.height),u=mm(r,a,c),d=mm(i,a,c),f=new s({width:a,height:c}),p=o(u,d,f.data,a,c,{threshold:n,includeAA:!1}),m=a*c,h=(p/m*100).toFixed(1),g=Fv(f.data,a,c,3,3),$=gm("diff.png");return Kn.writeFileSync($,s.sync.write(f),{mode:384}),{diffPath:$,diffPercent:parseFloat(h),totalPixels:m,changedPixels:p,regionSummary:g,beforePath:t,afterPath:e,width:a,height:c}}function mm(t,e,n){if(t.width===e&&t.height===n)return t.data;let s=Buffer.alloc(e*n*4,0);for(let o=0;o<t.height;o++){let r=o*t.width*4,i=o*e*4;t.data.copy(s,i,r,r+t.width*4)}return s}function Fv(t,e,n,s,o){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/s),a=Math.ceil(n/o),c=[];for(let u=0;u<o;u++)for(let d=0;d<s;d++){let f=0,p=0,m=d*i,h=u*a,g=Math.min(m+i,e),$=Math.min(h+a,n);for(let w=h;w<$;w++)for(let k=m;k<g;k++){p++;let E=(w*e+k)*4;(t[E]>0||t[E+1]>0)&&f++}if(f>0){let w=(f/p*100).toFixed(1),k=r[u]&&r[u][d]?r[u][d]:`row${u}-col${d}`;c.push({name:k,changedPercent:parseFloat(w),changed:f,total:p})}}return c.sort((u,d)=>d.changedPercent-u.changedPercent),c}var ym=[{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 Bv(t,{viewports:e=ym,height:n=800,fullPage:s=!1,timeout:o=3e4}={}){let{browserScreenshot:r}=Gn(),i=[];for(let a of e){let c=await r(t,{width:a.width,height:n,fullPage:s,timeout:o});i.push({label:a.label,width:a.width,path:c.path,base64:c.base64,media_type:c.media_type})}return i}function $m(t,e=[]){let n=ca(),s=n.sync.read(Kn.readFileSync(t));for(let i of e){let a=Uv(i.color||"#FF0000");i.type==="box"?(Wv(s,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&Hl(s,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(Hv(s,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&Hl(s,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(Yv(s,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&Hl(s,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let o=gm("annotated.png");Kn.writeFileSync(o,n.sync.write(s),{mode:384});let r=Kn.readFileSync(o).toString("base64");return{path:o,base64:r,media_type:"image/png"}}function Uv(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,n,s){if(e<0||n<0||e>=t.width||n>=t.height)return;let o=(n*t.width+e)*4;t.data[o]=s.r,t.data[o+1]=s.g,t.data[o+2]=s.b,t.data[o+3]=s.a}function Wv(t,e,n,s,o,r,i=3){for(let a=0;a<i;a++){for(let c=0;c<s;c++)On(t,e+c,n+a,r),On(t,e+c,n+o-1-a,r);for(let c=0;c<o;c++)On(t,e+a,n+c,r),On(t,e+s-1-a,n+c,r)}}function Wl(t,e,n,s,o,r,i=3){let a=Math.abs(s-e),c=Math.abs(o-n),u=e<s?1:-1,d=n<o?1:-1,f=a-c,p=e,m=n;for(;;){let h=Math.floor(i/2);for(let $=-h;$<=h;$++)for(let w=-h;w<=h;w++)On(t,p+$,m+w,r);if(p===s&&m===o)break;let g=2*f;g>-c&&(f-=c,p+=u),g<a&&(f+=a,m+=d)}}function Hv(t,e,n,s,o,r,i=3){Wl(t,e,n,s,o,r,i);let a=Math.atan2(o-n,s-e),c=15,u=a+Math.PI*.8,d=a-Math.PI*.8;Wl(t,s,o,Math.round(s+c*Math.cos(u)),Math.round(o+c*Math.sin(u)),r,i),Wl(t,s,o,Math.round(s+c*Math.cos(d)),Math.round(o+c*Math.sin(d)),r,i)}function Yv(t,e,n,s,o,r=3){for(let i=0;i<r;i++){let a=s-i;for(let c=0;c<360;c+=.5){let u=c*Math.PI/180,d=Math.round(e+a*Math.cos(u)),f=Math.round(n+a*Math.sin(u));On(t,d,f,o)}}}function Hl(t,e,n,s,o){let i=s.length*6+4,a=12;for(let c=0;c<a;c++)for(let u=0;u<i;u++)On(t,e+u,n+c,{r:0,g:0,b:0,a:200});for(let c=0;c<i;c++)On(t,e+c,n+a-1,o),On(t,e+c,n+a-2,o);for(let c=0;c<s.length;c++){let u=e+2+c*6;for(let d=2;d<9;d++)for(let f=0;f<4;f++)On(t,u+f,n+d,o)}}async function*Gv(t,e,{maxIterations:n=20,hmrDelay:s=1500,width:o=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=Gn(),c=Kv("chokidar"),u=await a(t,{width:o,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:u.path,base64:u.base64,media_type:u.media_type},!c){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let d=0,f=!1,p=c.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});p.on("change",()=>{f=!0});try{for(;d<n;){await Xv(()=>f,3e5),f=!1,d++,await zv(s);let m=await a(t,{width:o,height:r,timeout:i}),h=null;try{h=Yl(u.path,m.path)}catch{}u=m,yield{iteration:d,type:"change",path:m.path,base64:m.base64,media_type:m.media_type,diff:h?{diffPath:h.diffPath,diffPercent:h.diffPercent,changedPixels:h.changedPixels,regions:h.regionSummary}:null}}}finally{await p.close()}}function Kv(t){try{return require(t)}catch{return null}}function zv(t){return new Promise(e=>setTimeout(e,t))}function Xv(t,e=6e4){return new Promise((n,s)=>{let o=setInterval(()=>{t()&&(clearInterval(o),clearTimeout(r),n())},200),r=setTimeout(()=>{clearInterval(o),s(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function Vv(t,{sampleRate:e=4}={}){let s=ca().sync.read(Kn.readFileSync(t)),o=new Map;for(let u=0;u<s.height;u+=e)for(let d=0;d<s.width;d+=e){let f=(u*s.width+d)*4,p=s.data[f],m=s.data[f+1],h=s.data[f+2];if(s.data[f+3]<128)continue;let $=Math.round(p/8)*8,w=Math.round(m/8)*8,k=Math.round(h/8)*8,E=`${$},${w},${k}`;o.set(E,(o.get(E)||0)+1)}let r=[...o.entries()].sort((u,d)=>d[1]-u[1]).slice(0,20),i=r.reduce((u,d)=>u+d[1],0),a=r.map(([u,d])=>{let[f,p,m]=u.split(",").map(Number);return{hex:Jv(f,p,m),rgb:`rgb(${f}, ${p}, ${m})`,frequency:parseFloat((d/i*100).toFixed(1)),category:Zv(f,p,m)}}),c=Qv(s);return{colors:a,spacing:c,dimensions:{width:s.width,height:s.height},imagePath:t}}function Jv(t,e,n){return"#"+[t,e,n].map(s=>Math.min(255,s).toString(16).padStart(2,"0")).join("")}function Zv(t,e,n){let s=(t*299+e*587+n*114)/1e3;return s>240?"white/background":s<30?"black/text":s<80?"dark":t>200&&e<100&&n<100?"red/danger":t<100&&e>150&&n<100?"green/success":t<100&&e<100&&n>200?"blue/primary":t>200&&e>200&&n<100?"yellow/warning":t>200&&e>100&&n<50?"orange/accent":s>200?"light/subtle":"midtone"}function Qv(t){let e=[],n=!1,s=0,o=ek(t);for(let i=0;i<t.height;i++){let a=!0;for(let c=0;c<t.width;c+=4){let u=(i*t.width+c)*4;if(Math.abs(t.data[u]-o.r)>20||Math.abs(t.data[u+1]-o.g)>20||Math.abs(t.data[u+2]-o.b)>20){a=!1;break}}if(a&&n)n=!1,s=i;else if(!a&&!n&&(n=!0,s>0)){let c=i-s;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 ek(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],n=0,s=0,o=0;for(let[r,i]of e){let a=(i*t.width+r)*4;n+=t.data[a],s+=t.data[a+1],o+=t.data[a+2]}return{r:Math.round(n/4),g:Math.round(s/4),b:Math.round(o/4)}}async function tk(t,e,{width:n,height:s=800,fullPage:o=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=Gn(),u=ca().sync.read(Kn.readFileSync(e)),d=n||u.width,f=s||u.height,p=await a(t,{width:d,height:f,fullPage:o,timeout:i}),m=Yl(e,p.path,{threshold:r}),h=$m(p.path,m.regionSummary.filter(g=>g.changedPercent>1).map((g,$)=>{let E=Math.ceil(m.width/3),S=Math.ceil(m.height/3),x=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],C=0,H=0;for(let q=0;q<3;q++)for(let ie=0;ie<3;ie++)x[q][ie]===g.name&&(C=ie,H=q);return{type:"box",x:C*E+2,y:H*S+2,width:E-4,height:S-4,label:`${g.name}: ${g.changedPercent}%`,color:g.changedPercent>10?"#FF0000":"#FFAA00"}}));return{livePath:p.path,referencePath:e,diffPath:m.diffPath,annotatedPath:h.path,diffPercent:m.diffPercent,changedPixels:m.changedPixels,totalPixels:m.totalPixels,regions:m.regionSummary,liveBase64:p.base64,diffBase64:Kn.readFileSync(m.diffPath).toString("base64"),annotatedBase64:h.base64}}wm.exports={pixelDiff:Yl,responsiveSweep:Bv,annotateImage:$m,visualWatch:Gv,extractDesignTokens:Vv,designCompare:tk,DEFAULT_VIEWPORTS:ym}});var la=K((CM,bm)=>{var{C:Ke}=Ye(),gr="",Ot=[],mr=0,Ns=null;function nk(t){Ns=t}function sk(t,e){gr=t,Ot=[],mr=0;for(let s of e){mr++;let o=`t${mr}`;Ot.push({id:o,description:s.description||s.title||s.name||s.task||`Task ${mr}`,status:"pending",dependsOn:s.depends_on||[],result:null})}let n=Ot.map(s=>({...s}));return Ns&&Ns("create",{name:t,tasks:n}),n}function ok(t,e,n){let s=Ot.find(o=>o.id===t);return s?(s.status=e,n!==void 0&&(s.result=n),Ns&&Ns("update",{id:t,status:e,result:n}),{...s}):null}function rk(){return{name:gr,tasks:Ot.map(t=>({...t}))}}function ik(){gr="",Ot=[],mr=0,Ns&&Ns("clear",{})}function ak(){return Ot.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=Ot.find(s=>s.id===e);return n&&n.status==="done"}))}function ck(){if(Ot.length===0)return`${Ke.dim}No active tasks${Ke.reset}`;let t=[];gr&&(t.push(` ${Ke.bold}${Ke.cyan}Tasks: ${gr}${Ke.reset}`),t.push(` ${Ke.dim}${"\u2500".repeat(40)}${Ke.reset}`));for(let o of Ot){let r,i;switch(o.status){case"done":r="\u2713",i=Ke.green;break;case"in_progress":r="\u2192",i=Ke.cyan;break;case"failed":r="\u2717",i=Ke.red;break;default:r="\xB7",i=Ke.dim}let a=o.dependsOn.length>0?` ${Ke.dim}(after: ${o.dependsOn.join(", ")})${Ke.reset}`:"",c=`[${o.status}]`,u=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Ke.reset} ${Ke.bold}${o.id}${Ke.reset} ${u.padEnd(40)} ${i}${c}${Ke.reset}${a}`),o.result&&o.status==="done"){let d=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Ke.dim}\u2192 ${d}${Ke.reset}`)}}let e=Ot.filter(o=>o.status==="done").length,n=Ot.filter(o=>o.status==="failed").length,s=Ot.length;return t.push(` ${Ke.dim}${"\u2500".repeat(40)}${Ke.reset}`),t.push(` ${Ke.dim}${e}/${s} done${n>0?`, ${n} failed`:""}${Ke.reset}`),t.join(`
|
|
131
131
|
`)}function lk(){return Ot.length>0&&Ot.some(t=>t.status==="pending"||t.status==="in_progress")}bm.exports={createTasks:sk,updateTask:ok,getTaskList:rk,clearTasks:ik,getReadyTasks:ak,renderTaskList:ck,setOnChange:nk,hasActiveTasks:lk}});var ua=K((AM,xm)=>{var yr={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
|
|
132
132
|
Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
|
|
133
133
|
You excel at sysadmin, frontend, and multi-step coding tasks.
|
|
@@ -141,7 +141,7 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:2e4,staleAbort:6e4,i
|
|
|
141
141
|
Prioritize decisive, targeted edits. Read only what you need, then fix.
|
|
142
142
|
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.
|
|
143
143
|
Trust your reasoning. Use tools thoroughly when the task demands it.
|
|
144
|
-
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},_m={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function uk(t){let e=(t||"").toLowerCase(),n=null,s=0;for(let r of Object.keys(yr))e.startsWith(r)&&r.length>s&&(n=r,s=r.length);let o=n?{...yr[n]}:{..._m};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 dk(t){let e=(t||"").toLowerCase(),n=null,s=0;for(let o of Object.keys(yr))e.startsWith(o)&&o.length>s&&(n=o,s=o.length);return n&&yr[n].briefing||""}xm.exports={getModelProfile:uk,getModelBriefing:dk,PROFILES:yr,DEFAULTS:_m}});var
|
|
144
|
+
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},_m={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function uk(t){let e=(t||"").toLowerCase(),n=null,s=0;for(let r of Object.keys(yr))e.startsWith(r)&&r.length>s&&(n=r,s=r.length);let o=n?{...yr[n]}:{..._m};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 dk(t){let e=(t||"").toLowerCase(),n=null,s=0;for(let o of Object.keys(yr))e.startsWith(o)&&o.length>s&&(n=o,s=o.length);return n&&yr[n].briefing||""}xm.exports={getModelProfile:uk,getModelBriefing:dk,PROFILES:yr,DEFAULTS:_m}});var Kl=K((OM,Rm)=>{var{callChat:fk}=We(),{estimateTokens:Gl}=Ht(),Sm=process.env.NEX_COMPACTION!=="false",vm=6,km=2e3,Em=3,pk=`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.
|
|
145
145
|
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.
|
|
146
146
|
|
|
147
147
|
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:
|
|
@@ -173,11 +173,11 @@ Format your output as:
|
|
|
173
173
|
|
|
174
174
|
<summary>
|
|
175
175
|
[Sections 1-9 above]
|
|
176
|
-
</summary>`,Ps=0;async function hk(t){if(!Sm||t.length<vm||Ps>=Em)return null;let e=[{role:"system",content:pk},{role:"user",content:Tm(t)}];try{let s=((await fk(e,[],{temperature:0,maxTokens:km})).content||"").trim();if(!s)return Ps++,null;let o=s.match(/<summary>([\s\S]*?)<\/summary>/);if(o?s=o[1].trim():s=s.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!s)return Ps++,null;let r=t.reduce((a,c)=>a+
|
|
176
|
+
</summary>`,Ps=0;async function hk(t){if(!Sm||t.length<vm||Ps>=Em)return null;let e=[{role:"system",content:pk},{role:"user",content:Tm(t)}];try{let s=((await fk(e,[],{temperature:0,maxTokens:km})).content||"").trim();if(!s)return Ps++,null;let o=s.match(/<summary>([\s\S]*?)<\/summary>/);if(o?s=o[1].trim():s=s.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!s)return Ps++,null;let r=t.reduce((a,c)=>a+Gl(c.content||"")+(c.tool_calls?Gl(JSON.stringify(c.tool_calls)):0),0),i=Gl(s);return i>=r*.8?(Ps++,null):(Ps=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
177
177
|
${s}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return Ps++,null}}function mk(){Ps=0}function Tm(t){return t.map(e=>{let n=e.role==="tool"?"tool_result":e.role,s=(e.content||"").substring(0,500);if(e.tool_calls){let o=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${n}] ${s}
|
|
178
178
|
tools: ${o}`}return`[${n}] ${s}`}).join(`
|
|
179
179
|
|
|
180
|
-
`)}Rm.exports={compactMessages:hk,formatMessagesForSummary:Tm,resetCompactionFailures:mk,COMPACTION_ENABLED:Sm,COMPACTION_MIN_MESSAGES:vm,COMPACTION_SUMMARY_BUDGET:km,MAX_CONSECUTIVE_FAILURES:Em}});var Ht=K((MM,jm)=>{var gk=require("path");function Am(){return We().getActiveModel()}var yk={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},$k={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},Ls=new Map,Cm=1e3,
|
|
180
|
+
`)}Rm.exports={compactMessages:hk,formatMessagesForSummary:Tm,resetCompactionFailures:mk,COMPACTION_ENABLED:Sm,COMPACTION_MIN_MESSAGES:vm,COMPACTION_SUMMARY_BUDGET:km,MAX_CONSECUTIVE_FAILURES:Em}});var Ht=K((MM,jm)=>{var gk=require("path");function Am(){return We().getActiveModel()}var yk={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},$k={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},Ls=new Map,Cm=1e3,zl=new WeakMap,Is=null;function wk(){if(Is!==null)return Is;try{let t=Am(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[s,o]of Object.entries($k))if(n.startsWith(s))return Is=o,Is;return Is=yk[e]||4,Is}catch{return 4}}function bk(){Is=null}function Ds(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=120?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length>>1,(t.length>>1)+30)}:${t.substring(t.length-30)}`,n=Ls.get(e);if(n!==void 0)return Ls.delete(e),Ls.set(e,n),n;let s=Math.ceil(t.length/wk());if(Ls.size>=Cm){let o=Cm>>1,r=Ls.keys();for(let i=0;i<o;i++)Ls.delete(r.next().value)}return Ls.set(e,s),s}function _k(t){if(zl.has(t))return zl.get(t);let e=JSON.stringify(t);return zl.set(t,e),e}function js(t){let n=4;if(t.content&&(n+=Ds(t.content)),t.tool_calls)for(let s of t.tool_calls){n+=4,n+=Ds(s.function?.name||"");let o=s.function?.arguments;typeof o=="string"?n+=Ds(o):o&&(n+=Ds(JSON.stringify(o)))}return n}function hn(t){let e=0;for(let n of t)e+=js(n);return e}function xk(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let n=t?t.length:0,s=e.length,o=0;for(let r=n;r<s;r++)o+=js(e[r]);return o}var Xl=new WeakMap;function da(t){if(!t||t.length===0)return 0;if(Xl.has(t))return Xl.get(t);let e=Ds(JSON.stringify(t));return Xl.set(t,e),e}function fa(){return Am()?.contextWindow||32768}var Mt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function Sk(t,e){let n=t.length>0?t[t.length-1]:null,s=e?e.length:0;if(Mt.result&&t.length===Mt.msgCount&&n===Mt.lastMsgRef&&s===Mt.toolCount)return Mt.result;let o,r,i,a;if(Mt.messagesRef===t&&t.length>Mt.msgCount&&Mt.msgCount>=0){o=Mt.messageTokens,r=Mt.systemTokens,i=Mt.conversationTokens,a=Mt.toolResultTokens;for(let m=Mt.msgCount;m<t.length;m++){let h=js(t[m]);o+=h,t[m].role==="system"?r+=h:t[m].role==="tool"?a+=h:i+=h}}else{o=0,r=0,i=0,a=0;for(let m of t){let h=js(m);o+=h,m.role==="system"?r+=h:m.role==="tool"?a+=h:i+=h}}let c=da(e),u=o+c,d=fa(),f=d>0?u/d*100:0,p={used:u,limit:d,percentage:Math.round(f*10)/10,breakdown:{system:r,conversation:i,toolResults:a,toolDefinitions:c},messageCount:t.length};return Mt={msgCount:t.length,lastMsgRef:n,toolCount:s,result:p,messagesRef:t,messageTokens:o,systemTokens:r,conversationTokens:i,toolResultTokens:a},p}var $r=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,Om=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,Mm=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Nm={essential:.6,standard:.65,full:Math.min($r,.75)};function Pm(){if(process.env.NEX_COMPRESSION_THRESHOLD)return $r;try{let{getActiveTier:t}=fr(),e=t();return Nm[e]??$r}catch{return $r}}var vk=200,kk=1e3;function Lm(t,e){if(!t||t.length<=e)return t;let s=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=s)return t;let o=t.split(`
|
|
181
181
|
`);if(o.length<=10){let h=Math.floor(s*.6),g=Math.floor(s*.4),$=t.substring(0,h),w=t.substring(t.length-g);return $+`
|
|
182
182
|
...(${t.length} chars total)...
|
|
183
183
|
`+w}let r=Math.floor(o.length*.4),i=Math.floor(o.length*.4),a=[],c=0,u=Math.floor(s*.4);for(let h=0;h<r&&c<u;h++)if(c+o[h].length+1>u&&o[h].trim().startsWith("```")){a.push(o[h]),c+=o[h].length+1;let g=h+1;for(;g<o.length&&c<u*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 d=[],f=0,p=Math.floor(s*.4);for(let h=o.length-1;h>=o.length-i&&f<p;h--)if(f+o[h].length+1>p&&o[h].trim().startsWith("```")){d.push(o[h]),f+=o[h].length+1;let g=h-1;for(;g>=0&&f<p*1.5&&!o[g].trim().startsWith("```");)d.push(o[g]),f+=o[g].length+1,g--;g>=0&&o[g].trim().startsWith("```")&&(d.push(o[g]),f+=o[g].length+1),h=g}else d.push(o[h]),f+=o[h].length+1;d.reverse();let m=o.length-a.length-d.length;return a.join(`
|
|
@@ -189,14 +189,14 @@ ${s}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return Ps
|
|
|
189
189
|
`+o.map(r=>`- ${r}`).join(`
|
|
190
190
|
`)),s.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
|
|
191
191
|
${s.join(`
|
|
192
|
-
`)}`,_pinned:!0,_progressSnapshot:!0}}var Co={msgCount:-1,lastMsgRef:null,result:null};function Tk(){Co={msgCount:-1,lastMsgRef:null,result:null},Mt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function Rk(t,e,n={}){let s=t.length>0?t[t.length-1]:null;if(!n.force&&Co.result&&t.length===Co.msgCount&&s===Co.lastMsgRef)return Co.result;let o=n.threshold??Pm(),r=n.safetyMargin??Om,i=n.keepRecent??Mm,a=fa(),c=da(e),u=Math.floor(a*(o-r)),d=u-c,f=hn(t);if(f+c<=u){let te={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Co={msgCount:t.length,lastMsgRef:s,result:te},te}let m=f,h=null,g=0;t.length>0&&t[0].role==="system"&&(h=t[0],g=1);let $=Math.max(g,t.length-i),w=t.slice(g,$),k=t.slice($),E=w.map(te=>Ao(te,"light")),S=cs(h,E,k),x=hn(S);if(x+c<=u)return{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-x};if(E=w.map(te=>Ao(te,"medium")),S=cs(h,E,k),x=hn(S),x+c<=u)return{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-x};if(E=w.map(te=>Ao(te,"aggressive")),S=cs(h,E,k),x=hn(S),x+c<=u)return{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-x};let C=process.env.NEX_SKIP_COMPACTOR==="1",H=w.filter(te=>te._pinned),q=w.filter(te=>!te._compacted&&!te._pinned);if(!C&&q.length>=6)try{let{compactMessages:te}=
|
|
192
|
+
`)}`,_pinned:!0,_progressSnapshot:!0}}var Co={msgCount:-1,lastMsgRef:null,result:null};function Tk(){Co={msgCount:-1,lastMsgRef:null,result:null},Mt={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function Rk(t,e,n={}){let s=t.length>0?t[t.length-1]:null;if(!n.force&&Co.result&&t.length===Co.msgCount&&s===Co.lastMsgRef)return Co.result;let o=n.threshold??Pm(),r=n.safetyMargin??Om,i=n.keepRecent??Mm,a=fa(),c=da(e),u=Math.floor(a*(o-r)),d=u-c,f=hn(t);if(f+c<=u){let te={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Co={msgCount:t.length,lastMsgRef:s,result:te},te}let m=f,h=null,g=0;t.length>0&&t[0].role==="system"&&(h=t[0],g=1);let $=Math.max(g,t.length-i),w=t.slice(g,$),k=t.slice($),E=w.map(te=>Ao(te,"light")),S=cs(h,E,k),x=hn(S);if(x+c<=u)return{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-x};if(E=w.map(te=>Ao(te,"medium")),S=cs(h,E,k),x=hn(S),x+c<=u)return{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-x};if(E=w.map(te=>Ao(te,"aggressive")),S=cs(h,E,k),x=hn(S),x+c<=u)return{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-x};let C=process.env.NEX_SKIP_COMPACTOR==="1",H=w.filter(te=>te._pinned),q=w.filter(te=>!te._compacted&&!te._pinned);if(!C&&q.length>=6)try{let{compactMessages:te}=Kl(),T=await te(q);if(T){let Te=w.filter(Ee=>Ee._compacted&&!Ee._pinned),G=[...H,...Te,T.message],z=cs(h,G,k),fe=hn(z);if(fe+c<=u)return{messages:z,compressed:!0,compacted:!0,tokensRemoved:m-fe};w=G}}catch(te){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",te.message)}let ie=Dm([...E,...k]),le=E.map((te,T)=>({msg:te,score:te._pinned?1/0:Im(te,T,E.length,ie),tokens:js(te)}));for(;le.length>0&&x>d;){let te=-1;for(let T=0;T<le.length;T++)le[T].score!==1/0&&(te===-1||le[T].score<le[te].score)&&(te=T);if(te===-1)break;x-=le[te].tokens,le.splice(te,1)}return E=le.map(te=>te.msg),S=cs(h,E,k),x=hn(S),{messages:S,compressed:!0,compacted:!1,tokensRemoved:m-x}}function cs(t,e,n){let s=[];return t&&s.push(t),s.push(...e,...n),s}function Ck(t,e){if(!t)return"";if(Ds(t)<=e)return t;let s=e*4,o=t.split(`
|
|
193
193
|
`),r=Math.floor(s*.6),i=Math.floor(s*.4),a="",c=0;for(let m of o){if(a.length+m.length+1>r)break;a+=(a?`
|
|
194
194
|
`:"")+m,c++}let u="",d=0;for(let m=o.length-1;m>=c;m--){let h=o[m]+(u?`
|
|
195
195
|
`:"")+u;if(h.length>i)break;u=h,d++}let p=`
|
|
196
196
|
|
|
197
197
|
... (${o.length-c-d} lines omitted, ${o.length} total) ...
|
|
198
198
|
|
|
199
|
-
`;return a+p+u}var Ak=6;function Ok(t,e,n=!1){let s=fa(),o=da(e),r=Math.floor(s*(n?.35:.5))-o,i=hn(t),a=Math.floor(i*(n?.5:.8));r>a&&(r=a);let c=null,u=0;t.length>0&&t[0].role==="system"&&(c=t[0],u=1);let d=n?2:Ak,f=Math.max(u,t.length-d),p=t.slice(u,f),m=t.slice(f),h=p.map(x=>Ao(x,"aggressive"));n&&(m=m.map(x=>Ao(x,"aggressive")));let g=cs(c,h,m),$=hn(g);for(;h.length>0&&$>r;){let x=h.shift();$-=js(x)}n&&$>r&&(m=m.filter(C=>C.role==="user").slice(-1),g=cs(c,[],m),$=hn(g)),g=cs(c,h,m);let w=t.filter(x=>x.role==="user"),k=x=>{let C=typeof x.content=="string"?x.content:"";return C.startsWith("[SYSTEM WARNING]")||C.startsWith("[SYSTEM:")||C.startsWith("BLOCKED:")},E=w.find(x=>!k(x)),S=[...w].reverse().find(x=>!k(x));if(E&&!g.find(x=>x===E)){let x=g.findIndex(H=>H.role==="system"),C=x>=0?x+1:0;g.splice(C,0,E)}return S&&S!==E&&!g.find(x=>x===S)&&g.push(S),{messages:g,tokensRemoved:i-hn(g)}}jm.exports={estimateTokens:Ds,estimateMessageTokens:js,estimateMessagesTokens:hn,estimateDeltaTokens:xk,estimateToolsTokens:da,serializeMessage:_k,getContextWindow:fa,getUsage:Sk,compressMessage:Ao,compressToolResult:Lm,scoreMessageRelevance:Im,extractActiveFiles:Dm,buildProgressSnapshot:Ek,fitToContext:Rk,forceCompress:Ok,truncateFileContent:Ck,invalidateTokenRatioCache:bk,invalidateFitToContextCache:Tk,getEffectiveCompressionThreshold:Pm,COMPRESSION_THRESHOLD:$r,TIER_COMPRESSION_THRESHOLDS:Nm,SAFETY_MARGIN:Om,KEEP_RECENT:Mm}});var ga=K((PM,ig)=>{var{callStream:Mk,getActiveProviderName:ha,getActiveModelId:qm,getConfiguredProviders:Nk,getProvider:Fm,getActiveProvider:Bm,parseModelSpec:Um}=We(),{parseToolArgs:Wm}=bo(),{filterToolsForModel:Pk,getModelTier:pa}=fr(),{getModelBriefing:Lk}=ua(),{trackUsage:Hm,estimateTokens:Ym}=wo(),{MultiProgress:Ik,C:NM}=Ye();function Gm(t){return!t||typeof t!="string"?0:typeof Ym=="function"?Ym(t):Math.ceil(t.length/4)}var Xm=15,Dk=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),Km=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Vm=8,jk=2,ma=new Map,Jm=600*1e3;function qk(t,e){let n=ma.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<Jm?!1:(ma.set(t,{agentId:e,timestamp:Date.now()}),!0)}function wr(t){ma.delete(t)}function
|
|
199
|
+
`;return a+p+u}var Ak=6;function Ok(t,e,n=!1){let s=fa(),o=da(e),r=Math.floor(s*(n?.35:.5))-o,i=hn(t),a=Math.floor(i*(n?.5:.8));r>a&&(r=a);let c=null,u=0;t.length>0&&t[0].role==="system"&&(c=t[0],u=1);let d=n?2:Ak,f=Math.max(u,t.length-d),p=t.slice(u,f),m=t.slice(f),h=p.map(x=>Ao(x,"aggressive"));n&&(m=m.map(x=>Ao(x,"aggressive")));let g=cs(c,h,m),$=hn(g);for(;h.length>0&&$>r;){let x=h.shift();$-=js(x)}n&&$>r&&(m=m.filter(C=>C.role==="user").slice(-1),g=cs(c,[],m),$=hn(g)),g=cs(c,h,m);let w=t.filter(x=>x.role==="user"),k=x=>{let C=typeof x.content=="string"?x.content:"";return C.startsWith("[SYSTEM WARNING]")||C.startsWith("[SYSTEM:")||C.startsWith("BLOCKED:")},E=w.find(x=>!k(x)),S=[...w].reverse().find(x=>!k(x));if(E&&!g.find(x=>x===E)){let x=g.findIndex(H=>H.role==="system"),C=x>=0?x+1:0;g.splice(C,0,E)}return S&&S!==E&&!g.find(x=>x===S)&&g.push(S),{messages:g,tokensRemoved:i-hn(g)}}jm.exports={estimateTokens:Ds,estimateMessageTokens:js,estimateMessagesTokens:hn,estimateDeltaTokens:xk,estimateToolsTokens:da,serializeMessage:_k,getContextWindow:fa,getUsage:Sk,compressMessage:Ao,compressToolResult:Lm,scoreMessageRelevance:Im,extractActiveFiles:Dm,buildProgressSnapshot:Ek,fitToContext:Rk,forceCompress:Ok,truncateFileContent:Ck,invalidateTokenRatioCache:bk,invalidateFitToContextCache:Tk,getEffectiveCompressionThreshold:Pm,COMPRESSION_THRESHOLD:$r,TIER_COMPRESSION_THRESHOLDS:Nm,SAFETY_MARGIN:Om,KEEP_RECENT:Mm}});var ga=K((PM,ig)=>{var{callStream:Mk,getActiveProviderName:ha,getActiveModelId:qm,getConfiguredProviders:Nk,getProvider:Fm,getActiveProvider:Bm,parseModelSpec:Um}=We(),{parseToolArgs:Wm}=bo(),{filterToolsForModel:Pk,getModelTier:pa}=fr(),{getModelBriefing:Lk}=ua(),{trackUsage:Hm,estimateTokens:Ym}=wo(),{MultiProgress:Ik,C:NM}=Ye();function Gm(t){return!t||typeof t!="string"?0:typeof Ym=="function"?Ym(t):Math.ceil(t.length/4)}var Xm=15,Dk=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),Km=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Vm=8,jk=2,ma=new Map,Jm=600*1e3;function qk(t,e){let n=ma.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<Jm?!1:(ma.set(t,{agentId:e,timestamp:Date.now()}),!0)}function wr(t){ma.delete(t)}function Vl(){ma.clear()}function Jl(t){let e=(t.message||"").toLowerCase(),n=t.code||"";return e.includes("429")||e.includes("rate limit")?"rate_limit":e.includes("401")||e.includes("403")||e.includes("unauthorized")||e.includes("forbidden")?"auth":e.includes("context")&&(e.includes("too long")||e.includes("overflow")||e.includes("maximum"))||e.includes("400")&&(e.includes("content")||e.includes("length"))?"context_overflow":e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")?"server":e.includes("timed out")||e.includes("timeout")?"timeout":n==="ECONNRESET"||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ENOTFOUND"||e.includes("socket disconnected")||e.includes("tls")||e.includes("econnreset")||e.includes("fetch failed")||e.includes("etimedout")||e.includes("enotfound")?"network":"unknown"}function Zm(t){let e=Jl(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Qm(t,e,n){let s;for(let o=0;o<=Km;o++)try{return await Mk(t,e,n)}catch(r){s=r;let i=Jl(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<Km&&Zm(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(u=>setTimeout(u,c).unref());continue}throw r}throw s}var zm=new Set(["ask_user","task_list"]);function eg(t){return t>=2?new Set([...zm,"spawn_agents"]):zm}var Fk=new Set(["write_file","edit_file","patch_file"]),tg={explore:{allowedTools:new Set(["bash","read_file","list_directory","glob","grep","search_files","web_fetch","web_search"]),systemSuffix:"You are an exploration agent. Read and search code only. Do NOT modify any files."},review:{allowedTools:new Set(["read_file","list_directory","glob","grep","search_files"]),systemSuffix:"You are a code review agent. Read code and report findings. Do NOT make changes."},implement:{allowedTools:null,systemSuffix:""}},Bk=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Uk=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function ng(t){return Uk.test(t)?"full":Bk.test(t)?"essential":t.length>300?"full":"standard"}function sg(t){let e=Nk(),n=ha(),s=[...e].sort((o,r)=>(o.name===n?-1:1)-(r.name===n?-1:1));for(let o of s)for(let r of o.models)if(pa(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Wk={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Zl(t){if(t.model){let{provider:o,model:r}=Um(t.model),i=o?Fm(o):Bm(),a=o||ha();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=pa(r,a);return{provider:a,model:r,tier:c}}}let e=ng(t.task),n=Wk[e];if(n){let{provider:o,model:r}=Um(n),i=o?Fm(o):Bm(),a=o||ha();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=pa(r,a);return{provider:a,model:r,tier:c}}}let s=sg(e);if(s){let o=pa(s.model,s.provider);return{provider:s.provider,model:s.model,tier:o}}return{provider:null,model:null,tier:null}}async function og(t,e={},n=0){let s=n===0?Xm:Vm,o=Math.min(t.max_iterations||10,s),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},c=new Set,u=new Map,d=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
|
|
200
200
|
|
|
201
201
|
TASK: ${t.task}
|
|
202
202
|
${t.context?`
|
|
@@ -220,23 +220,23 @@ ERROR RECOVERY:
|
|
|
220
220
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
221
221
|
- After 2 failed attempts at the same operation, summarize the issue and stop.`,f=t.type&&tg[t.type],p=f&&f.systemSuffix?`
|
|
222
222
|
|
|
223
|
-
${f.systemSuffix}`:"",m=
|
|
223
|
+
${f.systemSuffix}`:"",m=Zl(t),h=m.provider,g=m.model,$=m.tier,w=Lk(g||qm()),E=[{role:"system",content:(w?`## Model Briefing
|
|
224
224
|
${w}
|
|
225
225
|
|
|
226
226
|
---
|
|
227
227
|
|
|
228
228
|
`:"")+d+p}];E.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:S,executeTool:x}=fn(),C=eg(n),H=Pk(S.filter(le=>!C.has(le.function.name)),$);if(f&&f.allowedTools&&(H=H.filter(le=>f.allowedTools.has(le.function.name))),g&&!t._skipLog){let le=$?` (${$})`:"";process.stderr.write(` [sub-agent: ${h}:${g}${le}]
|
|
229
229
|
`)}let q={};h&&(q.provider=h),g&&(q.model=g);let ie=new Set;try{for(let te=0;te<o;te++){let T=await Qm(E,H,q);if(!T||typeof T!="object")throw new Error("Empty or invalid response from provider");{let ve=h||ha(),be=g||qm();if(T.usage){let v=T.usage.prompt_tokens||0,L=T.usage.completion_tokens||0;a.input+=v,a.output+=L,Hm(ve,be,v,L)}else{let v=T.content||"",L=E.map(M=>typeof M.content=="string"?M.content:Array.isArray(M.content)?M.content.map(R=>typeof R=="string"?R:R.text||"").join(""):"").join(" "),O=Gm(L),D=Gm(v);a.input+=O,a.output+=D,a._estimated=!0,Hm(ve,be,O,D)}}let Te=T.content||"",G=T.tool_calls,z={role:"assistant",content:Te||""};if(G&&G.length>0&&(z.tool_calls=G),E.push(z),!G||G.length===0){for(let ve of c)wr(ve);return{task:t.task,status:"done",result:Te||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}let fe=new Set,Ee=G.map(ve=>{let be=ve.function.name,v=Wm(ve.function.arguments),L=ve.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!v)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${be}`,tool_call_id:L});if(["edit_file","patch_file"].includes(be)&&v.path){if(ie.has(v.path)||fe.has(v.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${v.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:L});fe.add(v.path)}let O=null;if(Fk.has(be)&&v.path){let M=require("path"),R=M.isAbsolute(v.path)?v.path:M.resolve(process.cwd(),v.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let N=M.relative(process.cwd(),R);if(t._readOnlyFiles.some(ne=>N===ne||N.startsWith(ne+"/")||R===ne||R.startsWith(ne+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${v.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:L})}if(c.has(R)||!qk(R,r))return Promise.resolve({role:"tool",content:`ERROR: File '${v.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:L});c.add(R),O=R}return i.push(be),e.onUpdate&&e.onUpdate({type:"tool_call",tool:be,agentId:r}),(be==="spawn_agents"?rg(v,n+1):x(be,v,{autoConfirm:!0,silent:!0})).then(M=>{O&&(wr(O),c.delete(O));let R=String(M??"");return v&&v.path&&(["edit_file","patch_file","write_file"].includes(be)&&R.startsWith("Edited:")?ie.add(v.path):be==="read_file"&&!R.startsWith("ERROR")&&ie.delete(v.path)),{role:"tool",content:R.length>2e4?R.substring(0,2e4)+`
|
|
230
|
-
...(truncated)`:R,tool_call_id:L}}).catch(M=>(O&&(wr(O),c.delete(O)),{role:"tool",content:`ERROR: ${M.message}`,tool_call_id:L}))}),Ae=await Promise.all(Ee);if(E.push(...Ae),te>=7&&E.length>12)try{let{compressMessage:ve}=Ht(),be=E.length-6;for(let v=1;v<be;v++)E[v]._subAgentCompressed||(E[v]={...ve(E[v],"light"),_subAgentCompressed:!0})}catch{}for(let ve=0;ve<G.length;ve++){let be=G[ve];if(be.function.name==="bash_exec"){let v=Wm(be.function.arguments);if((Ae[ve]?.content||"").startsWith("ERROR")&&v&&v.command){let O=v.command.replace(/\s+/g," ").trim().slice(0,100);u.set(O,(u.get(O)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${te+1}/${o}`)}for(let te of c)wr(te);let le=[...u.entries()].filter(([,te])=>te>=3).sort((te,T)=>T[1]-te[1]).slice(0,3).map(([te,T])=>`"${te}" (failed ${T}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:le,result:E[E.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}catch(le){for(let te of c)wr(te);return{task:t.task,status:"failed",result:`Error: ${le.message}`,toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}}async function rg(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let n=e===0?Dk:jk,s=e===0?Xm:Vm,o=(t.agents||[]).slice(0,n);if(o.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=o.map(d=>
|
|
231
|
-
`)}catch(d){return u.stop(),
|
|
232
|
-
`);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(u=>u.trim()).filter(Boolean):e[a]=c}n=s[2]}return{frontmatter:e,body:n}}function lg(t){let e=zn.join(Mo(),`${t}.md`);if(!nt.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=nt.readFileSync(e,"utf-8"),{frontmatter:s,body:o}=_r(n);return{name:t,content:n,body:o,frontmatter:s}}function Yk(t,e){let n=zn.join(Mo(),`${t}.md`);ag(n,e),zk(t,e),Gk()}function Gk(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=
|
|
233
|
-
`);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let c of ya(a))e[c]=(e[c]||0)+3}for(let i of ya(s||t))e[i]=(e[i]||0)+1;return e}function
|
|
230
|
+
...(truncated)`:R,tool_call_id:L}}).catch(M=>(O&&(wr(O),c.delete(O)),{role:"tool",content:`ERROR: ${M.message}`,tool_call_id:L}))}),Ae=await Promise.all(Ee);if(E.push(...Ae),te>=7&&E.length>12)try{let{compressMessage:ve}=Ht(),be=E.length-6;for(let v=1;v<be;v++)E[v]._subAgentCompressed||(E[v]={...ve(E[v],"light"),_subAgentCompressed:!0})}catch{}for(let ve=0;ve<G.length;ve++){let be=G[ve];if(be.function.name==="bash_exec"){let v=Wm(be.function.arguments);if((Ae[ve]?.content||"").startsWith("ERROR")&&v&&v.command){let O=v.command.replace(/\s+/g," ").trim().slice(0,100);u.set(O,(u.get(O)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${te+1}/${o}`)}for(let te of c)wr(te);let le=[...u.entries()].filter(([,te])=>te>=3).sort((te,T)=>T[1]-te[1]).slice(0,3).map(([te,T])=>`"${te}" (failed ${T}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:le,result:E[E.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}catch(le){for(let te of c)wr(te);return{task:t.task,status:"failed",result:`Error: ${le.message}`,toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}}async function rg(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let n=e===0?Dk:jk,s=e===0?Xm:Vm,o=(t.agents||[]).slice(0,n);if(o.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=o.map(d=>Zl(d)),c=o.map((d,f)=>{let p=a[f],m=p.model?` [${p.model}]`:"",h=d.task.substring(0,i-m.length);return`${r}Agent ${f+1}${m}: ${h}${d.task.length>h.length?"...":""}`}),u=new Ik(c);u.start();try{let d=o.map((g,$)=>{let w=a[$],k=Math.min(g.max_iterations||s,s),E=w.model?{...g,model:`${w.provider}:${w.model}`,_skipLog:!0,max_iterations:k}:{...g,_skipLog:!0,max_iterations:k};return og(E,{onUpdate:()=>{}},e).then(S=>(u.update($,S.status==="failed"?"error":"done"),S)).catch(S=>(u.update($,"error"),{task:g.task,status:"failed",result:`Error: ${S.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),f=await Promise.all(d);u.stop(),Vl();let p=["Sub-agent results:",""],m=0,h=0;for(let g=0;g<f.length;g++){let $=f[g],w=$.status==="done"?"\u2713":$.status==="truncated"?"\u26A0":"\u2717",k=$.modelSpec?` [${$.modelSpec}]`:"";p.push(`${w} Agent ${g+1}${k}: ${$.task}`),p.push(` Status: ${$.status}`),p.push(` Tools used: ${$.toolsUsed.length>0?$.toolsUsed.join(", "):"none"}`),p.push(` Result: ${$.result}`),$.repeatedFailures&&$.repeatedFailures.length>0&&p.push(` Repeated failures: ${$.repeatedFailures.join("; ")}`),p.push(""),m+=$.tokensUsed.input,h+=$.tokensUsed.output}return p.push(`Total sub-agent tokens: ${m} input + ${h} output`),p.join(`
|
|
231
|
+
`)}catch(d){return u.stop(),Vl(),`ERROR: Sub-agent execution failed: ${d.message}`}}ig.exports={runSubAgent:og,executeSpawnAgents:rg,clearAllLocks:Vl,classifyTask:ng,pickModelForTier:sg,resolveSubAgentModel:Zl,classifyError:Jl,isRetryableError:Zm,callWithRetry:Qm,getExcludedTools:eg,LOCK_TIMEOUT_MS:Jm,SUB_AGENT_TYPES:tg}});var xr=K((LM,bg)=>{var nt=require("fs"),zn=require("path"),{atomicWrite:ag,withFileLockSync:cg}=Bn(),Hk=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 Mo(){let t=zn.join(process.cwd(),".nex","brain");return nt.existsSync(t)||nt.mkdirSync(t,{recursive:!0}),t}function $a(){return zn.join(Mo(),".brain-index.json")}function tu(){return zn.join(Mo(),".embeddings.json")}function br(){let t=zn.join(process.cwd(),".nex","brain");if(!nt.existsSync(t))return[];try{return nt.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let n=zn.join(t,e),s=nt.statSync(n);return{name:e.replace(/\.md$/,""),path:n,size:s.size,modified:new Date(s.mtimeMs)}}).sort((e,n)=>n.modified-e.modified)}catch{return[]}}function _r(t){let e={},n=t,s=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(s){let o=s[1].split(`
|
|
232
|
+
`);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(u=>u.trim()).filter(Boolean):e[a]=c}n=s[2]}return{frontmatter:e,body:n}}function lg(t){let e=zn.join(Mo(),`${t}.md`);if(!nt.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=nt.readFileSync(e,"utf-8"),{frontmatter:s,body:o}=_r(n);return{name:t,content:n,body:o,frontmatter:s}}function Yk(t,e){let n=zn.join(Mo(),`${t}.md`);ag(n,e),zk(t,e),Gk()}function Gk(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=tu();nt.existsSync(t)&&setImmediate(async()=>{try{await gg()}catch{}})}function Kk(t){let e=zn.join(Mo(),`${t}.md`);return nt.existsSync(e)?(nt.unlinkSync(e),Xk(t),!0):!1}function ya(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Hk.has(e))}function nu(t){let e={},{frontmatter:n,body:s}=_r(t),o=Array.isArray(n.tags)?n.tags:[];for(let i of o){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(s||t).split(`
|
|
233
|
+
`);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let c of ya(a))e[c]=(e[c]||0)+3}for(let i of ya(s||t))e[i]=(e[i]||0)+1;return e}function su(){let t=$a();if(!nt.existsSync(t))return{documents:{}};try{return JSON.parse(nt.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function ou(t){ag($a(),JSON.stringify(t,null,2))}function zk(t,e){cg($a(),()=>{let n=su(),{frontmatter:s}=_r(e),o=Array.isArray(s.tags)?s.tags:[];n.documents[t]={keywords:nu(e),tags:o,modified:new Date().toISOString()},ou(n)})}function Xk(t){cg($a(),()=>{let e=su();delete e.documents[t],ou(e)})}function eu(){let t=br(),e={documents:{}};for(let n of t){let s=nt.readFileSync(n.path,"utf-8"),{frontmatter:o}=_r(s),r=Array.isArray(o.tags)?o.tags:[];e.documents[n.name]={keywords:nu(s),tags:r,modified:n.modified.toISOString()}}return ou(e),e}function ug(){let t=su(),e=br();for(let n of e){let s=t.documents[n.name];if(!s||new Date(s.modified)<n.modified)return eu()}for(let n of Object.keys(t.documents))if(!e.some(s=>s.name===n))return eu();return t}function dg(t,e={}){let{topK:n=3,minScore:s=.1}=e,o=ya(t);if(o.length===0)return[];let r=ug(),i=[];for(let[a,c]of Object.entries(r.documents)){let u=0;for(let d of o){c.keywords[d]&&(u+=c.keywords[d]);for(let[f,p]of Object.entries(c.keywords))f!==d&&f.length>3&&d.length>3&&(f.includes(d)||d.includes(f))&&(u+=p*.3)}u>=s&&i.push({name:a,score:u})}return i.sort((a,c)=>c.score-a.score),i.slice(0,n)}var fg=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Ql=400,Vk=50;async function pg(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),n=require("https"),s=new URL(`${t}/api/tags`),o=s.protocol==="https:"?n:e;return((await new Promise((a,c)=>{let u=o.get(s.toString(),{timeout:2e3},d=>{let f="";d.on("data",p=>f+=p),d.on("end",()=>{try{a(JSON.parse(f))}catch{c(new Error("bad json"))}})});u.on("error",c),u.on("timeout",()=>{u.destroy(),c(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(fg.split(":")[0]))}catch{return!1}}async function ru(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",n=require("http"),s=require("https"),o=new URL(`${e}/api/embeddings`),r=o.protocol==="https:"?s:n,i=JSON.stringify({model:fg,prompt:t});return new Promise((a,c)=>{let u=r.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},d=>{let f="";d.on("data",p=>f+=p),d.on("end",()=>{try{a(JSON.parse(f).embedding||[])}catch(p){c(p)}})});u.on("error",c),u.on("timeout",()=>{u.destroy(),c(new Error("embedding timeout"))}),u.write(i),u.end()})}function hg(t,e){if(!t||!e||t.length!==e.length)return 0;let n=0,s=0,o=0;for(let i=0;i<t.length;i++)n+=t[i]*e[i],s+=t[i]*t[i],o+=e[i]*e[i];let r=Math.sqrt(s)*Math.sqrt(o);return r===0?0:n/r}function mg(t){let e=t.split(/\s+/),n=[],s=0;for(;s<e.length;){let o=e.slice(s,s+Ql).join(" ");if(n.push({text:o,offset:s}),s+Ql>=e.length)break;s+=Ql-Vk}return n}async function gg(){let t=br(),e={documents:{}},n=tu();if(nt.existsSync(n))try{e=JSON.parse(nt.readFileSync(n,"utf-8"))}catch{}for(let s of t){let o=e.documents[s.name];if(o&&new Date(o.modified)>=s.modified)continue;let r=nt.readFileSync(s.path,"utf-8"),i=mg(r),a=[];for(let c of i){let u=await ru(c.text);a.push({text:c.text,embedding:u,offset:c.offset})}e.documents[s.name]={chunks:a,modified:s.modified.toISOString()}}for(let s of Object.keys(e.documents))t.some(o=>o.name===s)||delete e.documents[s];return nt.writeFileSync(n,JSON.stringify(e),"utf-8"),e}async function yg(t,e={}){let{topK:n=3,minSimilarity:s=.3}=e,o=tu();if(!nt.existsSync(o))return[];let r;try{r=JSON.parse(nt.readFileSync(o,"utf-8"))}catch{return[]}let i=await ru(t),a=[];for(let[c,u]of Object.entries(r.documents||{})){let d=0,f="";for(let p of u.chunks||[]){let m=hg(i,p.embedding);m>d&&(d=m,f=p.text)}d>=s&&a.push({name:c,score:d,bestChunk:f})}return a.sort((c,u)=>u.score-c.score),a.slice(0,n)}function $g(t,e,n={}){let{k:s=60,topK:o=3}=n,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(s+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(s+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,o)}async function wg(t,e={}){let{topK:n=3,minScore:s=.1}=e,o=dg(t,{topK:n,minScore:s}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await pg()){let a=await yg(t,{topK:n});r=$g(o,a,{topK:n})}}catch{}return r.map(i=>{let a=lg(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 Oo={queryKey:null,result:null,ts:0},Jk=3e5;async function Zk(t){if(!t||!t.trim())return"";let e=zn.join(process.cwd(),".nex","brain");if(!nt.existsSync(e)||br().length===0)return"";let s=t.trim().toLowerCase().slice(0,200);if(Oo.result!==null&&Oo.queryKey===s&&Date.now()-Oo.ts<Jk)return Oo.result;let o;try{o=await wg(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let r;try{r=Ht().estimateTokens}catch{r=d=>Math.ceil(d.length/4)}let i=25e3,a=[],c=0;for(let d of o){let f=d.content||"",p=r(f);if(c+p>i){let h=i-c;if(h<100)break;let g=h/p;f=f.slice(0,Math.floor(f.length*g))+`
|
|
234
234
|
...(truncated)`}let m=typeof d.score=="number"?d.score.toFixed(2):String(d.score);if(a.push(`--- ${d.name} (relevance: ${m}) ---
|
|
235
235
|
${f}`),c+=r(f),c>=i)break}if(a.length===0)return Oo={queryKey:s,result:"",ts:Date.now()},"";let u=`KNOWLEDGE BASE (auto-selected):
|
|
236
236
|
|
|
237
237
|
${a.join(`
|
|
238
238
|
|
|
239
|
-
`)}`;return Oo={queryKey:s,result:u,ts:Date.now()},u}bg.exports={getBrainDir:Mo,listDocuments:br,readDocument:lg,writeDocument:Yk,removeDocument:Kk,buildIndex:
|
|
239
|
+
`)}`;return Oo={queryKey:s,result:u,ts:Date.now()},u}bg.exports={getBrainDir:Mo,listDocuments:br,readDocument:lg,writeDocument:Yk,removeDocument:Kk,buildIndex:eu,getIndex:ug,query:wg,getBrainContext:Zk,isEmbeddingAvailable:pg,generateEmbedding:ru,buildEmbeddingIndex:gg,semanticQuery:yg,cosineSimilarity:hg,_keywordQuery:dg,_extractKeywords:nu,_chunkText:mg,parseFrontmatter:_r,tokenize:ya,_fuseResults:$g}});var mn=K((IM,Mg)=>{var Ve=require("fs"),Yt=require("path"),Qk=require("os"),{atomicWrite:wa,withFileLockSync:_g}=Bn(),Sr=["user","feedback","project","reference"],eE=50;function qs(){return Yt.join(process.cwd(),".nex","memory")}function No(){return Yt.join(qs(),"memory.json")}function xg(){return Yt.join(qs(),"MEMORY.md")}function tE(){return Yt.join(process.cwd(),"NEX.md")}function Sg(){return Yt.join(Qk.homedir(),".nex","NEX.md")}function ba(){let t=qs();Ve.existsSync(t)||Ve.mkdirSync(t,{recursive:!0})}function vg(t){let e=Yt.join(qs(),t);return Ve.existsSync(e)||Ve.mkdirSync(e,{recursive:!0}),e}function vr(){let t=No();if(!Ve.existsSync(t))return{};try{return JSON.parse(Ve.readFileSync(t,"utf-8"))}catch{return{}}}function kg(t){ba(),wa(No(),JSON.stringify(t,null,2))}function Eg(){let t=No();if(!Ve.existsSync(t))return;let e=vr(),n=Object.keys(e);if(n.length===0){try{Ve.renameSync(t,t+".bak")}catch{}return}for(let s of n){let o=e[s],r=o.value||String(o),i=s.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=vg("project"),c=Yt.join(a,`${i}.md`),u=r.split(`
|
|
240
240
|
`)[0].slice(0,100),d=`---
|
|
241
241
|
name: ${s}
|
|
242
242
|
description: ${u}
|
|
@@ -244,7 +244,7 @@ type: project
|
|
|
244
244
|
---
|
|
245
245
|
|
|
246
246
|
${r}
|
|
247
|
-
`;wa(c,d)}_a();try{Ve.renameSync(t,t+".bak")}catch{}}function nE(t,e,n,s){if(!Sr.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Sr.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!n||typeof n!="string"||n.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let o=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!o)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=vg(t),i=Yt.join(r,`${o}.md`);if(Ve.existsSync(i))try{if(
|
|
247
|
+
`;wa(c,d)}_a();try{Ve.renameSync(t,t+".bak")}catch{}}function nE(t,e,n,s){if(!Sr.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Sr.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!n||typeof n!="string"||n.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let o=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!o)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=vg(t),i=Yt.join(r,`${o}.md`);if(Ve.existsSync(i))try{if(iu(Ve.readFileSync(i,"utf-8")).body.slice(0,200)===n.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=s||n.split(`
|
|
248
248
|
`)[0].slice(0,100),c=`---
|
|
249
249
|
name: ${e}
|
|
250
250
|
description: ${a}
|
|
@@ -252,7 +252,7 @@ type: ${t}
|
|
|
252
252
|
---
|
|
253
253
|
|
|
254
254
|
${n}
|
|
255
|
-
`;return wa(i,c),_a(),{ok:!0,path:i,updated:!0}}function sE(t,e){if(!Sr.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),s=Yt.join(qs(),t,`${n}.md`);if(!Ve.existsSync(s))return!1;try{return Ve.unlinkSync(s),_a(),!0}catch{return!1}}function
|
|
255
|
+
`;return wa(i,c),_a(),{ok:!0,path:i,updated:!0}}function sE(t,e){if(!Sr.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),s=Yt.join(qs(),t,`${n}.md`);if(!Ve.existsSync(s))return!1;try{return Ve.unlinkSync(s),_a(),!0}catch{return!1}}function iu(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let n=e[1],s=(e[2]||"").trim(),o=r=>{let i=n.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:o("name"),description:o("description"),type:o("type"),body:s}}function Tg(){let t=[],e=qs();for(let n of Sr){let s=Yt.join(e,n);if(!Ve.existsSync(s))continue;let o;try{o=Ve.readdirSync(s).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of o){let i=Yt.join(s,r);try{let a=Ve.readFileSync(i,"utf-8"),c=iu(a);t.push({type:n,name:c.name||Yt.basename(r,".md"),description:c.description,filePath:i})}catch{}}}return t}function _a(){let t=Tg(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=eE+2)break;let s=`${n.type}/${Yt.basename(n.filePath)}`;e.push(`- [${n.name}](${s}) \u2014 ${n.description||"(no description)"}`)}ba(),wa(xg(),e.join(`
|
|
256
256
|
`)+`
|
|
257
257
|
`)}function Rg(){let t=xg();if(!Ve.existsSync(t))return"";try{return Ve.readFileSync(t,"utf-8").trim()}catch{return""}}function oE(t,e){ba(),_g(No(),()=>{let n=vr();n[t]={value:e,updatedAt:new Date().toISOString()},kg(n)})}function rE(t){let e=vr();return e[t]?e[t].value:null}function iE(t){return ba(),_g(No(),()=>{let e=vr();return t in e?(delete e[t],kg(e),!0):!1})}function Cg(){let t=vr();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function Ag(){let t=Sg();if(!Ve.existsSync(t))return"";try{return Ve.readFileSync(t,"utf-8").trim()}catch{return""}}function Og(){let t=tE();if(!Ve.existsSync(t))return"";try{return Ve.readFileSync(t,"utf-8").trim()}catch{return""}}function aE(){Eg();let t=[],e=Ag();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
258
258
|
${e}`);let n=Og();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
@@ -265,14 +265,14 @@ ${f.map(m=>` ${m.key}: ${m.value}`).join(`
|
|
|
265
265
|
`}s=p.trimEnd()+`
|
|
266
266
|
[Memory index truncated \u2014 use delete_memory to prune old entries]`}else s.length>u&&(s="");let d=[...t];return s&&d.push(s),d.length>0&&d.push(i),d.join(`
|
|
267
267
|
|
|
268
|
-
`)}Mg.exports={saveMemory:nE,deleteMemory:sE,scanMemories:Tg,rebuildIndex:_a,loadMemoryIndex:Rg,remember:oE,recall:rE,forget:iE,listMemories:Cg,loadGlobalInstructions:Ag,loadProjectInstructions:Og,getMemoryContext:aE,_getMemoryDir:qs,_getMemoryFile:No,_getGlobalNexMdPath:Sg,_parseMemoryFile:
|
|
269
|
-
`;kr.appendFileSync(Pg(),n,"utf-8")}catch{}}function Lg(t){if(!t||typeof t!="object")return{};let e={};for(let[n,s]of Object.entries(t))/key|token|password|secret|credential/i.test(n)?e[n]="***":typeof s=="string"&&s.length>500?e[n]=s.substring(0,500)+`... (${s.length} chars)`:e[n]=s;return e}function Ig(t={}){let e=Ng(),n=t.days||1,s=[];for(let o=0;o<n;o++){let r=t.date||new Date(Date.now()-o*864e5).toISOString().split("T")[0],i=
|
|
270
|
-
`).filter(c=>c.trim());for(let c of a)try{let u=JSON.parse(c);if(t.tool&&u.tool!==t.tool)continue;s.push(u)}catch{}if(t.date)break}return s}function lE(t=1){let e=Ig({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let n={},s=0,o=0;for(let r of e)n[r.tool]=(n[r.tool]||0)+1,s+=r.duration||0,r.success&&o++;return{totalCalls:e.length,byTool:n,avgDuration:Math.round(s/e.length),successRate:o/e.length}}function uE(t){
|
|
268
|
+
`)}Mg.exports={saveMemory:nE,deleteMemory:sE,scanMemories:Tg,rebuildIndex:_a,loadMemoryIndex:Rg,remember:oE,recall:rE,forget:iE,listMemories:Cg,loadGlobalInstructions:Ag,loadProjectInstructions:Og,getMemoryContext:aE,_getMemoryDir:qs,_getMemoryFile:No,_getGlobalNexMdPath:Sg,_parseMemoryFile:iu,_migrateIfNeeded:Eg,VALID_TYPES:Sr}});var lu=K((DM,Dg)=>{var kr=require("fs"),au=require("path"),cu=process.env.NEX_AUDIT!=="false",Fs=null;function Ng(){return Fs||(Fs=au.join(process.cwd(),".nex","audit"),kr.existsSync(Fs)||kr.mkdirSync(Fs,{recursive:!0}),Fs)}function Pg(){let t=new Date().toISOString().split("T")[0];return au.join(Ng(),`${t}.jsonl`)}function cE(t){if(cu)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Lg(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},n=JSON.stringify(e)+`
|
|
269
|
+
`;kr.appendFileSync(Pg(),n,"utf-8")}catch{}}function Lg(t){if(!t||typeof t!="object")return{};let e={};for(let[n,s]of Object.entries(t))/key|token|password|secret|credential/i.test(n)?e[n]="***":typeof s=="string"&&s.length>500?e[n]=s.substring(0,500)+`... (${s.length} chars)`:e[n]=s;return e}function Ig(t={}){let e=Ng(),n=t.days||1,s=[];for(let o=0;o<n;o++){let r=t.date||new Date(Date.now()-o*864e5).toISOString().split("T")[0],i=au.join(e,`${r}.jsonl`);if(!kr.existsSync(i))continue;let a=kr.readFileSync(i,"utf-8").split(`
|
|
270
|
+
`).filter(c=>c.trim());for(let c of a)try{let u=JSON.parse(c);if(t.tool&&u.tool!==t.tool)continue;s.push(u)}catch{}if(t.date)break}return s}function lE(t=1){let e=Ig({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let n={},s=0,o=0;for(let r of e)n[r.tool]=(n[r.tool]||0)+1,s+=r.duration||0,r.success&&o++;return{totalCalls:e.length,byTool:n,avgDuration:Math.round(s/e.length),successRate:o/e.length}}function uE(t){cu=t}function dE(){return cu}function fE(){Fs=null}Dg.exports={logToolExecution:cE,sanitizeArgs:Lg,readAuditLog:Ig,getAuditSummary:lE,setAuditEnabled:uE,isAuditEnabled:dE,getAuditLogPath:Pg,_reset:fE}});var Kg=K((FM,Gg)=>{var st=require("fs").promises,Er=require("fs"),Be=require("path"),tt=require("util").promisify(require("child_process").exec),Bs=require("util").promisify(require("child_process").execFile),{spawnSync:pE}=require("child_process"),uu=require("axios"),{isForbidden:hE,isSSHForbidden:mE,isDangerous:gE,isCritical:jg,isBashPathForbidden:yE,confirm:gn}=_t(),{showDiff:xa,showNewFile:$E,showEditDiff:jM,confirmFileChange:Tr}=pp(),{C:ye,Spinner:wE,getToolSpinnerText:bE}=Ye(),{isGitRepo:du,getCurrentBranch:qg,getStatus:_E,getDiff:xE}=rs(),{recordChange:Sa}=Un(),{fuzzyFindText:Fg,findMostSimilar:Ar}=Kp(),{runDiagnostics:Rr}=Xp(),{findFileInIndex:SE,getFileIndex:qM}=$l(),{resolveProfile:sn,sshExec:qt,scpUpload:vE,scpDownload:kE}=ko(),{resolveDeployConfig:EE,loadDeployConfigs:TE}=xl(),{getEditMode:Bg}=fr(),RE=/^(vim?|nano|emacs|pico|less|more|top|htop|iftop|iotop|glances|telnet\s|screen|tmux|fzf|gum|dialog|whiptail|man\s|node\s*$|python3?\s*$|irb\s*$|rails\s*c|psql\s|mysql\s|redis-cli|mongosh?|sqlite3)\b/,CE=/^ssh\s/,AE=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function Gt(t){return st.access(t).then(()=>!0).catch(()=>!1)}async function va(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=Ft(e);if(n&&await Gt(n))return{fixedPath:n,message:`(auto-fixed path: ${t} \u2192 ${e})`};let s=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=Be.extname(t);if(!o)for(let i of s){let a=Ft(t+i);if(a&&await Gt(a))return{fixedPath:a,message:`(auto-fixed: added ${i} extension)`}}if(o){let i=t.replace(/\.[^.]+$/,"");for(let a of s){if(a===o)continue;let c=Ft(i+a);if(c&&await Gt(c))return{fixedPath:c,message:`(auto-fixed: ${o} \u2192 ${a})`}}}let r=Be.basename(t);if(r&&r.length>2)try{let i=SE(r).map(a=>Ft(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${Be.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
271
271
|
${i.map(c=>Be.relative(process.cwd(),c)).map(c=>` - ${c}`).join(`
|
|
272
272
|
`)}`}}catch{}return{fixedPath:null,message:""}}function OE(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 Hg(t,e){let n=[];if(/command not found|: not found|not recognized/i.test(t)){let s=e.match(/^(\S+)/),o=s?s[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?n.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?n.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):n.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let s=t.match(/Cannot find module '([^']+)'/),o=s?s[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?n.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):n.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&n.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let s=t.match(/port (\d+)|:(\d+)/),o=s?s[1]||s[2]:"";n.push(`HINT: Port ${o||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&n.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&n.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&n.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&n.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let s=t.match(/curl:\s*\((\d+)\)/),o=s?parseInt(s[1],10):null;o===6||/Could not resolve host/i.test(t)?n.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?n.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?n.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?n.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===35||/SSL.*error/i.test(t))&&n.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let s=t.match(/port (\d+)/),o=s?s[1]:"";n.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&n.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&n.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&n.push("HINT: The working directory was deleted during this session \u2014 bash cannot execute commands in a non-existent cwd. Previous rm/delete commands succeeded. Use list_directory or glob to verify the state instead of retrying bash."),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&n.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),n.length===0?t:t+`
|
|
273
273
|
|
|
274
274
|
`+n.join(`
|
|
275
|
-
`)}function Yg(t,e,n){let s=Ar(t,e);if(!s)return null;let o=Math.max(2,Math.ceil(e.length*.03));return s.distance>o?null:{autoFixed:!0,matchText:s.text,content:t.split(s.text).join(n),distance:s.distance,line:s.line}}var Ug=!1,Us=null;function ME(){Us&&(Us(),Us=null)}var du=null;function NE(t){du=t}async function uu(){if(!Ug){Ug=!0;try{let{stdout:t}=await tt("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await tt('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await tt("git stash pop",{cwd:process.cwd(),timeout:1e4}),await tt("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var PE=[/\.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 Ft(t){let e=Be.isAbsolute(t)?Be.resolve(t):Be.resolve(process.cwd(),t);for(let n of PE)if(n.test(e))return null;return e}var LE=[{type:"function",function:{name:"bash",description:`Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. Example: use bash for "npm install" or "git status", but NOT for "cat config.json" (use read_file instead) or "grep -r 'error' src/" (use grep tool instead). AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.`,parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. ALWAYS read a file before editing it to ensure exact content matching \u2014 edit_file requires the EXACT text including whitespace and newlines. Example: read_file path=src/app.js line_start=10 line_end=20. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Concrete example: read_file(path='src/app.js', line_start=10, line_end=20) reads lines 10-20 of src/app.js. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding. IMPORTANT: If you need more than 350 lines, specify line_start and line_end explicitly \u2014 omitting them will truncate the output.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. Example: use write_file for creating a new config file like .env.example, but NOT for changing one line in an existing file (use edit_file instead). For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. ALWAYS call read_file first to get the exact content \u2014 edit_file requires the EXACT text including whitespace, indentation, and newlines. Example: edit_file(path='src/config.js', old_text='debug: false', new_text='debug: true'). IMPORTANT: old_text must match byte-for-byte \u2014 even a single space or newline difference will cause failure. If the edit fails with 'old_text not found', re-read that region with line_start/line_end then retry. For multiple replacements in one file, prefer patch_file (atomic). For new files, use write_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. Example: use list_directory to see the overall layout of the src/ directory, but NOT for finding all .js files (use glob instead). For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. Example: use search_files for finding all occurrences of 'error' in .js files, but NOT for finding all .js files (use glob instead). For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern by name or extension. Returns paths sorted by modification time. ALWAYS use this to locate files BEFORE reading them \u2014 never guess file paths. Example: glob(pattern='src/**/*.test.js') finds all test files in src directory. DO NOT use for content search (e.g. finding 'error' in files) \u2014 use grep tool instead. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to get the exact path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file CONTENTS with regex \u2014 use this when you need to find text inside files. Example: grep(pattern='callStream') finds files containing the text 'callStream'. Do NOT use glob for this \u2014 glob finds files by NAME pattern, grep searches file CONTENTS. Use output_mode='files_with_matches' for just file paths, output_mode='content' (default) for matching lines. Use include to filter by file type (e.g. '*.js'). Supports context lines, offset pagination, and multiline patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Example: when changing 3 different variables in the same function, use patch_file with an array of 3 { old_text, new_text } objects instead of 3 separate edit_file calls. This ensures either all changes are applied or none are, preventing partial edits. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"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.'}},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 Cr(t,{server:e,context:n}={}){let s=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,s){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${s} "${i}"`}return r}async function Wg(t,e,n={}){switch(t){case"bash":{let s=e.command,o=hE(s);if(o){let f=OE(s);return`BLOCKED: Command matches forbidden pattern: ${o}${f?`
|
|
275
|
+
`)}function Yg(t,e,n){let s=Ar(t,e);if(!s)return null;let o=Math.max(2,Math.ceil(e.length*.03));return s.distance>o?null:{autoFixed:!0,matchText:s.text,content:t.split(s.text).join(n),distance:s.distance,line:s.line}}var Ug=!1,Us=null;function ME(){Us&&(Us(),Us=null)}var pu=null;function NE(t){pu=t}async function fu(){if(!Ug){Ug=!0;try{let{stdout:t}=await tt("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await tt('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await tt("git stash pop",{cwd:process.cwd(),timeout:1e4}),await tt("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var PE=[/\.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 Ft(t){let e=Be.isAbsolute(t)?Be.resolve(t):Be.resolve(process.cwd(),t);for(let n of PE)if(n.test(e))return null;return e}var LE=[{type:"function",function:{name:"bash",description:`Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. Example: use bash for "npm install" or "git status", but NOT for "cat config.json" (use read_file instead) or "grep -r 'error' src/" (use grep tool instead). AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.`,parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. ALWAYS read a file before editing it to ensure exact content matching \u2014 edit_file requires the EXACT text including whitespace and newlines. Example: read_file path=src/app.js line_start=10 line_end=20. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Concrete example: read_file(path='src/app.js', line_start=10, line_end=20) reads lines 10-20 of src/app.js. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding. IMPORTANT: If you need more than 350 lines, specify line_start and line_end explicitly \u2014 omitting them will truncate the output.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. Example: use write_file for creating a new config file like .env.example, but NOT for changing one line in an existing file (use edit_file instead). For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. ALWAYS call read_file first to get the exact content \u2014 edit_file requires the EXACT text including whitespace, indentation, and newlines. Example: edit_file(path='src/config.js', old_text='debug: false', new_text='debug: true'). IMPORTANT: old_text must match byte-for-byte \u2014 even a single space or newline difference will cause failure. If the edit fails with 'old_text not found', re-read that region with line_start/line_end then retry. For multiple replacements in one file, prefer patch_file (atomic). For new files, use write_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. Example: use list_directory to see the overall layout of the src/ directory, but NOT for finding all .js files (use glob instead). For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. Example: use search_files for finding all occurrences of 'error' in .js files, but NOT for finding all .js files (use glob instead). For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern by name or extension. Returns paths sorted by modification time. ALWAYS use this to locate files BEFORE reading them \u2014 never guess file paths. Example: glob(pattern='src/**/*.test.js') finds all test files in src directory. DO NOT use for content search (e.g. finding 'error' in files) \u2014 use grep tool instead. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to get the exact path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file CONTENTS with regex \u2014 use this when you need to find text inside files. Example: grep(pattern='callStream') finds files containing the text 'callStream'. Do NOT use glob for this \u2014 glob finds files by NAME pattern, grep searches file CONTENTS. Use output_mode='files_with_matches' for just file paths, output_mode='content' (default) for matching lines. Use include to filter by file type (e.g. '*.js'). Supports context lines, offset pagination, and multiline patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Example: when changing 3 different variables in the same function, use patch_file with an array of 3 { old_text, new_text } objects instead of 3 separate edit_file calls. This ensures either all changes are applied or none are, preventing partial edits. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"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.'}},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 Cr(t,{server:e,context:n}={}){let s=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,s){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${s} "${i}"`}return r}async function Wg(t,e,n={}){switch(t){case"bash":{let s=e.command,o=hE(s);if(o){let f=OE(s);return`BLOCKED: Command matches forbidden pattern: ${o}${f?`
|
|
276
276
|
HINT: ${f}`:""}`}let r=yE(s);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
|
|
277
277
|
HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(n.autoConfirm?jg(s):gE(s)){let f=jg(s)?"\u26D4":"\u26A0";if(!await gn(` ${f} bash: \`${s}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Er.accessSync(a)}catch{a=require("os").homedir(),n.silent||console.log(`${ye.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${ye.reset}`)}let c=CE.test(s.trim())&&!AE.test(s.trim());if(RE.test(s.trim())||c){n.silent||console.log(`${ye.dim} \u25B6 interactive: ${s}${ye.reset}`);let f=pE("sh",["-c",s],{stdio:"inherit",cwd:a});return f.error?`ERROR: ${f.error.message}`:f.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${f.status})`}let{ToolProgress:u}=po(),d=n.silent?null:new u("bash",s.substring(0,40));d&&d.start();try{let{stdout:f,stderr:p}=await tt(s,{cwd:a,timeout:9e4,maxBuffer:5242880});return d&&d.stop(),f||p||"(no output)"}catch(f){d&&d.stop();let p=(f.stderr||f.stdout||f.message||"").toString().substring(0,5e3),m=Hg(p,s);return`EXIT ${f.code||1}
|
|
278
278
|
${m}`}}case"read_file":{let s=Ft(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Gt(s)){let C=await va(e.path);if(C.fixedPath)s=C.fixedPath,console.log(`${ye.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Be.relative(process.cwd(),s)}${ye.reset}`);else return`ERROR: File not found: ${e.path}${C.message?`
|
|
@@ -282,7 +282,7 @@ ${m}`}}case"read_file":{let s=Ft(e.path);if(!s)return`ERROR: Access denied \u201
|
|
|
282
282
|
|
|
283
283
|
[File truncated: showing lines 1-${p} of ${f} total. Use line_start/line_end to read other sections, e.g. line_start=${p+1} line_end=${Math.min(p*2,f)}]`:!m&&f>p?`
|
|
284
284
|
[Large file (${f} lines total) \u2014 use line_start/line_end for other sections]`:"";return`${E}
|
|
285
|
-
${S}${x}`}case"write_file":{await
|
|
285
|
+
${S}${x}`}case"write_file":{await fu();let s=Ft(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await Gt(s),r=null;if(n.autoConfirm)o&&(r=await st.readFile(s,"utf-8"));else if(o){r=await st.readFile(s,"utf-8");let d=await Rr(s,e.content);if(xa(s,r,e.content,{annotations:d}),!await Tr("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let d=await Rr(s,e.content);if($E(s,e.content,{annotations:d}),!await Tr("Create"))return"CANCELLED: User declined to create file."}let i=Be.dirname(s);await Gt(i)||await st.mkdir(i,{recursive:!0}),await st.writeFile(s,e.content,"utf-8");let c=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||e.content.startsWith("#!");c&&await st.chmod(s,493),Sa("write_file",s,r,e.content);let u=c?" [chmod +x applied]":"";return`Written: ${s} (${e.content.length} chars)${u}`}case"edit_file":{await fu();let s=Ft(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Gt(s)){let d=await va(e.path);if(d.fixedPath)s=d.fixedPath,console.log(`${ye.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Be.relative(process.cwd(),s)}${ye.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
286
286
|
`+d.message:""}`}let r=await st.readFile(s,"utf-8"),i=e.old_text,a=!1,c=!1;if(!r.includes(e.old_text)){let{getActiveModelId:d,getActiveProviderName:f}=We();if(Bg(d(),f())==="strict"){let h=Ar(r,e.old_text);return h?`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)
|
|
287
287
|
Most similar text (line ${h.line}, distance ${h.distance}):
|
|
288
288
|
${h.text}`:`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)`}let m=Fg(r,e.old_text);if(m)i=m,a=!0,console.log(`${ye.dim} \u2713 fuzzy whitespace match applied${ye.reset}`);else{let h=Yg(r,e.old_text,e.new_text);if(h){if(!n.autoConfirm){let E=await Rr(s,h.content);if(xa(s,r,h.content,{annotations:E}),!await Tr(`Apply (auto-fix, line ${h.line}, distance ${h.distance})`))return"CANCELLED: User declined to apply edit."}await st.writeFile(s,h.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||h.content.startsWith("#!"))&&await st.chmod(s,493),Sa("edit_file",s,r,h.content);let k=h.matchText.length>80?h.matchText.substring(0,77)+"...":h.matchText;return console.log(`${ye.dim} \u2713 auto-fixed edit: line ${h.line}, distance ${h.distance}${ye.reset}`),`Edited: ${s} (auto-fixed, line ${h.line}, distance ${h.distance}, matched: "${k}")`}let g=Ar(r,e.old_text);if(g){let k=r.split(`
|
|
@@ -298,7 +298,7 @@ Recovery: grep -n "${$.replace(/"/g,'\\"')}" <file> to find the line, then re-re
|
|
|
298
298
|
Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${s}${w}`}}if(!n.autoConfirm){let d=r.split(i).join(e.new_text),f=await Rr(s,d);if(xa(s,r,d,{annotations:f}),!await Tr(a?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(i).join(e.new_text);return await st.writeFile(s,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||u.startsWith("#!"))&&await st.chmod(s,493),Sa("edit_file",s,r,u),a?`Edited: ${s} (fuzzy match)`:`Edited: ${s}`}case"list_directory":{let s=Ft(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Gt(s)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=Ft(u),f=await Gt(d);if(d&&f)s=d;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],c=async(u,d,f)=>{if(d>r)return;let p;try{p=await st.readdir(u,{withFileTypes:!0})}catch{return}p=p.filter(m=>!m.name.startsWith(".")&&m.name!=="node_modules");for(let m of p){if(i&&!m.isDirectory()&&!i.test(m.name))continue;let h=m.isDirectory()?"/":"";a.push(`${f}${m.name}${h}`),m.isDirectory()&&await c(Be.join(u,m.name),d+1,f+" ")}};return await c(s,1,""),a.join(`
|
|
299
299
|
`)||"(empty)"}case"search_files":{let s=Ft(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn","--null","-H"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,s);try{let{stdout:r}=await Bs("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),a=[];for(let c=0;c<i.length;c+=2){let u=i[c],d=i[c+1];if(u&&d){let f=d.split(`
|
|
300
300
|
`).filter(p=>p.trim());for(let p of f)if(a.push(`${u}:${p}`),a.length>=50)break}if(a.length>=50)break}return a.join(`
|
|
301
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?Ft(e.path):o,i=e.pattern,a=q=>{let ie=q.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${ie}$`)},c=a(i),u=i.split("/").pop(),d=a(u),{ToolProgress:f}=po(),p=new f("glob","Finding files...");p.start();let{getFileIndex:m,getIndexedCwd:h,refreshIndex:g,isIndexValid:$}
|
|
301
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?Ft(e.path):o,i=e.pattern,a=q=>{let ie=q.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${ie}$`)},c=a(i),u=i.split("/").pop(),d=a(u),{ToolProgress:f}=po(),p=new f("glob","Finding files...");p.start();let{getFileIndex:m,getIndexedCwd:h,refreshIndex:g,isIndexValid:$}=$l(),w=m(),k=h();$(r)||(await g(r),w=m());let E=w.filter(q=>c.test(q)||d.test(Be.basename(q))).map(q=>Be.join(r,q));if(E.length===0)return p.stop(),"(no matches)";let S=await Promise.all(E.slice(0,210).map(async q=>{try{let ie=await st.stat(q);return{path:q,mtime:ie.mtimeMs}}catch{return{path:q,mtime:0}}}));S.sort((q,ie)=>ie.mtime-q.mtime);let x=S.map(q=>q.path),C=E.length>200,H=x.slice(0,200).join(`
|
|
302
302
|
`);return p.update({count:E.length,detail:e.pattern}),p.stop(),C?`${H}
|
|
303
303
|
|
|
304
304
|
\u26A0 Results truncated at 200. Use a more specific pattern.`:H}case"grep":{let s=e.path?Ft(e.path):process.cwd();if(e.staged){let{getDiff:c}=rs(),u=await c(!0);if(!u.trim())return"(no staged changes)";let d=new Set,f=u.split(`
|
|
@@ -308,18 +308,18 @@ Recovery: use grep -n to locate the text, then re-read that section with line_st
|
|
|
308
308
|
`).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,s);let{ToolProgress:i}=po(),a=new i("grep","Searching...");a.start();try{let{stdout:c}=await Bs("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),u;if(e.output_mode==="files_with_matches"||e.output_mode==="count")u=c.trim().split(`
|
|
309
309
|
`).filter(p=>p.trim());else{let p=c.split("\0");u=[];for(let m=0;m<p.length;m+=2){let h=p[m],g=p[m+1];if(h&&g){let $=g.split(`
|
|
310
310
|
`).filter(w=>w.trim());for(let w of $)u.push(`${h}:${w}`)}}}let d=e.offset||0,f=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return u=u.slice(d,d+f),a.update({count:u.length,detail:`in ${s}`}),a.stop(),u.join(`
|
|
311
|
-
`).trim()||"(no matches)"}catch(c){return a.stop(),c.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await
|
|
311
|
+
`).trim()||"(no matches)"}catch(c){return a.stop(),c.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await fu();let s=Ft(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Gt(s)){let w=await va(e.path);if(w.fixedPath)s=w.fixedPath,console.log(`${ye.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Be.relative(process.cwd(),s)}${ye.reset}`);else return`ERROR: File not found: ${e.path}${w.message?`
|
|
312
312
|
`+w.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await st.readFile(s,"utf-8"),{getActiveModelId:a,getActiveProviderName:c}=We(),u=Bg(a(),c()),d=[],f=!1,p=!1;for(let w=0;w<r.length;w++){let{old_text:k,new_text:E}=r[w];if(i.includes(k))d.push({old_text:k,new_text:E});else if(u==="strict"){let S=Ar(i,k);return S?`ERROR: Patch ${w+1} old_text not found in ${s} (strict mode \u2014 exact match required)
|
|
313
313
|
Most similar text (line ${S.line}, distance ${S.distance}):
|
|
314
314
|
${S.text}`:`ERROR: Patch ${w+1} old_text not found in ${s} (strict mode \u2014 exact match required)`}else{let S=Fg(i,k);if(S)d.push({old_text:S,new_text:E}),f=!0;else{let x=Ar(i,k);if(x){let C=Math.max(3,Math.ceil(k.length*.05));if(x.distance<=C)d.push({old_text:x.text,new_text:E}),p=!0;else return`ERROR: Patch ${w+1} old_text not found in ${s}
|
|
315
315
|
Most similar text (line ${x.line}, distance ${x.distance}):
|
|
316
|
-
${x.text}`}else return`ERROR: Patch ${w+1} old_text not found in ${s}`}}}let m=i;for(let{old_text:w,new_text:k}of d)m=m.split(w).join(k);if(!n.autoConfirm){let w=await Rr(s,m);if(xa(s,i,m,{annotations:w}),!await Tr(f?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await st.writeFile(s,m,"utf-8");let h=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||m.startsWith("#!");h&&await st.chmod(s,493),Sa("patch_file",s,i,m);let g=p?" (auto-fixed)":f?" (fuzzy match)":"",$=h?" [chmod +x applied]":"";return`Patched: ${s} (${r.length} replacements)${g}${$}`}case"web_fetch":{let s=e.url,o=e.max_length||1e4;try{let i=new URL(s).hostname;if(/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|169\.254\.|0\.|localhost$|\[::1?\]|\[fd|fc)/i.test(i))return"ERROR: Fetching private/internal addresses is not allowed.";let a=await
|
|
316
|
+
${x.text}`}else return`ERROR: Patch ${w+1} old_text not found in ${s}`}}}let m=i;for(let{old_text:w,new_text:k}of d)m=m.split(w).join(k);if(!n.autoConfirm){let w=await Rr(s,m);if(xa(s,i,m,{annotations:w}),!await Tr(f?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await st.writeFile(s,m,"utf-8");let h=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||m.startsWith("#!");h&&await st.chmod(s,493),Sa("patch_file",s,i,m);let g=p?" (auto-fixed)":f?" (fuzzy match)":"",$=h?" [chmod +x applied]":"";return`Patched: ${s} (${r.length} replacements)${g}${$}`}case"web_fetch":{let s=e.url,o=e.max_length||1e4;try{let i=new URL(s).hostname;if(/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|169\.254\.|0\.|localhost$|\[::1?\]|\[fd|fc)/i.test(i))return"ERROR: Fetching private/internal addresses is not allowed.";let a=await uu.get(s,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof a.data=="string"?a.data:JSON.stringify(a.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,o)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${s}: ${r.message}`}}case"web_search":{let s=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await uu.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]
|
|
317
317
|
|
|
318
318
|
${r}`;return i.length>0&&(a+=`
|
|
319
319
|
|
|
320
320
|
Sources:
|
|
321
321
|
`+i.slice(0,s).map((c,u)=>`${u+1}. ${c}`).join(`
|
|
322
|
-
`)),a}catch(o){console.error(`${ye.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${ye.reset}`)}try{let r=(await
|
|
322
|
+
`)),a}catch(o){console.error(`${ye.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${ye.reset}`)}try{let r=(await uu.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<s;){let u=c[1].replace(/.*uddg=/,"").split("&")[0],d=c[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:d,url:decodeURIComponent(u)})}catch{i.push({title:d,url:u})}}return i.length===0?"(no results)":i.map((u,d)=>`${d+1}. ${u.title}
|
|
323
323
|
${u.url}`).join(`
|
|
324
324
|
|
|
325
325
|
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:s}=Gn();try{let o=await s(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
|
|
@@ -410,13 +410,13 @@ Pixel deviation: ${o.changedPixels.toLocaleString()} / ${o.totalPixels.toLocaleS
|
|
|
410
410
|
Regional breakdown:
|
|
411
411
|
${r}
|
|
412
412
|
|
|
413
|
-
[Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:o.livePath,base64:o.liveBase64,media_type:"image/png"},{path:o.diffPath,base64:o.diffBase64,media_type:"image/png"},{path:o.annotatedPath,base64:o.annotatedBase64,media_type:"image/png"}]}}catch(s){return`ERROR: ${s.message}`}case"ask_user":{let{question:s,options:o=[]}=e;return
|
|
413
|
+
[Three images attached: live screenshot, pixel diff, annotated deviation map]`,images:[{path:o.livePath,base64:o.liveBase64,media_type:"image/png"},{path:o.diffPath,base64:o.diffBase64,media_type:"image/png"},{path:o.annotatedPath,base64:o.annotatedBase64,media_type:"image/png"}]}}catch(s){return`ERROR: ${s.message}`}case"ask_user":{let{question:s,options:o=[]}=e;return pu?new Promise(r=>{Us=()=>r("CANCELLED"),pu(s,o).then(i=>{Us=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});Us=()=>{i.close(),r("CANCELLED")};let a=o.length>0?`
|
|
414
414
|
${o.map((c,u)=>` ${u+1}. ${c}`).join(`
|
|
415
415
|
`)}
|
|
416
416
|
`:"";console.log(`
|
|
417
|
-
${ye.cyan}${ye.bold} ? ${s}${ye.reset}${a}`),i.question(`${ye.cyan} > ${ye.reset}`,c=>{Us=null,i.close(),r(c.trim()||"(no response)")})})}case"git_status":{if(!await
|
|
417
|
+
${ye.cyan}${ye.bold} ? ${s}${ye.reset}${a}`),i.question(`${ye.cyan} > ${ye.reset}`,c=>{Us=null,i.close(),r(c.trim()||"(no response)")})})}case"git_status":{if(!await du())return"ERROR: Not a git repository";let s=await qg()||"(detached)",o=await _E();if(o.length===0)return`Branch: ${s}
|
|
418
418
|
Clean working tree (no changes)`;let r=[`Branch: ${s}`,`Changed files (${o.length}):`];for(let i of o){let a=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${a}: ${i.file}`)}return r.join(`
|
|
419
|
-
`)}case"git_diff":{if(!await
|
|
419
|
+
`)}case"git_diff":{if(!await du())return"ERROR: Not a git repository";let s;if(e.file){let o=["diff"];e.staged&&o.push("--cached"),o.push("--",e.file);try{s=execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{s=""}}else s=await xE(!!e.staged);return s||"(no diff)"}case"git_log":{if(!await du())return"ERROR: Not a git repository";let o=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&o.push("--",e.file);try{return execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:s,updateTask:o,getTaskList:r,renderTaskList:i,hasActiveTasks:a}=la(),{getActiveTaskProgress:c}=Ye(),u=c();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let d=s(e.name,e.tasks);return u||console.log(`
|
|
420
420
|
`+i()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
421
421
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
422
422
|
`)}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)?(u||console.log(`
|
|
@@ -582,7 +582,7 @@ ${d}`:d||"(empty log)"}case"find_large":{let c=e.path||"/",u=e.limit||20,d=e.min
|
|
|
582
582
|
${p}`:p||`(no files larger than ${d} in ${c})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";let c=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",u;switch(e.service_action){case"status":u=`systemctl status ${c} --no-pager -l 2>&1 | head -40`;break;case"list_failed":u="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":u=`systemctl start ${c} && systemctl status ${c} --no-pager -l 2>&1 | head -20`;break;case"stop":u=`systemctl stop ${c} && echo "${c} stopped"`;break;case"restart":u=`systemctl restart ${c} && systemctl status ${c} --no-pager -l 2>&1 | head -20`;break;case"reload":u=`systemctl reload ${c} 2>&1 || systemctl reload-or-restart ${c} 2>&1`;break;case"enable":u=`systemctl enable ${c} && echo "${c} enabled"`;break;case"disable":u=`systemctl disable ${c} && echo "${c} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:d,exitCode:f}=await r(u,3e4);return f===0||e.service_action==="status"&&f===3?d||`service ${e.service_action} OK`:`EXIT ${f}
|
|
583
583
|
${d}`}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",u;e.pid?u=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${c} ${e.pid} && echo "Sent ${c} to PID ${e.pid}"`:u=`pgrep -a "${e.process_name}" 2>/dev/null | head -5 && pkill -${c} "${e.process_name}" && echo "Sent ${c} to all '${e.process_name}' processes"`;let{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
|
|
584
584
|
${d}`:d}case"journalctl":{let c=e.lines||100,u=["journalctl","--no-pager","-n",String(c)];e.unit&&u.push("-u",e.unit.includes(".")?e.unit:`${e.unit}.service`),e.priority&&u.push("-p",e.priority),e.since&&u.push(`--since="${e.since}"`),u.push('2>/dev/null || echo "(journalctl not available)"');let{out:d,exitCode:f}=await r(u.join(" "),2e4);return f!==0?`EXIT ${f}
|
|
585
|
-
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:s}=mn(),o=s(e.type,e.name,e.content,e.description);return o.ok?o.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${o.path}`:`ERROR: ${o.error}`}case"delete_memory":{let{deleteMemory:s}=mn();return s(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:s}=Xi(),o=await s(t,e,n);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function IE(t,e,n={}){let{emit:s}=Xi(),{logToolExecution:o}=
|
|
585
|
+
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:s}=mn(),o=s(e.type,e.name,e.content,e.description);return o.ok?o.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${o.path}`:`ERROR: ${o.error}`}case"delete_memory":{let{deleteMemory:s}=mn();return s(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:s}=Xi(),o=await s(t,e,n);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function IE(t,e,n={}){let{emit:s}=Xi(),{logToolExecution:o}=lu(),r=Date.now(),i=n.silent?null:bE(t,e);if(!i){let c=await Wg(t,e,n);return o({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await s("onToolResult",{tool:t,args:e,result:c}),c}let a=new wE(i);a.start();try{let c=await Wg(t,e,n);return a.stop(),o({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await s("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}}Gg.exports={TOOL_DEFINITIONS:LE,executeTool:IE,resolvePath:Ft,autoFixPath:va,autoFixEdit:Yg,enrichBashError:Hg,cancelPendingAskUser:ME,setAskUserHandler:NE,fileExists:Gt}});var fn=K((BM,zg)=>{zg.exports=Kg()});var mu=K((WM,Xg)=>{var{loadServerProfiles:Or,resolveProfile:UM,sshExec:DE}=ko(),hu={almalinux9:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all. Open port: firewall-cmd --permanent --add-port=PORT/tcp && firewall-cmd --reload.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent | audit2why. Fix context: restorecon -Rv /path.","Nginx config: /etc/nginx/. Test: nginx -t. Reload: systemctl reload nginx.","Process list: ps aux. Ports: ss -tuln.","Python: python3. Pip: pip3. Virtualenv: python3 -m venv."],almalinux8:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent."],ubuntu:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw. Status: ufw status. Allow port: ufw allow PORT/tcp.","SELinux NOT active by default (AppArmor instead). Check: aa-status."],debian:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw or iptables."],macos:["Package manager: Homebrew (brew). Install: brew install <pkg>. Update: brew update && brew upgrade.","Service manager: launchctl (NOT systemctl). Start: brew services start <name>. List: brew services list.",`No systemd. No journalctl. Use: log show --predicate 'process == "nginx"' --last 1h instead.`,"Firewall: macOS built-in (pfctl or System Settings). Check: pfctl -s rules.","Process list: ps aux. Ports: lsof -i -n -P | grep LISTEN."]};function jE(){let t=Or();if(Object.keys(t).length===0)return null;let n=["## Remote Servers (.nex/servers.json)"];n.push(""),n.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[o,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,a=r.port&&Number(r.port)!==22?`:${r.port}`:"",c=r.os?` \u2014 OS: ${r.os}`:"",u=r.sudo?", sudo available":"";n.push(`- **${o}**: ${i}${a}${c}${u}`)}let s=new Set;for(let o of Object.values(t))o.os&&hu[o.os]&&s.add(o.os);if(s.size>0){n.push("");for(let o of s){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;n.push(`### ${r} Notes`);for(let i of hu[o])n.push(`- ${i}`)}}return n.join(`
|
|
586
586
|
`)}function qE(t){let e=Or();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function FE(){return Object.keys(Or())}function BE(){let t=require("fs"),n=require("path").join(process.cwd(),"NEX.md"),s="";try{s=t.readFileSync(n,"utf-8")}catch{}let o=Or(),r=Object.keys(o);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],a=s.toLowerCase();if(!i.some(p=>a.includes(p)))return null;let u=r.map(p=>{let m=o[p],h=m.user?`${m.user}@${m.host}`:m.host,g=m.port&&Number(m.port)!==22?`:${m.port}`:"";return` - **${p}**: ${h}${g}${m.os?` (${m.os})`:""}`}).join(`
|
|
587
587
|
`),d=r.map(p=>o[p].log_path).filter(Boolean),f=d.length>0?`
|
|
588
588
|
- Server log paths: ${d.join(", ")}`:"";return`# Deployment Context (Auto-detected)
|
|
@@ -613,9 +613,9 @@ ${u}
|
|
|
613
613
|
- 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.
|
|
614
614
|
- 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.
|
|
615
615
|
- 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 WE(t){if(typeof t!="string")return null;let e=[...t.matchAll(/https?:\/\/([a-zA-Z0-9._-]+)/g)];if(e.length===0)return null;let n=Or();if(Object.keys(n).length===0)return null;let s=null,o=null;for(let[,i]of e){let a=i.toLowerCase().split(".");for(let[c,u]of Object.entries(n))if(a.includes(c.toLowerCase())){s=u,o=c;break}if(s)break;for(let[c,u]of Object.entries(n))if(u.host===i){s=u,o=c;break}if(s)break}if(!s||!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 DE(s,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=s.user?`${s.user}@${s.host}`:s.host;return`[Server context for "${o}" (${a}) \u2014 probed at task start]
|
|
616
|
-
`+i.trim()}catch{return null}}Xg.exports={getServerContext:jE,getDeploymentContextBlock:BE,hasServerOS:qE,getProfileNames:FE,probeUrlServer:WE,OS_HINTS:
|
|
616
|
+
`+i.trim()}catch{return null}}Xg.exports={getServerContext:jE,getDeploymentContextBlock:BE,hasServerOS:qE,getProfileNames:FE,probeUrlServer:WE,OS_HINTS:hu}});var Ta=K((HM,Qg)=>{var Nt=require("fs").promises,Jg=require("fs"),at=require("path"),ka=require("util").promisify(require("child_process").exec),{C:Po}=Ye(),{getMergeConflicts:Zg}=rs(),{getServerContext:HE}=mu(),YE=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function GE(t){try{return Jg.readFileSync(t,"utf-8").split(`
|
|
617
617
|
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function KE(t,e){for(let n of e)if(n===t||n.includes("*")&&new RegExp("^"+n.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function zE(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:s=[]}={}){let o=at.join(t,".gitignore"),r=[...s,...GE(o)],i=0,a=[at.basename(t)+"/"];function c(u,d,f){if(f>e||i>=n)return;let p;try{p=Jg.readdirSync(u,{withFileTypes:!0})}catch{return}p.sort((h,g)=>h.isDirectory()!==g.isDirectory()?h.isDirectory()?-1:1:h.name.localeCompare(g.name));let m=p.filter(h=>!(YE.has(h.name)||h.name.startsWith(".")&&h.name!==".env.example"||KE(h.name,r)));for(let h=0;h<m.length;h++){if(i>=n){a.push(`${d}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=m[h],$=h===m.length-1,w=$?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",k=d+($?" ":"\u2502 "),E=g.isDirectory()?g.name+"/":g.name;a.push(`${d}${w}${E}`),i++,g.isDirectory()&&c(at.join(u,g.name),k,f+1)}}return c(t,"",1),a.join(`
|
|
618
|
-
`)}var
|
|
618
|
+
`)}var gu=new Map,Io=new Map,Ea=null,Vg=3e4,Lo={result:null,expiry:0,cwd:null};async function Mn(t){try{return await t()}catch{return null}}async function XE(){if(!Ea||Date.now()>Ea)return!1;let t=[at.join(process.cwd(),"package.json"),at.join(process.cwd(),"README.md"),at.join(process.cwd(),".gitignore")];for(let e of t)try{let n=await Nt.stat(e),s=Io.get(e);if(!s||n.mtimeMs!==s)return!1}catch{if(Io.has(e))return!1}try{let e=at.join(process.cwd(),".git","HEAD"),n=await Nt.stat(e),s=Io.get(e);if(!s||n.mtimeMs!==s)return!1}catch{}return!0}async function VE(){let t=[at.join(process.cwd(),"package.json"),at.join(process.cwd(),"README.md"),at.join(process.cwd(),".gitignore"),at.join(process.cwd(),".git","HEAD"),at.join(process.cwd(),"CLAUDE.md"),at.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let n=await Nt.stat(e);Io.set(e,n.mtimeMs)}catch{Io.delete(e)}}async function JE(t){let e="fileContext",n=gu.get(e),s=!1;if(n&&await XE()&&(s=!0),!s){let u=[],d=at.join(t,"package.json");if(await Mn(()=>Nt.access(d).then(()=>!0).catch(()=>!1)))try{let S=await Nt.readFile(d,"utf-8"),x=JSON.parse(S),C={name:x.name,version:x.version};x.scripts&&(C.scripts=Object.keys(x.scripts).slice(0,15)),x.dependencies&&(C.deps=Object.keys(x.dependencies).length),x.devDependencies&&(C.devDeps=Object.keys(x.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(C)}`)}catch{}let p=at.join(t,"README.md");if(await Mn(()=>Nt.access(p).then(()=>!0).catch(()=>!1))){let x=(await Nt.readFile(p,"utf-8")).split(`
|
|
619
619
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
620
620
|
${x.join(`
|
|
621
621
|
`)}`)}let h=at.join(t,".gitignore");if(await Mn(()=>Nt.access(h).then(()=>!0).catch(()=>!1))){let S=await Nt.readFile(h,"utf-8");u.push(`GITIGNORE:
|
|
@@ -623,24 +623,24 @@ ${S.trim()}`)}let $=at.join(t,"CLAUDE.md");if(await Mn(()=>Nt.access($).then(()=
|
|
|
623
623
|
${S.trim()}`)}let k=at.join(t,".nex","CLAUDE.md");if(await Mn(()=>Nt.access(k).then(()=>!0).catch(()=>!1))){let S=await Nt.readFile(k,"utf-8");S.trim()&&u.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
|
|
624
624
|
${S.trim()}`)}n=u.join(`
|
|
625
625
|
|
|
626
|
-
`),
|
|
626
|
+
`),gu.set(e,n),Ea=Date.now()+Vg,await VE()}let o=[n],r,i,a,c;if(Lo.result&&Date.now()<Lo.expiry&&Lo.cwd===t?{branch:r,status:i,log:a,conflicts:c}=Lo.result:([r,i,a,c]=await Promise.all([Mn(async()=>{let{stdout:u}=await ka("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Mn(async()=>{let{stdout:u}=await ka("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Mn(async()=>{let{stdout:u}=await ka("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),Zg()]),Lo={result:{branch:r,status:i,log:a,conflicts:c},expiry:Date.now()+Vg,cwd:t}),r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
|
|
627
627
|
${i}`),a&&o.push(`RECENT COMMITS:
|
|
628
628
|
${a}`),c&&c.length>0){let u=c.map(d=>` ${d.file}`).join(`
|
|
629
629
|
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
630
630
|
${u}`)}try{let u=HE();u&&o.push(u)}catch{}return o.join(`
|
|
631
631
|
|
|
632
|
-
`)}async function ZE(t){let e=at.join(t,"package.json"),n="";if(await Mn(()=>Nt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Nt.readFile(e,"utf-8"),a=JSON.parse(i);n=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([Mn(async()=>{let{stdout:i}=await ka("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Zg()]);if(r&&r.length>0){console.log(`${Po.red} \u26A0 ${r.length} unresolved merge conflict(s):${Po.reset}`);for(let i of r)console.log(`${Po.red} ${i.file}${Po.reset}`);console.log(`${Po.yellow} \u2192 Resolve conflicts before starting tasks${Po.reset}`)}console.log()}Qg.exports={gatherProjectContext:JE,printContext:ZE,generateFileTree:zE,_clearContextCache:()=>{hu.clear(),Io.clear(),Ea=null,Lo={result:null,expiry:0,cwd:null}}}});var $n=K((YM,ny)=>{var yn=require("fs"),Ra=require("path"),{atomicWrite:QE}=Bn();function Nr(){return Ra.join(process.cwd(),".nex","sessions")}function mu(){let t=Nr();yn.existsSync(t)||yn.mkdirSync(t,{recursive:!0,mode:448})}function gu(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Ra.join(Nr(),`${e}.json`)}function yu(t,e,n={}){mu();let s=gu(t),o={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return QE(s,JSON.stringify(o,null,2)),{path:s,name:t}}function ey(t){let e=gu(t);if(!yn.existsSync(e))return null;try{return JSON.parse(yn.readFileSync(e,"utf-8"))}catch{return null}}function ty(){mu();let t=Nr(),e=yn.readdirSync(t).filter(s=>s.endsWith(".json")),n=[];for(let s of e)try{let o=JSON.parse(yn.readFileSync(Ra.join(t,s),"utf-8"));n.push({name:o.name||s.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider,score:o.score!=null?o.score:null,scoreGrade:o.scoreGrade||null})}catch{}return n.sort((s,o)=>(o.updatedAt||"").localeCompare(s.updatedAt||""))}function eT(t){let e=gu(t);return yn.existsSync(e)?(yn.unlinkSync(e),!0):!1}function tT(){let t=ty();return t.length===0?null:ey(t[0].name)}var Ws=null,Xn=null,Mr=null;function nT(t,e={}){t.length!==0&&(Ws&&clearTimeout(Ws),Xn=t,Mr=e||{},Ws=setTimeout(()=>{Xn&&Xn.length>0&&yu("_autosave",Xn,Mr),Ws=null,Xn=null,Mr=null},5e3))}function sT(){Ws&&(clearTimeout(Ws),Ws=null),Xn&&Xn.length>0&&(yu("_autosave",Xn,Mr),Xn=null,Mr=null)}function oT(){mu();let t=Nr(),e=yn.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,s=new Date(n.getTime()-720*60*60*1e3),o=0;for(let r of e){let i=Ra.join(t,r);try{let a=yn.statSync(i);new Date(a.mtime)<s&&(yn.unlinkSync(i),o++)}catch{}}return o}ny.exports={saveSession:yu,loadSession:ey,listSessions:ty,deleteSession:eT,getLastSession:tT,autoSave:nT,flushAutoSave:sT,clearOldSessions:oT,_getSessionsDir:Nr}});var Ca=K((GM,uy)=>{"use strict";var Pr=require("fs"),sy=require("path");function oy(t){let e=[];return t.forEach((n,s)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_use"&&e.push({name:o.name||"",input:o.input||{},index:s,id:o.id||null})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(o=>{let r=o.function?.name||o.name||"",i={};try{i=typeof o.function?.arguments=="string"?JSON.parse(o.function.arguments):o.function?.arguments||o.input||{}}catch{}e.push({name:r,input:i,index:s,id:o.id||null})}))}),e}function rT(t){let e=new Set;return t.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&e.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_result"&&s.tool_use_id&&typeof s.content=="string"&&s.content.startsWith("BLOCKED:")&&e.add(s.tool_use_id)})}),e}function ry(t){let e=[];return t.forEach((n,s)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{if(o&&o.type==="tool_result"){let r=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(o.content||"");e.push({content:r,index:s})}}),n.role==="tool"){let o=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:o,index:s})}}),e}function iy(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let s=n.content.filter(o=>o&&(o.type==="text"||typeof o=="string")).map(o=>typeof o=="string"?o:o.text||"").join("").trim();if(s)return s}}}return""}function ay(t,e){let n=[];for(let s=t.length-1;s>=0&&n.length<e;s--){let o=t[s];if(o.role!=="assistant")continue;let r="";typeof o.content=="string"?r=o.content.trim():Array.isArray(o.content)&&(r=o.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function cy(t){let e=new Map;for(let n of t){let s;try{s=JSON.stringify(n.input)}catch{s=String(n.input)}let o=`${n.name}|${s}`;e.set(o,(e.get(o)||0)+1)}return e}function ly(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,n=[],s=oy(t),o=ry(t),r=s.length,i=rT(t),a=s.filter(v=>!v.id||!i.has(v.id));t.some(v=>v.role==="user"&&typeof v.content=="string"&&v.content.startsWith("[SYSTEM WARNING]")&&(v.content.includes("edited")||v.content.includes("bash command")||v.content.includes("grep pattern")||v.content.includes("re-read")||v.content.includes("already in your context")))&&(e-=2,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let u=s.find(v=>{let L=v.input?.command||v.input?.cmd||"";return/\bsed\s+-n\b/.test(L)});if(u){let v=(u.input?.command||u.input?.cmd||"").slice(0,80);o.some(O=>O.content.includes("BLOCKED: sed -n is forbidden")||O.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${v}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${v}`))}s.find(v=>{if(v.name!=="grep"&&v.name!=="bash"&&v.name!=="ssh_exec")return!1;let L=v.input?.command||v.input?.cmd||"",O=v.input?.pattern||"",D=`${L} ${O}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(D)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(D)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let f=t.some(v=>v.role==="assistant"),p=iy(t),h=ay(t,3).some(v=>v.length>100&&!/^[^.!]{0,40}\?$/.test(v));if(f&&!h&&(p.length<80||/^[^.!]{0,40}\?$/.test(p))){e-=2;let v=p.length>0?`"${p.slice(0,60)}..."`:"(no assistant text found)";n.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${v}`)}r>40?(e-=1.5,n.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,n.push(`High tool call count: ${r} (>25 threshold)`)),t.some(v=>{let L=typeof v.content=="string"?v.content:Array.isArray(v.content)?v.content.map(O=>typeof O=="string"?O:O.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(L)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let w=cy(a),k=0,E="";for(let[v,L]of w)L>k&&(k=L,E=v);if(k>=3){let[v]=E.split("|");e-=1,n.push(`Same tool call repeated ${k}\xD7 (tool: ${v})`)}let S=!1,x=t.findIndex(v=>v.role==="user"&&typeof v.content=="string"&&v.content.includes("[SYSTEM STOP]")&&v.content.includes('"valid":true'));x>=0&&s.filter(L=>L.index>x).length>0&&(S=!0),S&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let C=s.filter(v=>v.name==="ssh_exec");if(C.length>=8){let v=0,L=1;for(let O=1;O<C.length;O++)C[O].index<=C[O-1].index+2?L++:(v=Math.max(v,L),L=1);v=Math.max(v,L),v>=8&&(e-=.5,n.push(`SSH reconnect storm: ${v} consecutive SSH calls`))}f&&C.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(p)&&(e-=2,n.push("Surrender: model asked user to manually provide server output instead of gathering it"));let H=new Map;for(let v of a)if(v.name==="read_file"&&v.input?.path){let L=v.input.path;H.has(L)||H.set(L,{count:0,ranges:[]});let O=H.get(L);if(O.count++,v.input.line_start!=null){let D=v.input.line_start||1,M=v.input.line_end||D+350;O.ranges.push([D,M])}}function q(v,L,O){for(let[D,M]of O){let R=Math.max(v,D),N=Math.min(L,M);if(N>R){let Z=N-R,ne=L-v||1;if(Z/ne>=.7)return!0}}return!1}let ie=0,le="";for(let[v,L]of H){if(L.count<3)continue;if(L.ranges.length===L.count){let M=!1,R=[];for(let[N,Z]of L.ranges){if(R.length>0&&q(N,Z,R)){M=!0;break}R.push([N,Z])}if(!M)continue}if(L.count-L.ranges.length<=2&&L.ranges.length>=1){let M=!1,R=[];for(let[N,Z]of L.ranges){if(R.length>0&&q(N,Z,R)){M=!0;break}R.push([N,Z])}if(!M)continue}L.count>ie&&(ie=L.count,le=v)}if(ie>=3){e-=1;let v=le.split("/").slice(-2).join("/");n.push(`read_file loop: "${v}" read ${ie}\xD7 (file already in context)`)}let te=0,T="";for(let[v,L]of H){if(L.ranges.length<4)continue;let O=[],D=!1;for(let[M,R]of L.ranges){if(O.length>0&&q(M,R,O)){D=!0;break}O.push([M,R])}!D&&L.ranges.length>te&&(te=L.ranges.length,T=v)}if(te>=4){e-=.5;let v=T.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${v}" read in ${te} sequential sections \u2014 use grep instead`)}let Te=new Map;for(let v of a)if(v.name==="grep"&&v.input?.path&&v.input?.pattern){let L=v.input.path;Te.has(L)||Te.set(L,new Set),Te.get(L).add(v.input.pattern)}let G=0,z="";for(let[v,L]of Te)v.split("/").pop().includes(".")&&L.size>G&&(G=L.size,z=v);if(G>=3){e-=.75;let v=z.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${v}" searched ${G}\xD7 with different patterns (file already in context)`)}{let v=new Set,L=new Set,O=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let M of s){if(M.name==="write_file"&&M.input?.path){let R=M.input.path.split("/").pop(),N=M.input.path.includes("/tests/");O.test(R)&&!N&&v.add(M.input.path)}if((M.name==="bash"||M.name==="ssh_exec")&&M.input?.command){let R=M.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(R)for(let N of R){let Z=N.split(/\s+/),ne=Z[Z.length-1];for(let Q of v)(Q.endsWith(ne)||ne.endsWith(Q.split("/").pop()))&&L.add(Q)}}}let D=L.size;if(D>=1){let M=Math.min(D*.25,.5);e-=M;let R=[...L].map(N=>N.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${R} \u2014 write inline logic or use tests/ instead`)}}let fe=o.filter(v=>v.content.startsWith("EXIT")).length;fe>=10?(e-=1,n.push(`Bash exit-error storm: ${fe} tool results started with EXIT (repeated failing commands)`)):fe>=5&&(e-=.5,n.push(`Repeated bash errors: ${fe} tool results with non-zero exit code`));for(let v of t){if(v.role!=="assistant")continue;let L="";if(typeof v.content=="string"?L=v.content:Array.isArray(v.content)&&(L=v.content.filter(ne=>ne&&(ne.type==="text"||typeof ne=="string")).map(ne=>typeof ne=="string"?ne:ne.text||"").join("")),L.length<=5e3)continue;let O=L.split(/(?<=\. )/).filter(ne=>ne.trim().length>0);if(O.length<6)continue;let D=new Map;for(let ne=0;ne<=O.length-3;ne++){let Q=O.slice(ne,ne+3).join("").trim();Q.length>30&&D.set(Q,(D.get(Q)||0)+1)}let M=0,R="";for(let[ne,Q]of D)Q>M&&(M=Q,R=ne);if(M<3)continue;let Z=R.length*M/L.length;if(Z>=.4||M>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${M}\xD7 same paragraph, ${Math.round(Z*100)}% repeated)`);break}}{let v=new Set(["read_file","list_directory","search_files","glob","grep"]),L=t.some(D=>Array.isArray(D.tool_calls)?D.tool_calls.some(M=>v.has(M.function?.name)):Array.isArray(D.content)?D.content.some(M=>M.type==="tool_use"&&v.has(M.name)):!1);t.some(D=>D.role==="assistant"&&typeof D.content=="string"&&(D.content.includes("## Steps")||D.content.includes("/plan approve")))&&!L&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let Ee=o.filter(v=>v.content.startsWith("BLOCKED:")&&!v.content.includes("BLOCKED: sed -n")&&!v.content.includes("SSH paused")&&!v.content.includes("SSH temporarily paused"));if(Ee.length>0){let v=Math.min(Ee.length*.5,1.5);e-=v,n.push(`${Ee.length} tool call${Ee.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Ae=t.filter(v=>{let L=typeof v.content=="string"?v.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(L)}).length;if(Ae>0){let v=Math.min(Ae*1,2);e-=v,n.push(`Super-nuclear context wipe fired ${Ae}\xD7 (context collapse \u2014 task too large or read loops)`)}{let v=!1,L=!1,O=!1;for(let M of s){if(M.name!=="bash")continue;let R=(M.input?.command||M.input?.cmd||"").trim();!(/cat\s*>/.test(R)||/<</.test(R))&&/\bcat\s+\S/.test(R)&&(v=!0),/^\s*ls(\s|$)/.test(R)&&!/npm|yarn|pnpm|make|git\b/.test(R)&&(L=!0),/\bfind\s+\S/.test(R)&&!/git\b|npm\b|-exec\b/.test(R)&&(O=!0)}let D=[v,L,O].filter(Boolean).length;if(D>0){let M=Math.min(D*.25,.75);e-=M;let R=[];v&&R.push("cat (use read_file)"),L&&R.push("ls (use list_directory)"),O&&R.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${R.join(", ")}`)}}{let v=s.some(R=>(R.name==="write_file"||R.name==="Write")&&R.input?.path&&(R.input.path.endsWith("requirements.txt")||R.input.path.endsWith("Pipfile")||R.input.path.endsWith("pyproject.toml"))),L=s.some(R=>(R.name==="write_file"||R.name==="Write")&&R.input?.path&&R.input.path.endsWith("package.json")),O=s.filter(R=>(R.name==="bash"||R.name==="Bash")&&R.input?.command).map(R=>R.input.command),D=O.some(R=>/pip\s+install|python\s+-m\s+venv/.test(R)),M=O.some(R=>/npm\s+install/.test(R));v&&!D?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):L&&!M&&s.some(N=>(N.name==="write_file"||N.name==="Write")&&N.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(N.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(f){let v=t.find(R=>R.role==="assistant"),L="";v&&(typeof v.content=="string"?L=v.content:Array.isArray(v.content)&&(L=v.content.filter(R=>R&&(R.type==="text"||typeof R=="string")).map(R=>typeof R=="string"?R:R.text||"").join("")));let O=L.slice(0,400),D=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,M=O.split(`
|
|
632
|
+
`)}async function ZE(t){let e=at.join(t,"package.json"),n="";if(await Mn(()=>Nt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Nt.readFile(e,"utf-8"),a=JSON.parse(i);n=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([Mn(async()=>{let{stdout:i}=await ka("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Zg()]);if(r&&r.length>0){console.log(`${Po.red} \u26A0 ${r.length} unresolved merge conflict(s):${Po.reset}`);for(let i of r)console.log(`${Po.red} ${i.file}${Po.reset}`);console.log(`${Po.yellow} \u2192 Resolve conflicts before starting tasks${Po.reset}`)}console.log()}Qg.exports={gatherProjectContext:JE,printContext:ZE,generateFileTree:zE,_clearContextCache:()=>{gu.clear(),Io.clear(),Ea=null,Lo={result:null,expiry:0,cwd:null}}}});var $n=K((YM,ny)=>{var yn=require("fs"),Ra=require("path"),{atomicWrite:QE}=Bn();function Nr(){return Ra.join(process.cwd(),".nex","sessions")}function yu(){let t=Nr();yn.existsSync(t)||yn.mkdirSync(t,{recursive:!0,mode:448})}function $u(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Ra.join(Nr(),`${e}.json`)}function wu(t,e,n={}){yu();let s=$u(t),o={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return QE(s,JSON.stringify(o,null,2)),{path:s,name:t}}function ey(t){let e=$u(t);if(!yn.existsSync(e))return null;try{return JSON.parse(yn.readFileSync(e,"utf-8"))}catch{return null}}function ty(){yu();let t=Nr(),e=yn.readdirSync(t).filter(s=>s.endsWith(".json")),n=[];for(let s of e)try{let o=JSON.parse(yn.readFileSync(Ra.join(t,s),"utf-8"));n.push({name:o.name||s.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider,score:o.score!=null?o.score:null,scoreGrade:o.scoreGrade||null})}catch{}return n.sort((s,o)=>(o.updatedAt||"").localeCompare(s.updatedAt||""))}function eT(t){let e=$u(t);return yn.existsSync(e)?(yn.unlinkSync(e),!0):!1}function tT(){let t=ty();return t.length===0?null:ey(t[0].name)}var Ws=null,Xn=null,Mr=null;function nT(t,e={}){t.length!==0&&(Ws&&clearTimeout(Ws),Xn=t,Mr=e||{},Ws=setTimeout(()=>{Xn&&Xn.length>0&&wu("_autosave",Xn,Mr),Ws=null,Xn=null,Mr=null},5e3))}function sT(){Ws&&(clearTimeout(Ws),Ws=null),Xn&&Xn.length>0&&(wu("_autosave",Xn,Mr),Xn=null,Mr=null)}function oT(){yu();let t=Nr(),e=yn.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,s=new Date(n.getTime()-720*60*60*1e3),o=0;for(let r of e){let i=Ra.join(t,r);try{let a=yn.statSync(i);new Date(a.mtime)<s&&(yn.unlinkSync(i),o++)}catch{}}return o}ny.exports={saveSession:wu,loadSession:ey,listSessions:ty,deleteSession:eT,getLastSession:tT,autoSave:nT,flushAutoSave:sT,clearOldSessions:oT,_getSessionsDir:Nr}});var Ca=K((GM,uy)=>{"use strict";var Pr=require("fs"),sy=require("path");function oy(t){let e=[];return t.forEach((n,s)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_use"&&e.push({name:o.name||"",input:o.input||{},index:s,id:o.id||null})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(o=>{let r=o.function?.name||o.name||"",i={};try{i=typeof o.function?.arguments=="string"?JSON.parse(o.function.arguments):o.function?.arguments||o.input||{}}catch{}e.push({name:r,input:i,index:s,id:o.id||null})}))}),e}function rT(t){let e=new Set;return t.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&e.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_result"&&s.tool_use_id&&typeof s.content=="string"&&s.content.startsWith("BLOCKED:")&&e.add(s.tool_use_id)})}),e}function ry(t){let e=[];return t.forEach((n,s)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{if(o&&o.type==="tool_result"){let r=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(o.content||"");e.push({content:r,index:s})}}),n.role==="tool"){let o=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:o,index:s})}}),e}function iy(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let s=n.content.filter(o=>o&&(o.type==="text"||typeof o=="string")).map(o=>typeof o=="string"?o:o.text||"").join("").trim();if(s)return s}}}return""}function ay(t,e){let n=[];for(let s=t.length-1;s>=0&&n.length<e;s--){let o=t[s];if(o.role!=="assistant")continue;let r="";typeof o.content=="string"?r=o.content.trim():Array.isArray(o.content)&&(r=o.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function cy(t){let e=new Map;for(let n of t){let s;try{s=JSON.stringify(n.input)}catch{s=String(n.input)}let o=`${n.name}|${s}`;e.set(o,(e.get(o)||0)+1)}return e}function ly(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,n=[],s=oy(t),o=ry(t),r=s.length,i=rT(t),a=s.filter(v=>!v.id||!i.has(v.id));t.some(v=>v.role==="user"&&typeof v.content=="string"&&v.content.startsWith("[SYSTEM WARNING]")&&(v.content.includes("edited")||v.content.includes("bash command")||v.content.includes("grep pattern")||v.content.includes("re-read")||v.content.includes("already in your context")))&&(e-=2,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let u=s.find(v=>{let L=v.input?.command||v.input?.cmd||"";return/\bsed\s+-n\b/.test(L)});if(u){let v=(u.input?.command||u.input?.cmd||"").slice(0,80);o.some(O=>O.content.includes("BLOCKED: sed -n is forbidden")||O.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${v}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${v}`))}s.find(v=>{if(v.name!=="grep"&&v.name!=="bash"&&v.name!=="ssh_exec")return!1;let L=v.input?.command||v.input?.cmd||"",O=v.input?.pattern||"",D=`${L} ${O}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(D)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(D)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let f=t.some(v=>v.role==="assistant"),p=iy(t),h=ay(t,3).some(v=>v.length>100&&!/^[^.!]{0,40}\?$/.test(v));if(f&&!h&&(p.length<80||/^[^.!]{0,40}\?$/.test(p))){e-=2;let v=p.length>0?`"${p.slice(0,60)}..."`:"(no assistant text found)";n.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${v}`)}r>40?(e-=1.5,n.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,n.push(`High tool call count: ${r} (>25 threshold)`)),t.some(v=>{let L=typeof v.content=="string"?v.content:Array.isArray(v.content)?v.content.map(O=>typeof O=="string"?O:O.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(L)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let w=cy(a),k=0,E="";for(let[v,L]of w)L>k&&(k=L,E=v);if(k>=3){let[v]=E.split("|");e-=1,n.push(`Same tool call repeated ${k}\xD7 (tool: ${v})`)}let S=!1,x=t.findIndex(v=>v.role==="user"&&typeof v.content=="string"&&v.content.includes("[SYSTEM STOP]")&&v.content.includes('"valid":true'));x>=0&&s.filter(L=>L.index>x).length>0&&(S=!0),S&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let C=s.filter(v=>v.name==="ssh_exec");if(C.length>=8){let v=0,L=1;for(let O=1;O<C.length;O++)C[O].index<=C[O-1].index+2?L++:(v=Math.max(v,L),L=1);v=Math.max(v,L),v>=8&&(e-=.5,n.push(`SSH reconnect storm: ${v} consecutive SSH calls`))}f&&C.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(p)&&(e-=2,n.push("Surrender: model asked user to manually provide server output instead of gathering it"));let H=new Map;for(let v of a)if(v.name==="read_file"&&v.input?.path){let L=v.input.path;H.has(L)||H.set(L,{count:0,ranges:[]});let O=H.get(L);if(O.count++,v.input.line_start!=null){let D=v.input.line_start||1,M=v.input.line_end||D+350;O.ranges.push([D,M])}}function q(v,L,O){for(let[D,M]of O){let R=Math.max(v,D),N=Math.min(L,M);if(N>R){let Z=N-R,ne=L-v||1;if(Z/ne>=.7)return!0}}return!1}let ie=0,le="";for(let[v,L]of H){if(L.count<3)continue;if(L.ranges.length===L.count){let M=!1,R=[];for(let[N,Z]of L.ranges){if(R.length>0&&q(N,Z,R)){M=!0;break}R.push([N,Z])}if(!M)continue}if(L.count-L.ranges.length<=2&&L.ranges.length>=1){let M=!1,R=[];for(let[N,Z]of L.ranges){if(R.length>0&&q(N,Z,R)){M=!0;break}R.push([N,Z])}if(!M)continue}L.count>ie&&(ie=L.count,le=v)}if(ie>=3){e-=1;let v=le.split("/").slice(-2).join("/");n.push(`read_file loop: "${v}" read ${ie}\xD7 (file already in context)`)}let te=0,T="";for(let[v,L]of H){if(L.ranges.length<4)continue;let O=[],D=!1;for(let[M,R]of L.ranges){if(O.length>0&&q(M,R,O)){D=!0;break}O.push([M,R])}!D&&L.ranges.length>te&&(te=L.ranges.length,T=v)}if(te>=4){e-=.5;let v=T.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${v}" read in ${te} sequential sections \u2014 use grep instead`)}let Te=new Map;for(let v of a)if(v.name==="grep"&&v.input?.path&&v.input?.pattern){let L=v.input.path;Te.has(L)||Te.set(L,new Set),Te.get(L).add(v.input.pattern)}let G=0,z="";for(let[v,L]of Te)v.split("/").pop().includes(".")&&L.size>G&&(G=L.size,z=v);if(G>=3){e-=.75;let v=z.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${v}" searched ${G}\xD7 with different patterns (file already in context)`)}{let v=new Set,L=new Set,O=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let M of s){if(M.name==="write_file"&&M.input?.path){let R=M.input.path.split("/").pop(),N=M.input.path.includes("/tests/");O.test(R)&&!N&&v.add(M.input.path)}if((M.name==="bash"||M.name==="ssh_exec")&&M.input?.command){let R=M.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(R)for(let N of R){let Z=N.split(/\s+/),ne=Z[Z.length-1];for(let Q of v)(Q.endsWith(ne)||ne.endsWith(Q.split("/").pop()))&&L.add(Q)}}}let D=L.size;if(D>=1){let M=Math.min(D*.25,.5);e-=M;let R=[...L].map(N=>N.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${R} \u2014 write inline logic or use tests/ instead`)}}let fe=o.filter(v=>v.content.startsWith("EXIT")).length;fe>=10?(e-=1,n.push(`Bash exit-error storm: ${fe} tool results started with EXIT (repeated failing commands)`)):fe>=5&&(e-=.5,n.push(`Repeated bash errors: ${fe} tool results with non-zero exit code`));for(let v of t){if(v.role!=="assistant")continue;let L="";if(typeof v.content=="string"?L=v.content:Array.isArray(v.content)&&(L=v.content.filter(ne=>ne&&(ne.type==="text"||typeof ne=="string")).map(ne=>typeof ne=="string"?ne:ne.text||"").join("")),L.length<=5e3)continue;let O=L.split(/(?<=\. )/).filter(ne=>ne.trim().length>0);if(O.length<6)continue;let D=new Map;for(let ne=0;ne<=O.length-3;ne++){let Q=O.slice(ne,ne+3).join("").trim();Q.length>30&&D.set(Q,(D.get(Q)||0)+1)}let M=0,R="";for(let[ne,Q]of D)Q>M&&(M=Q,R=ne);if(M<3)continue;let Z=R.length*M/L.length;if(Z>=.4||M>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${M}\xD7 same paragraph, ${Math.round(Z*100)}% repeated)`);break}}{let v=new Set(["read_file","list_directory","search_files","glob","grep"]),L=t.some(D=>Array.isArray(D.tool_calls)?D.tool_calls.some(M=>v.has(M.function?.name)):Array.isArray(D.content)?D.content.some(M=>M.type==="tool_use"&&v.has(M.name)):!1);t.some(D=>D.role==="assistant"&&typeof D.content=="string"&&(D.content.includes("## Steps")||D.content.includes("/plan approve")))&&!L&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let Ee=o.filter(v=>v.content.startsWith("BLOCKED:")&&!v.content.includes("BLOCKED: sed -n")&&!v.content.includes("SSH paused")&&!v.content.includes("SSH temporarily paused"));if(Ee.length>0){let v=Math.min(Ee.length*.5,1.5);e-=v,n.push(`${Ee.length} tool call${Ee.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Ae=t.filter(v=>{let L=typeof v.content=="string"?v.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(L)}).length;if(Ae>0){let v=Math.min(Ae*1,2);e-=v,n.push(`Super-nuclear context wipe fired ${Ae}\xD7 (context collapse \u2014 task too large or read loops)`)}{let v=!1,L=!1,O=!1;for(let M of s){if(M.name!=="bash")continue;let R=(M.input?.command||M.input?.cmd||"").trim();!(/cat\s*>/.test(R)||/<</.test(R))&&/\bcat\s+\S/.test(R)&&(v=!0),/^\s*ls(\s|$)/.test(R)&&!/npm|yarn|pnpm|make|git\b/.test(R)&&(L=!0),/\bfind\s+\S/.test(R)&&!/git\b|npm\b|-exec\b/.test(R)&&(O=!0)}let D=[v,L,O].filter(Boolean).length;if(D>0){let M=Math.min(D*.25,.75);e-=M;let R=[];v&&R.push("cat (use read_file)"),L&&R.push("ls (use list_directory)"),O&&R.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${R.join(", ")}`)}}{let v=s.some(R=>(R.name==="write_file"||R.name==="Write")&&R.input?.path&&(R.input.path.endsWith("requirements.txt")||R.input.path.endsWith("Pipfile")||R.input.path.endsWith("pyproject.toml"))),L=s.some(R=>(R.name==="write_file"||R.name==="Write")&&R.input?.path&&R.input.path.endsWith("package.json")),O=s.filter(R=>(R.name==="bash"||R.name==="Bash")&&R.input?.command).map(R=>R.input.command),D=O.some(R=>/pip\s+install|python\s+-m\s+venv/.test(R)),M=O.some(R=>/npm\s+install/.test(R));v&&!D?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):L&&!M&&s.some(N=>(N.name==="write_file"||N.name==="Write")&&N.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(N.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(f){let v=t.find(R=>R.role==="assistant"),L="";v&&(typeof v.content=="string"?L=v.content:Array.isArray(v.content)&&(L=v.content.filter(R=>R&&(R.type==="text"||typeof R=="string")).map(R=>typeof R=="string"?R:R.text||"").join("")));let O=L.slice(0,400),D=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,M=O.split(`
|
|
633
633
|
`).find(R=>{let N=R.trim();return N.length>0&&N.length<=30&&/^\d/.test(N)&&/=/.test(N)&&!/[a-zA-Z]/.test(N)});if(D.test(O)||M){e-=1.5;let R=(M||O.split(`
|
|
634
634
|
`)[0]).trim().slice(0,40);n.push(`Thinking-chain leak: non-sequitur artifact at response start: "${R}"`)}}if(f&&r>0){let v=t.findIndex(O=>O.role==="assistant"),L=t.findIndex(O=>!!(Array.isArray(O.tool_calls)&&O.tool_calls.length>0||Array.isArray(O.content)&&O.content.some(D=>D&&D.type==="tool_use")));if(v!==-1&&L!==-1&&v<L){let O=t[v],D="";typeof O.content=="string"?D=O.content:Array.isArray(O.content)&&(D=O.content.filter(N=>N&&(N.type==="text"||typeof N=="string")).map(N=>typeof N=="string"?N:N.text||"").join(""));let M=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(D),R=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(D);(M||R)&&(e-=1,n.push("Answer-before-verify: model gave concrete file paths/SSH commands before making any tool calls (paths guessed, not verified)"))}}if(f){let v=p;if(v.length>100){let O=(v.match(/^```/gm)||[]).length%2!==0,D=/"\s*:\s*$/.test(v.trimEnd()),M=/[,\[{]\s*$/.test(v.trimEnd());(O||D||M)&&(e-=.75,n.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let v=[];t.forEach((O,D)=>{let M=[];Array.isArray(O.tool_calls)&&O.tool_calls.forEach(R=>{if((R.function?.name||R.name||"")==="read_file"){let Z={};try{Z=typeof R.function?.arguments=="string"?JSON.parse(R.function.arguments):R.function?.arguments||{}}catch{}(Z.path||"").endsWith(".json")&&M.push({id:R.id,path:Z.path})}}),Array.isArray(O.content)&&O.content.forEach(R=>{R&&R.type==="tool_use"&&R.name==="read_file"&&(R.input?.path||"").endsWith(".json")&&M.push({id:R.id,path:R.input.path})}),M.forEach(R=>v.push({...R,msgIdx:D}))});let L=0;for(let O of v){let D=null;for(let R of t){if(R.role==="tool"&&R.tool_call_id===O.id&&typeof R.content=="string"){D=R.content;break}if(R.role==="user"&&Array.isArray(R.content)){let N=R.content.find(Z=>Z&&Z.type==="tool_result"&&Z.tool_use_id===O.id);if(N){D=typeof N.content=="string"?N.content:"";break}}}if(!D)continue;D.split(`
|
|
635
635
|
`).filter(R=>R.trim()).length<5&&/^\s*\[/.test(D)&&!/\]\s*$/.test(D.trimEnd())&&L++}L>=1&&(e-=.75,n.push(`Shallow JSON read: ${L} .json file${L>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let v=o.filter(L=>/argument errors?/i.test(L.content)||/missing required (argument|parameter)/i.test(L.content)||/invalid argument/i.test(L.content));v.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${v.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):v.length>=2&&(e-=.25,n.push(`Tool argument errors: ${v.length} tool calls returned argument errors`))}{let v=!1,L=0,O=0;for(let D of a){if((D.name==="bash"||D.name==="Bash")&&D.input?.command&&/git\s+commit\b/.test(D.input.command)){v&&(O=Math.max(O,L)),v=!0,L=0;continue}v&&(D.name==="bash"||D.name==="Bash")&&D.input?.command&&/git\s+(status|diff|log|show)\b/.test(D.input.command)&&L++}O=Math.max(O,L),O>=3&&(e-=.75,n.push(`Post-commit verification waste: ${O} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let ve=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",be=n.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${n.length} issue${n.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:ve,issues:n,summary:be}}function iT(t){try{let{loadSession:e}=$n(),n=e(t);return n?ly(n.messages||[]):null}catch{return null}}function aT(t,e=null){let{score:n,issues:s}=t,o=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(n>=8||s.length===0)return"";let a=s.map(d=>d.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(n>=6){let d=a.slice(0,3),f=a.length-d.length,p=d.join(" \xB7 ");return f>0&&(p+=` (+${f})`),`
|
|
636
636
|
${o}${p}${r}`}let c="";for(let d of a.slice(0,4))c+=`
|
|
637
637
|
${i}\u26A0${r} ${o}${d}${r}`;let u=a.length-4;return u>0&&(c+=`
|
|
638
|
-
${o}(+${u} more)${r}`),c}function cT(t,e={}){try{let n=sy.join(process.cwd(),".nex");Pr.existsSync(n)||Pr.mkdirSync(n,{recursive:!0});let s=sy.join(n,"benchmark-history.json"),o=[];if(Pr.existsSync(s))try{o=JSON.parse(Pr.readFileSync(s,"utf-8"))}catch{o=[]}Array.isArray(o)||(o=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};o.push(i),o.length>100&&(o=o.slice(o.length-100)),Pr.writeFileSync(s,JSON.stringify(o,null,2))}catch{}}uy.exports={scoreMessages:ly,scoreSession:iT,formatScore:aT,appendScoreHistory:cT,_extractToolCalls:oy,_extractToolResults:ry,_getLastAssistantText:iy,_getLastNAssistantTexts:ay,_countDuplicateToolCalls:cy}});var us=K((KM,my)=>{"use strict";var lT=require("os")
|
|
638
|
+
${o}(+${u} more)${r}`),c}function cT(t,e={}){try{let n=sy.join(process.cwd(),".nex");Pr.existsSync(n)||Pr.mkdirSync(n,{recursive:!0});let s=sy.join(n,"benchmark-history.json"),o=[];if(Pr.existsSync(s))try{o=JSON.parse(Pr.readFileSync(s,"utf-8"))}catch{o=[]}Array.isArray(o)||(o=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};o.push(i),o.length>100&&(o=o.slice(o.length-100)),Pr.writeFileSync(s,JSON.stringify(o,null,2))}catch{}}uy.exports={scoreMessages:ly,scoreSession:iT,formatScore:aT,appendScoreHistory:cT,_extractToolCalls:oy,_extractToolResults:ry,_getLastAssistantText:iy,_getLastNAssistantTexts:ay,_countDuplicateToolCalls:cy}});var us=K((KM,my)=>{"use strict";var lT=require("os"),bu=require("path"),ls=require("fs"),Lr=bu.join(lT.homedir(),".nex-code","model-routing.json"),Aa={frontend:{id:"frontend",label:"Frontend",icon:"\u2B21",envVar:"NEX_ROUTE_FRONTEND",pattern:/\b(react|vue|angular|svelte|jsx|tsx|html|css|scss|sass|tailwind|bootstrap|component|dom\b|ui\s|button|modal|navbar|sidebar|stylesheet|responsive|flexbox|grid|animation|frontend|front.end|onclick|hover|transition|web\s+design|landing\s+page|browser\s+event)\b/i},sysadmin:{id:"sysadmin",label:"Sysadmin",icon:"\u2699",envVar:"NEX_ROUTE_SYSADMIN",pattern:/\b(nginx|apache|docker|kubernetes|k8s|systemd|systemctl|deploy(ment)?|server\s+config|firewall|iptables\b|ssh\s+key|cron(job)?|ansible|terraform|ci\/cd|pipeline|container\b|pod\b|apt\s+install|yum\s+install|daemon|pm2|supervisor|logrotate|ssl\s+cert|lets.encrypt|reverse\s+proxy|load\s+balanc|haproxy|vhost|virtual\s+host)\b/i},data:{id:"data",label:"Data",icon:"\u2B21",envVar:"NEX_ROUTE_DATA",pattern:/\b(sql\b|mysql|postgres(ql)?|sqlite|mongodb|redis\b|query\b|database|db\s+migration|schema\s+change|table\s+join|aggregate\b|pandas\b|dataframe|\.csv\b|etl\b|data\s+transform|data\s+pipeline|analytics|data\s+warehouse|dbt\b|orm\b|knex|sequelize|prisma\s+schema)\b/i},agentic:{id:"agentic",label:"Agentic",icon:"\u2B21",envVar:"NEX_ROUTE_AGENTIC",pattern:/\b(spawn\s+agent|agent\s+swarm|multi.?agent|parallel\s+agent|orchestrat|coordinate\s+multiple\s+agent|delegate.+agent|sub.?agent|architect.*coder)\b/i},coding:{id:"coding",label:"Coding",icon:"\u2B21",envVar:"NEX_ROUTE_CODING",pattern:null}},dy=["agentic","frontend","sysadmin","data","coding"];function uT(t){if(!t||t.length<8)return null;for(let e of dy){let n=Aa[e];if(!n.pattern||n.pattern.test(t))return n}return Aa.coding}function Ir(){try{if(ls.existsSync(Lr))return JSON.parse(ls.readFileSync(Lr,"utf-8"))}catch{}return{}}function fy(t){let e=Aa[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:Ir()[t]||null}var py={plan:10,implement:35,verify:8},_u={plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function hy(){let t=Ir();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=We();if(e()==="ollama")return _u}catch{}return process.env.NEX_PHASE_ROUTING==="1"?_u:null}function dT(t,e){let n=hy();return n?.[t]?n[t]:e?fy(e):null}function fT(t){return Ir().phaseBudgets?.[t]||py[t]||20}function pT(){return process.env.NEX_PHASE_ROUTING==="0"?!1:hy()!==null}function hT(t){let e=bu.dirname(Lr);ls.existsSync(e)||ls.mkdirSync(e,{recursive:!0});let n=Ir(),s={...n,...t};!t.phases&&n.phases&&(s.phases=n.phases),!t.phaseBudgets&&n.phaseBudgets&&(s.phaseBudgets=n.phaseBudgets),ls.writeFileSync(Lr,JSON.stringify(s,null,2));try{let o=bu.join(e,".env"),r="";ls.existsSync(o)&&(r=ls.readFileSync(o,"utf-8"));let i=r.split(/\r?\n/),a=(c,u)=>{let d=i.findIndex(f=>f.startsWith(c+"="));d>=0?i[d]=`${c}=${u}`:i.push(`${c}=${u}`)};s.coding&&a("NEX_ROUTE_CODING",s.coding),s.frontend&&a("NEX_ROUTE_FRONTEND",s.frontend),s.sysadmin&&a("NEX_ROUTE_SYSADMIN",s.sysadmin),s.data&&a("NEX_ROUTE_DATA",s.data),s.agentic&&a("NEX_ROUTE_AGENTIC",s.agentic),s.phases&&(s.phases.plan&&a("NEX_PHASE_PLAN_MODEL",s.phases.plan),s.phases.implement&&a("NEX_PHASE_IMPLEMENT_MODEL",s.phases.implement),s.phases.verify&&a("NEX_PHASE_VERIFY_MODEL",s.phases.verify)),ls.writeFileSync(o,i.filter(c=>c.trim()!=="").join(`
|
|
639
639
|
`)+`
|
|
640
|
-
`)}catch{}}my.exports={CATEGORIES:Aa,DETECTION_ORDER:dy,detectCategory:uT,getModelForCategory:fy,getModelForPhase:dT,getPhaseBudget:fT,isPhaseRoutingEnabled:pT,DEFAULT_PHASE_BUDGETS:py,BUILTIN_PHASE_DEFAULTS:
|
|
640
|
+
`)}catch{}}my.exports={CATEGORIES:Aa,DETECTION_ORDER:dy,detectCategory:uT,getModelForCategory:fy,getModelForPhase:dT,getPhaseBudget:fT,isPhaseRoutingEnabled:pT,DEFAULT_PHASE_BUDGETS:py,BUILTIN_PHASE_DEFAULTS:_u,saveRoutingConfig:hT,loadRoutingConfig:Ir,ROUTING_CONFIG_PATH:Lr}});var wy=K((zM,$y)=>{"use strict";var Hs=require("fs"),Dr=require("path"),mT=require("os"),{detectCategory:gT}=us(),Do=Dr.join(mT.homedir(),".nex-code","examples"),xu=Dr.join(__dirname,"..","examples");function gy(t){try{let n=Hs.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),s=n.match(/^user:\s*(.+)$/m);if(!s)return null;let o=s[1].trim(),r=n.indexOf(`
|
|
641
641
|
A: |`);if(r===-1)return null;let i=n.slice(r+5),a=[],c=0;for(let d of i.split(`
|
|
642
642
|
`))if(d.startsWith(" ")){for(;c>0;)a.push(""),c--;a.push(d.slice(2))}else if(d.trim()==="")a.length>0&&c++;else break;if(a.length===0)return null;let u=a.join(`
|
|
643
|
-
`).trim();return{user:o,assistant:u}}catch{return null}}function yy(t){let e=`${t}.md`,n=Dr.join(Do,e);if(Hs.existsSync(n)){let o=gy(n);if(o)return o}let s=Dr.join(
|
|
643
|
+
`).trim();return{user:o,assistant:u}}catch{return null}}function yy(t){let e=`${t}.md`,n=Dr.join(Do,e);if(Hs.existsSync(n)){let o=gy(n);if(o)return o}let s=Dr.join(xu,e);return Hs.existsSync(s)?gy(s):null}function yT(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=gT(t);return e?yy(e.id):null}function $T(){let t=new Set;for(let e of[Do,xu])try{for(let n of Hs.readdirSync(e))n.endsWith(".md")&&t.add(n.replace(".md",""))}catch{}return[...t].sort()}function wT(t,e){Hs.existsSync(Do)||Hs.mkdirSync(Do,{recursive:!0});let n=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
|
|
644
644
|
|
|
645
645
|
user: ${e.user}
|
|
646
646
|
|
|
@@ -648,10 +648,10 @@ A: |
|
|
|
648
648
|
${e.assistant.split(`
|
|
649
649
|
`).map(s=>` ${s}`).join(`
|
|
650
650
|
`)}
|
|
651
|
-
`;Hs.writeFileSync(Dr.join(Do,`${t}.md`),n,"utf-8")}$y.exports={getFewShotForInput:yT,loadExampleForCategory:yy,listAvailableExamples:$T,savePrivateExample:wT,PRIVATE_EXAMPLES_DIR:Do,BUNDLED_EXAMPLES_DIR:
|
|
651
|
+
`;Hs.writeFileSync(Dr.join(Do,`${t}.md`),n,"utf-8")}$y.exports={getFewShotForInput:yT,loadExampleForCategory:yy,listAvailableExamples:$T,savePrivateExample:wT,PRIVATE_EXAMPLES_DIR:Do,BUNDLED_EXAMPLES_DIR:xu}});var qr=K((VM,vy)=>{var Kt=require("fs"),jo=require("path"),{C:XM}=Ye(),{atomicWrite:bT,withFileLockSync:_T}=Bn(),Oa={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"},qo={...Oa};function by(){let t=jo.join(process.cwd(),".nex","config.json");if(Kt.existsSync(t))try{let e=JSON.parse(Kt.readFileSync(t,"utf-8"));e.permissions&&(qo={...Oa,...e.permissions})}catch{}}function xT(){let t=jo.join(process.cwd(),".nex"),e=jo.join(t,"config.json");Kt.existsSync(t)||Kt.mkdirSync(t,{recursive:!0}),_T(e,()=>{let n={};if(Kt.existsSync(e))try{n=JSON.parse(Kt.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=qo,bT(e,JSON.stringify(n,null,2))})}function _y(t){return qo[t]||"ask"}function ST(t,e){return["allow","ask","deny"].includes(e)?(qo[t]=e,!0):!1}function vT(t){return _y(t)}function kT(){return Object.entries(qo).map(([t,e])=>({tool:t,mode:e}))}function ET(){qo={...Oa}}var jr={readonly:{description:"Read-only access \u2014 can search and read but not modify",allowedTools:["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","ask_user","web_fetch","web_search","browser_open","browser_screenshot","task_list"],blockedTools:["bash","write_file","edit_file","patch_file","deploy","ssh_exec","service_manage","container_manage","container_exec","remote_agent"],autoConfirm:!1,allowDangerous:!1},developer:{description:"Standard developer access \u2014 can read, write, and run commands",allowedTools:null,blockedTools:["deploy","service_manage","container_manage","remote_agent"],autoConfirm:!1,allowDangerous:!1},admin:{description:"Full access \u2014 all tools, including deployment and infrastructure",allowedTools:null,blockedTools:[],autoConfirm:!1,allowDangerous:!0}};function xy(){let t=jo.join(process.cwd(),".nex","config.json");try{return Kt.existsSync(t)&&JSON.parse(Kt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function TT(t){let e=jo.join(process.cwd(),".nex"),n=jo.join(e,"config.json");Kt.existsSync(e)||Kt.mkdirSync(e,{recursive:!0});let s={};try{Kt.existsSync(n)&&(s=JSON.parse(Kt.readFileSync(n,"utf-8")))}catch{s={}}s.teamPermissions=t,Kt.writeFileSync(n,JSON.stringify(s,null,2),"utf-8")}function Sy(){let t=xy();if(!t)return jr.admin;let e=t.role||"admin",n=jr[e]||jr.admin;return{...n,...t.overrides,blockedTools:[...n.blockedTools||[],...t.overrides?.blockedTools||[]]}}function RT(t){let e=Sy();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 CT(){return Object.entries(jr).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}by();vy.exports={getPermission:_y,setPermission:ST,checkPermission:vT,listPermissions:kT,loadPermissions:by,savePermissions:xT,resetPermissions:ET,DEFAULT_PERMISSIONS:Oa,PERMISSION_PRESETS:jr,loadPresetConfig:xy,savePresetConfig:TT,getEffectivePreset:Sy,isToolAllowed:RT,listPresets:CT}});var wn=K((ZM,Cy)=>{var Gs=require("fs"),Ma=require("path"),JM=require("readline"),{C:Ie}=Ye(),Ne=null,vu=!1,ku=null,ky=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Na(){return Ma.join(process.cwd(),".nex","plans")}function Ey(){let t=Na();Gs.existsSync(t)||Gs.mkdirSync(t,{recursive:!0})}function AT(t,e=[]){return Ne={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(n=>({description:n.description||n,files:n.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},Ne}function OT(){return Ne}function MT(t){vu=t}function NT(){return vu}function PT(){return!Ne||Ne.status!=="draft"?!1:(Ne.status="approved",Ne.updatedAt=new Date().toISOString(),!0)}function LT(){return!Ne||Ne.status!=="approved"?!1:(Ne.status="executing",!0)}function Su(t,e){return!Ne||t<0||t>=Ne.steps.length?!1:(Ne.steps[t].status=e,Ne.updatedAt=new Date().toISOString(),Ne.steps.every(n=>n.status==="done"||n.status==="skipped")&&(Ne.status="completed"),!0)}function IT(t){if(!t)return`${Ie.dim}No active plan${Ie.reset}`;let e={draft:`${Ie.yellow}DRAFT${Ie.reset}`,approved:`${Ie.green}APPROVED${Ie.reset}`,executing:`${Ie.blue}EXECUTING${Ie.reset}`,completed:`${Ie.green}COMPLETED${Ie.reset}`},n=[];n.push(`
|
|
652
652
|
${Ie.bold}${Ie.cyan}Plan: ${t.task}${Ie.reset}`),n.push(`${Ie.dim}Status: ${e[t.status]||t.status}${Ie.reset}
|
|
653
653
|
`);for(let s=0;s<t.steps.length;s++){let o=t.steps[s],r;switch(o.status){case"done":r=`${Ie.green}\u2713${Ie.reset}`;break;case"in_progress":r=`${Ie.blue}\u2192${Ie.reset}`;break;case"skipped":r=`${Ie.dim}\u25CB${Ie.reset}`;break;default:r=`${Ie.dim} ${Ie.reset}`}n.push(` ${r} ${Ie.bold}Step ${s+1}:${Ie.reset} ${o.description}`),o.files.length>0&&n.push(` ${Ie.dim}Files: ${o.files.join(", ")}${Ie.reset}`)}return n.push(""),n.join(`
|
|
654
|
-
`)}function DT(t){if(t||(t=Ne),!t)return null;Ey();let e=Ma.join(Na(),`${t.name}.json`);return Gs.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function jT(t){let e=Ma.join(Na(),`${t}.json`);if(!Gs.existsSync(e))return null;try{let n=JSON.parse(Gs.readFileSync(e,"utf-8"));return Ne=n,n}catch{return null}}function qT(){Ey();let t=Na(),e=Gs.readdirSync(t).filter(s=>s.endsWith(".json")),n=[];for(let s of e)try{let o=JSON.parse(Gs.readFileSync(Ma.join(t,s),"utf-8"));n.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return n.sort((s,o)=>(o.createdAt||"").localeCompare(s.createdAt||""))}function FT(t){if(!t)return[];let e=[],n=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),s=n?n[1]:t,o=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=o.exec(s))!==null;){let a=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let a=r[1].replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,a=[...t.matchAll(i)];for(let c=0;c<Math.min(e.length,a.length);c++){let u=a[c][1];e[c].files=u.split(/[,\s]+/).filter(d=>/[./]/.test(d)).slice(0,5)}}return e}function BT(t){
|
|
654
|
+
`)}function DT(t){if(t||(t=Ne),!t)return null;Ey();let e=Ma.join(Na(),`${t.name}.json`);return Gs.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function jT(t){let e=Ma.join(Na(),`${t}.json`);if(!Gs.existsSync(e))return null;try{let n=JSON.parse(Gs.readFileSync(e,"utf-8"));return Ne=n,n}catch{return null}}function qT(){Ey();let t=Na(),e=Gs.readdirSync(t).filter(s=>s.endsWith(".json")),n=[];for(let s of e)try{let o=JSON.parse(Gs.readFileSync(Ma.join(t,s),"utf-8"));n.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return n.sort((s,o)=>(o.createdAt||"").localeCompare(s.createdAt||""))}function FT(t){if(!t)return[];let e=[],n=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),s=n?n[1]:t,o=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=o.exec(s))!==null;){let a=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let a=r[1].replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,a=[...t.matchAll(i)];for(let c=0;c<Math.min(e.length,a.length);c++){let u=a[c][1];e[c].files=u.split(/[,\s]+/).filter(d=>/[./]/.test(d)).slice(0,5)}}return e}function BT(t){ku=t}function UT(){return ku}function WT(){Ne=null,vu=!1,ku=null,KT()}function HT(){return`
|
|
655
655
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
656
656
|
|
|
657
657
|
# Allowed Tools (read-only)
|
|
@@ -699,23 +699,23 @@ Bullet list of potential issues and mitigations.
|
|
|
699
699
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
700
700
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
701
701
|
- Do NOT make any file changes \u2014 your role is analysis and planning only.
|
|
702
|
-
- Do NOT call ask_user. If anything is ambiguous, add an "## Assumptions" section to the plan and state your assumption. The user approves or rejects the whole plan \u2014 that is the only gate.`}var Ys=0;function YT(){!Ne||Ne.status!=="executing"||(Ys>0&&
|
|
703
|
-
`),n=[],s=!1,o="";for(let r of e){let i=Ay();if(r.trim().startsWith("```")){if(s)n.push(`${A.dim}${"\u2500".repeat(40)}${A.reset}`),s=!1,o="";else{s=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";n.push(`${A.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${A.reset}`)}continue}if(s){n.push(` ${
|
|
704
|
-
`)}function Ks(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function zs(t){return t?t.replace(/`([^`]+)`/g,`${A.cyan}$1${A.reset}`).replace(/\*\*([^*]+)\*\*/g,`${A.bold}$1${A.reset}`).replace(/\*([^*]+)\*/g,`${A.dim}$1${A.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${A.cyan}$1${A.reset} ${A.dim}($2)${A.reset}`):""}function
|
|
702
|
+
- Do NOT call ask_user. If anything is ambiguous, add an "## Assumptions" section to the plan and state your assumption. The user approves or rejects the whole plan \u2014 that is the only gate.`}var Ys=0;function YT(){!Ne||Ne.status!=="executing"||(Ys>0&&Su(Ys-1,"done"),Ys<Ne.steps.length&&(Su(Ys,"in_progress"),Ys++))}function GT(){if(!Ne||Ne.status!=="executing"||Ne.steps.length===0)return null;let t=Math.min(Ys,Ne.steps.length),e=Ne.steps.length,n=Math.max(0,t-1),s=Ne.steps[n]?.description||"";return{current:t,total:e,description:s}}function KT(){Ys=0}var Ty=["interactive","semi-auto","autonomous"],Ry="interactive";function zT(t){return Ty.includes(t)?(Ry=t,!0):!1}function XT(){return Ry}Cy.exports={createPlan:AT,getActivePlan:OT,setPlanMode:MT,isPlanMode:NT,approvePlan:PT,startExecution:LT,updateStep:Su,formatPlan:IT,savePlan:DT,loadPlan:jT,listPlans:qT,clearPlan:WT,getPlanModePrompt:HT,setPlanContent:BT,getPlanContent:UT,extractStepsFromText:FT,advancePlanStep:YT,getPlanStepInfo:GT,PLAN_MODE_ALLOWED_TOOLS:ky,setAutonomyLevel:zT,getAutonomyLevel:XT,AUTONOMY_LEVELS:Ty}});var Fy=K((QM,qy)=>{var{C:A}=Ye();function Ay(){return Math.max(10,(process.stdout.columns||80)-2)}function VT(t){if(!t)return"";let e=t.split(`
|
|
703
|
+
`),n=[],s=!1,o="";for(let r of e){let i=Ay();if(r.trim().startsWith("```")){if(s)n.push(`${A.dim}${"\u2500".repeat(40)}${A.reset}`),s=!1,o="";else{s=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";n.push(`${A.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${A.reset}`)}continue}if(s){n.push(` ${Tu(r,o)}`);continue}if(r.startsWith("### ")){n.push(`${A.bold}${A.cyan} ${Ks(r.substring(4))}${A.reset}`);continue}if(r.startsWith("## ")){n.push(`${A.bold}${A.cyan} ${Ks(r.substring(3))}${A.reset}`);continue}if(r.startsWith("# ")){n.push(`${A.bold}${A.cyan}${Ks(r.substring(2))}${A.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,""),u=`${a}${A.cyan}\u2022${A.reset} ${zs(c)}`;n.push(Xs(u,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let c=a[1],u=a[2],d=a[3],f=`${c}${A.cyan}${u}.${A.reset} ${zs(d)}`,p=c+" ".repeat(u.length+2);n.push(Xs(f,i,p));continue}}n.push(Xs(zs(r),i))}return n.join(`
|
|
704
|
+
`)}function Ks(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function zs(t){return t?t.replace(/`([^`]+)`/g,`${A.cyan}$1${A.reset}`).replace(/\*\*([^*]+)\*\*/g,`${A.bold}$1${A.reset}`).replace(/\*([^*]+)\*/g,`${A.dim}$1${A.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${A.cyan}$1${A.reset} ${A.dim}($2)${A.reset}`):""}function Tu(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Oy(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?My(t):e==="json"||e==="jsonc"?Ny(t):e==="python"||e==="py"?Py(t):e==="go"||e==="golang"?Ly(t):e==="rust"||e==="rs"?Iy(t):e==="css"||e==="scss"||e==="less"?Dy(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?jy(t):t:""}function Oy(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(o,`${A.yellow}$1${A.reset}`),r=r.replace(e,`${A.magenta}$1${A.reset}`),r=r.replace(n,`${A.green}$&${A.reset}`),r=r.replace(s,`${A.dim}$1${A.reset}`),r}function My(t){let e=/^(\s*)([\w-]+)/,n=/(--?\w[\w-]*)/g,s=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(n,`${A.cyan}$1${A.reset}`),r=r.replace(e,`$1${A.green}$2${A.reset}`),r=r.replace(s,`${A.yellow}$&${A.reset}`),r=r.replace(o,`${A.dim}$1${A.reset}`),r}function Ny(t){let e=/("[\w-]+")\s*:/g,n=/:\s*("(?:[^"\\]|\\.)*")/g,s=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${A.cyan}$1${A.reset}:`),r=r.replace(n,`: ${A.green}$1${A.reset}`),r=r.replace(s,`: ${A.yellow}$1${A.reset}`),r=r.replace(o,`: ${A.magenta}$1${A.reset}`),r}function Py(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,n=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,s=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(o,`${A.yellow}$1${A.reset}`),i=i.replace(e,`${A.magenta}$1${A.reset}`),i=i.replace(r,`${A.cyan}$1${A.reset}`),i=i.replace(n,`${A.green}$&${A.reset}`),i=i.replace(s,`${A.dim}$1${A.reset}`),i}function Ly(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,n=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${A.yellow}$1${A.reset}`),i=i.replace(n,`${A.cyan}$1${A.reset}`),i=i.replace(e,`${A.magenta}$1${A.reset}`),i=i.replace(s,`${A.green}$&${A.reset}`),i=i.replace(o,`${A.dim}$1${A.reset}`),i}function Iy(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,n=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,s=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,a=t;return a=a.replace(r,`${A.yellow}$1${A.reset}`),a=a.replace(n,`${A.cyan}$1${A.reset}`),a=a.replace(e,`${A.magenta}$1${A.reset}`),a=a.replace(i,`${A.yellow}$1${A.reset}`),a=a.replace(s,`${A.green}$&${A.reset}`),a=a.replace(o,`${A.dim}$1${A.reset}`),a}function Dy(t){let e=/^(\s*)([\w-]+)\s*:/,n=/:\s*([^;]+)/,s=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,a=t;return a=a.replace(i,`${A.yellow}$1${A.reset}`),a=a.replace(o,`${A.yellow}$1${A.reset}`),a=a.replace(e,`$1${A.cyan}$2${A.reset}:`),a=a.replace(s,`$1${A.magenta}$&${A.reset}`),a=a.replace(r,`${A.dim}$1${A.reset}`),a}function jy(t){let e=/<\/?(\w[\w-]*)/g,n=/\s([\w-]+)=/g,s=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(o,`${A.dim}$1${A.reset}`),i=i.replace(s,`${A.green}$&${A.reset}`),i=i.replace(e,`<${A.magenta}$1${A.reset}`),i=i.replace(n,` ${A.cyan}$1${A.reset}=`),i=i.replace(r,`${A.yellow}$1${A.reset}`),i}function Xs(t,e,n=""){if(!e||e<10)return t;let s="",o=0,r=-1,i=0,a=0,c=t.length;for(;i<c;){if(t[i]==="\x1B"){let u=i+1;if(u<c&&t[u]==="["){for(u++;u<c&&!/[a-zA-Z]/.test(t[u]);)u++;u<c&&u++}i=u;continue}if(t[i]===" "&&(r=i),o++,o>e&&r!==-1){s+=t.slice(a,r)+`
|
|
705
705
|
`+n,a=r+1,i=a,o=n.length,r=-1;continue}o>e&&r===-1&&(s+=t.slice(a,i)+`
|
|
706
706
|
`+n,a=i,o=n.length+1),i++}return s+=t.slice(a),s}function JT(t,e){if(!t||t.length===0)return"";let n=t.map((i,a)=>{let c=e.reduce((u,d)=>Math.max(u,(d[a]||"").length),0);return Math.max(i.length,c)}),s=n.map(i=>"\u2500".repeat(i+2)).join("\u253C"),o=t.map((i,a)=>` ${A.bold}${i.padEnd(n[a])}${A.reset} `).join("\u2502"),r=[];r.push(`${A.dim}\u250C${s.replace(/┼/g,"\u252C")}\u2510${A.reset}`),r.push(`${A.dim}\u2502${A.reset}${o}${A.dim}\u2502${A.reset}`),r.push(`${A.dim}\u251C${s}\u2524${A.reset}`);for(let i of e){let a=t.map((c,u)=>` ${(i[u]||"").padEnd(n[u])} `).join(`${A.dim}\u2502${A.reset}`);r.push(`${A.dim}\u2502${A.reset}${a}${A.dim}\u2502${A.reset}`)}return r.push(`${A.dim}\u2514${s.replace(/┼/g,"\u2534")}\u2518${A.reset}`),r.join(`
|
|
707
|
-
`)}function ZT(t,e,n,s=30){let o=n>0?Math.round(e/n*100):0,r=Math.round(o/100*s),i=s-r,a=o>=100?A.green:o>50?A.yellow:A.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${A.dim}${"\u2591".repeat(i)}${A.reset} ${o}% (${e}/${n})`}var
|
|
707
|
+
`)}function ZT(t,e,n,s=30){let o=n>0?Math.round(e/n*100):0,r=Math.round(o/100*s),i=s-r,a=o>=100?A.green:o>50?A.yellow:A.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${A.dim}${"\u2591".repeat(i)}${A.reset} ${o}% (${e}/${n})`}var Eu=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}_cursorWrite(e){try{process.stderr.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let n=[0,1,2,3,4,3,2,1],s=n[this._cursorFrame%n.length],o="";for(let r=0;r<5;r++)o+=r===s?`${Rt().T.cyan}\u25CF${Rt().T.reset}`:" ";this._cursorWrite(`\x1B[2K\r${o}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let n;for(;(n=this.buffer.indexOf(`
|
|
708
708
|
`))!==-1;){let s=this.buffer.substring(0,n);this.buffer=this.buffer.substring(n+1),this._renderLine(s)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${A.dim}${"\u2500".repeat(40)}${A.reset}
|
|
709
709
|
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=Ay();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${A.dim}${"\u2500".repeat(40)}${A.reset}
|
|
710
710
|
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let o=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${A.dim}${"\u2500".repeat(3)}${o}${"\u2500".repeat(Math.max(0,37-o.length))}${A.reset}
|
|
711
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
711
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${Tu(e,this.codeBlockLang)}
|
|
712
712
|
`);return}if(e.startsWith("### ")){this._safeWrite(`${A.bold}${A.cyan} ${Ks(e.substring(4))}${A.reset}
|
|
713
713
|
`);return}if(e.startsWith("## ")){this._safeWrite(`${A.bold}${A.cyan} ${Ks(e.substring(3))}${A.reset}
|
|
714
714
|
`);return}if(e.startsWith("# ")){this._safeWrite(`${A.bold}${A.cyan}${Ks(e.substring(2))}${A.reset}
|
|
715
715
|
`);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${A.cyan}\u2022${A.reset} ${zs(r)}`,a=Xs(i,n,o+" ");this._safeWrite(`${a}
|
|
716
716
|
`);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}${A.cyan}${i}.${A.reset} ${zs(a)}`,u=r+" ".repeat(i.length+2),d=Xs(c,n,u);this._safeWrite(`${d}
|
|
717
717
|
`);return}}let s=Xs(zs(e),n);this._safeWrite(`${s}
|
|
718
|
-
`)}};qy.exports={renderMarkdown:VT,renderInline:zs,stripHeadingMarkers:Ks,highlightCode:
|
|
718
|
+
`)}};qy.exports={renderMarkdown:VT,renderInline:zs,stripHeadingMarkers:Ks,highlightCode:Tu,highlightJS:Oy,highlightBash:My,highlightJSON:Ny,highlightPython:Py,highlightGo:Ly,highlightRust:Iy,highlightCSS:Dy,highlightHTML:jy,renderTable:JT,renderProgress:ZT,wrapAnsi:Xs,StreamRenderer:Eu}});var Au=K((eN,Hy)=>{var{execSync:QT}=require("child_process"),Ru=require("path"),Fr=require("fs"),Cu=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function By(){return Ru.join(process.cwd(),".nex","hooks")}function e1(){return Ru.join(process.cwd(),".nex","config.json")}function Uy(){let t=e1();if(!Fr.existsSync(t))return{};try{return JSON.parse(Fr.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Pa(t){if(!Cu.includes(t))return[];let e=[],n=By(),s=Ru.join(n,t);Fr.existsSync(s)&&e.push(s);let o=Uy();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function Wy(t,e={},n=3e4){try{return{success:!0,exitCode:0,output:QT(t,{cwd:process.cwd(),encoding:"utf-8",timeout:n,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(s){let o=typeof s.status=="number"?s.status:1;return{success:!1,exitCode:o,blocked:o===2,output:s.stdout?s.stdout.trim():"",error:s.stderr?s.stderr.trim():s.message}}}function t1(t,e={}){let n=Pa(t);if(n.length===0)return{results:[],blocked:!1};let s={};for(let[r,i]of Object.entries(e))s[`NEX_${r.toUpperCase()}`]=String(i);let o=[];for(let r of n){let i=Wy(r,s);if(o.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:o,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:o,blocked:!1}}function n1(t){return Pa(t).length>0}function s1(){let t=[];for(let e of Cu){let n=Pa(e);n.length>0&&t.push({event:e,commands:n})}return t}function o1(){let t=By();return Fr.existsSync(t)||Fr.mkdirSync(t,{recursive:!0}),t}Hy.exports={HOOK_EVENTS:Cu,loadHookConfig:Uy,getHooksForEvent:Pa,executeHook:Wy,runHooks:t1,hasHooks:n1,listHooks:s1,initHooksDir:o1}});var Br=K((oN,o$)=>{"use strict";var{callWithRetry:Gy,runSubAgent:r1,clearAllLocks:i1}=ga(),{parseModelSpec:Ky,getActiveProviderName:tN,getActiveModelId:nN}=We(),{detectCategory:a1,getModelForCategory:Yy}=us(),{MultiProgress:c1,C:we}=Ye(),{getModelBriefing:sN}=ua(),zy=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),La=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Xy="devstral-2:123b",Vy="kimi-k2.5",Jy=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
|
|
719
719
|
|
|
720
720
|
RULES:
|
|
721
721
|
- Output ONLY a JSON array, no markdown fences, no explanation.
|
|
@@ -744,13 +744,13 @@ ORIGINAL REQUEST:
|
|
|
744
744
|
{prompt}
|
|
745
745
|
|
|
746
746
|
SUB-AGENT RESULTS:
|
|
747
|
-
{results}`;async function Qy(t,e=1,n=2e3){for(let s=0;s<=e;s++)try{return await t()}catch(o){if(s===e)throw o;await new Promise(r=>setTimeout(r,n))}}function e$(t){let e=0,n=[];return function(){return new Promise(o=>{let r=()=>{e<t?(e++,o(()=>{e--,n.length>0&&n.shift()()})):n.push(r)};r()})}}function l1(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,n=[],s=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);s&&s.length>=2&&(e=Math.max(e,s.length),n.push(`${s.length} numbered items`));let o=t.match(/(?:^|\n)\s*[-*]\s+\S/g);o&&o.length>=3&&(e=Math.max(e,o.length),n.push(`${o.length} bullet points`));let r=t.split(/;\s*/).filter(u=>u.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),n.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),n.push(`${i.length} transition keywords`));let a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=a,estimatedGoals:e,reason:n.length>0?n.join(", "):"single goal"}}function
|
|
748
|
-
${e.slice(0,200)}`)}async function t$(t,e,n={}){let s=n.maxSubTasks||La,r=[{role:"system",content:Jy.replace("{maxSubTasks}",String(s)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=Ky(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let c=(await Gy(r,[],i)).content||"",u=
|
|
747
|
+
{results}`;async function Qy(t,e=1,n=2e3){for(let s=0;s<=e;s++)try{return await t()}catch(o){if(s===e)throw o;await new Promise(r=>setTimeout(r,n))}}function e$(t){let e=0,n=[];return function(){return new Promise(o=>{let r=()=>{e<t?(e++,o(()=>{e--,n.length>0&&n.shift()()})):n.push(r)};r()})}}function l1(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,n=[],s=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);s&&s.length>=2&&(e=Math.max(e,s.length),n.push(`${s.length} numbered items`));let o=t.match(/(?:^|\n)\s*[-*]\s+\S/g);o&&o.length>=3&&(e=Math.max(e,o.length),n.push(`${o.length} bullet points`));let r=t.split(/;\s*/).filter(u=>u.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),n.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),n.push(`${i.length} transition keywords`));let a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=a,estimatedGoals:e,reason:n.length>0?n.join(", "):"single goal"}}function Ou(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let n=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(n)try{return JSON.parse(n[1].trim())}catch{}let s=e.search(/[[\{]/);if(s>=0){let o=e.slice(s);try{return JSON.parse(o)}catch{}}throw new Error(`Could not extract valid JSON from response:
|
|
748
|
+
${e.slice(0,200)}`)}async function t$(t,e,n={}){let s=n.maxSubTasks||La,r=[{role:"system",content:Jy.replace("{maxSubTasks}",String(s)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=Ky(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let c=(await Gy(r,[],i)).content||"",u=Ou(c);if(!Array.isArray(u))throw new Error(`Decompose returned non-array: ${typeof u}`);let d=10,p=u.slice(0,s).map((g,$)=>({id:g.id||`t${$+1}`,task:String(g.task||""),scope:Array.isArray(g.scope)?g.scope:[],estimatedCalls:typeof g.estimatedCalls=="number"?Math.min(g.estimatedCalls,d):8,priority:typeof g.priority=="number"?g.priority:$+1})).filter(g=>g.task.length>0),m=p.reduce((g,$)=>g+$.estimatedCalls,0),h=La*d;if(m>h){let{debugLog:g}=nr();g(`${Rt().T.yellow} \u26A0 Orchestrator: total estimated calls ${m} > ${h} \u2014 consider raising maxSubTasks${Rt().T.reset}`)}return p}async function n$(t,e,n){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let s=t.map((d,f)=>{let p=d.status==="done"?"SUCCESS":d.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${f+1} [${p}] ---
|
|
749
749
|
Task: ${d.task}
|
|
750
750
|
Result: ${d.result}
|
|
751
751
|
Tools: ${(d.toolsUsed||[]).join(", ")||"none"}`}).join(`
|
|
752
752
|
|
|
753
|
-
`),r=[{role:"system",content:Zy.replace("{prompt}",e).replace("{results}",s)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let d=Ky(n);d.provider&&(i.provider=d.provider),d.model&&(i.model=d.model)}let c=(await Gy(r,[],i)).content||"",u=
|
|
753
|
+
`),r=[{role:"system",content:Zy.replace("{prompt}",e).replace("{results}",s)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let d=Ky(n);d.provider&&(i.provider=d.provider),d.model&&(i.model=d.model)}let c=(await Gy(r,[],i)).content||"",u=Ou(c);return{summary:String(u.summary||""),conflicts:Array.isArray(u.conflicts)?u.conflicts:[],commitMessage:String(u.commitMessage||""),filesChanged:Array.isArray(u.filesChanged)?u.filesChanged:[]}}async function u1(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Vy,s=e.workerModel||Xy,o=e.maxParallel||zy,r=e.maxSubTasks||La,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
|
|
754
754
|
${we.bold}Orchestrator${we.reset} ${we.dim}model: ${n} | workers: ${s} | max parallel: ${o}${we.reset}
|
|
755
755
|
`),i("decomposing"),console.log(`${we.dim}Phase 1: Decomposing prompt into sub-tasks...${we.reset}`);let c;try{c=await t$(t,n,{maxSubTasks:r})}catch(G){return console.log(`${we.red}Decompose failed: ${G.message}${we.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${G.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(c.length===0)return console.log(`${we.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${we.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${we.green}Decomposed into ${c.length} sub-tasks:${we.reset}`);for(let G of c){console.log(` ${we.dim}${G.id}:${we.reset} ${G.task}`);let z=G.scope.filter(Boolean);z.length>0&&console.log(` ${we.dim}scope: ${z.join(", ")}${we.reset}`)}console.log("");let u=new Map;for(let G=0;G<c.length;G++)for(let z of c[G].scope)z&&!u.has(z)&&u.set(z,G);i("executing"),console.log(`${we.dim}Phase 2: Running ${c.length} sub-agents (max ${o} parallel)...${we.reset}
|
|
756
756
|
`);let d=Date.now(),f=e$(o),p={findings:[],_lock:!1},m=c.map(G=>{let z=a1(G.task);return(z?Yy(z.id):null)||s}),h=c.map((G,z)=>{let fe=`Agent ${z+1} [${m[z]}]: `,Ee=Math.max(20,60-fe.length),Ae=G.task.substring(0,Ee)+(G.task.length>Ee?"...":"");return fe+Ae}),g=new c1(h);g.start();let $=`
|
|
@@ -782,7 +782,7 @@ ${Ee}
|
|
|
782
782
|
`):void 0,max_iterations:Math.min(G.estimatedCalls||10,15),model:Z,_skipLog:!0,_systemPrompt:$,_readOnlyFiles:ve},{onUpdate:ne=>{if(ne&&ne.type==="tool_call"&&process.stderr.isTTY){let Q=`Agent ${z+1} [${Z}]`,ge=ne.tool||"...";g.labels[z]=`${Q}: ${ge}`}}})},1,2e3),R=typeof M.result=="string"?M.result.slice(0,200):String(M.result||"").slice(0,200);return p.findings.push({agentId:G.id,summary:R,files:Array.isArray(G.scope)?G.scope:[]}),g.labels[z]=h[z],g.update(z,M.status==="failed"?"error":"done"),a.input+=M.tokensUsed?.input||0,a.output+=M.tokensUsed?.output||0,M.tokensUsed?._estimated&&(a._estimated=!0),{...M,_scope:G.scope,_idx:z}}catch(Ee){return g.labels[z]=h[z],g.update(z,"error"),{task:G.task,status:"failed",result:`Error: ${Ee.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let x;try{x=E}finally{g.stop({silent:!0}),i1()}console.log("");let C=Math.round((Date.now()-d)/1e3),H=C>=60?`${Math.floor(C/60)}m ${C%60}s`:`${C}s`;for(let G=0;G<x.length;G++){let z=x[G],Ee=z.status==="done"||z.status==="truncated"&&z.result&&!z.result.startsWith("Error")?`${we.green}\u2713${we.reset}`:`${we.red}\u2717${we.reset}`,Ae=z._scope&&z._scope.length>0?z._scope.map(v=>v.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],ve=Ae.length>0?Ae.join(", "):z.task.substring(0,35)+(z.task.length>35?"...":""),be=G===x.length-1;console.log(` ${Ee} Agent ${G+1} ${we.dim}${ve}${we.reset}${be?` ${we.dim}${H}${we.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${we.dim}Phase 3: Synthesizing results...${we.reset}`);let q;try{q=await n$(x,t,n)}catch(G){console.log(`${we.yellow}Synthesize failed: ${G.message} \u2014 using raw results.${we.reset}`),q={summary:x.map(z=>z.result).join(`
|
|
783
783
|
`),conflicts:[],commitMessage:"",resourcesChanged:[]}}let ie=p.findings.flatMap(G=>G.files),le=new Map;for(let G of ie)le.set(G,(le.get(G)||0)+1);let te=[...le.values()].some(G=>G>1),T=p.findings.length>1&&te?` ${we.dim}(agents shared context)${we.reset}`:"";if(console.log(`
|
|
784
784
|
${we.bold}Summary:${we.reset} ${q.summary}${T}`),q.conflicts.length>0){console.log(`${we.yellow}Conflicts:${we.reset}`);for(let G of q.conflicts)console.log(` - ${G}`)}q.commitMessage&&console.log(`${we.dim}Suggested commit: ${q.commitMessage}${we.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(`${we.dim}Tokens: ${Te}${we.reset}
|
|
785
|
-
`),{results:x,synthesis:q,totalTokens:a}}var d1=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,f1=/\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 s$(t){if(!t)return"implement";let e=d1.test(t);return f1.test(t)?"implement":e?"explore":"implement"}o$.exports={runOrchestrated:u1,decompose:t$,synthesize:n$,detectComplexPrompt:l1,extractJSON:
|
|
785
|
+
`),{results:x,synthesis:q,totalTokens:a}}var d1=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,f1=/\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 s$(t){if(!t)return"implement";let e=d1.test(t);return f1.test(t)?"implement":e?"explore":"implement"}o$.exports={runOrchestrated:u1,decompose:t$,synthesize:n$,detectComplexPrompt:l1,extractJSON:Ou,createSemaphore:e$,DECOMPOSE_PROMPT:Jy,SYNTHESIZE_PROMPT:Zy,DEFAULT_ORCHESTRATOR_MODEL:Vy,DEFAULT_WORKER_MODEL:Xy,DEFAULT_MAX_PARALLEL:zy,DEFAULT_MAX_SUBTASKS:La,withRetry:Qy,_classifyWorkerType:s$}});var Se=K((uN,A$)=>{var{C:y,Spinner:Bo,TaskProgress:p1,formatToolCall:h1,formatToolSummary:Wu,formatSectionHeader:Ia,formatMilestone:m1,setActiveTaskProgress:rN,getThinkingVerb:Mu,setActiveModelForSpinner:g1}=Ye(),{debugLog:W,warnLog:iN}=nr(),{MilestoneTracker:y1}=lp(),{callStream:r$}=We(),{parseToolArgs:$1}=bo(),{executeTool:w1}=fn(),{gatherProjectContext:b1}=Ta(),{fitToContext:_1,forceCompress:Nn,getUsage:bn,estimateTokens:x1,buildProgressSnapshot:S1}=Ht(),{autoSave:v1,flushAutoSave:k1}=$n(),{scoreMessages:E1,formatScore:T1,appendScoreHistory:R1}=Ca(),{detectCategory:C1,getModelForPhase:Hu,getPhaseBudget:Vs,isPhaseRoutingEnabled:A1}=us();function ze(t){v1(t),k1()}function O1(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 Da(t){try{if(!t.some(s=>s.role!=="assistant"?!1:!!(Array.isArray(s.content)&&s.content.some(o=>o&&o.type==="tool_use")||Array.isArray(s.tool_calls)&&s.tool_calls.length>0)))return;let n=E1(t);if(!n)return;console.log(T1(n,y));try{let{_getSessionsDir:s}=$n(),o=require("fs"),r=require("path").join(s(),"_autosave.json");if(o.existsSync(r)){let i=JSON.parse(o.readFileSync(r,"utf-8"));i.score=n.score,i.scoreGrade=n.grade,i.scoreIssues=n.issues,o.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:s}=bo(),o=lo();R1(n.score,{version:o.version,model:s?s():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:M1}=mn(),{getDeploymentContextBlock:N1,probeUrlServer:P1}=mu(),{getFewShotForInput:L1}=wy(),{checkPermission:I1,setPermission:D1,savePermissions:j1}=qr(),{confirm:w$,setAllowAlwaysHandler:q1,getAutoConfirm:Va}=_t(),{isPlanMode:Jr,getPlanModePrompt:F1,PLAN_MODE_ALLOWED_TOOLS:b$,setPlanContent:B1,extractStepsFromText:U1,createPlan:W1,getActivePlan:aN,startExecution:cN,advancePlanStep:H1,getPlanStepInfo:Y1}=wn(),{StreamRenderer:G1}=Fy(),{runHooks:i$}=Au(),{routeMCPCall:K1,getMCPToolDefinitions:z1}=Ki(),{getSkillInstructions:X1,getSkillToolDefinitions:V1,routeSkillCall:J1,matchSkillTriggers:Z1}=Wn(),{trackUsage:a$,estimateTokens:c$}=wo();function l$(t){return!t||typeof t!="string"?0:typeof c$=="function"?c$(t):Math.ceil(t.length/4)}var{validateToolArgs:Q1}=fl(),{filterToolsForModel:u$,getModelTier:eR,PROVIDER_DEFAULT_TIER:lN}=fr(),{getConfiguredProviders:tR,getActiveProviderName:Uo,getActiveModelId:xn,setActiveModel:d$,MODEL_EQUIVALENTS:Ja}=We(),{getModelProfile:nR,getModelBriefing:sR}=ua(),ps=require("fs"),tc=require("path"),oR=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function rR(t){let e=m1(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
|
|
786
786
|
`)}var f$=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,p$=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,iR=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function aR(t){let e=[],n;for(f$.lastIndex=0;(n=f$.exec(t))!==null;){let s=n[1].trim(),o=s.startsWith("~")?s.replace("~",process.env.HOME||""):tc.resolve(s);ps.existsSync(o)&&e.push({raw:s,abs:o})}return e}function _$(t){let e=[],n;for(p$.lastIndex=0;(n=p$.exec(t))!==null;)e.push(n[1].trim());return e}async function x$(t){try{let n=await require("axios").get(t,{responseType:"arraybuffer",timeout:1e4,maxContentLength:10*1024*1024,headers:{"User-Agent":"nex-code/vision"}}),s=n.headers["content-type"]||"",o=s.startsWith("image/")?s.split(";")[0]:cR(t);return{data:Buffer.from(n.data).toString("base64"),media_type:o}}catch{return null}}function cR(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 S$(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=tc.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&ps.existsSync(e)){let o=ps.readFileSync(e);if(o.length>100)return{data:o.toString("base64"),media_type:"image/png",path:e};try{ps.unlinkSync(e)}catch{}}let s=t("osascript",["-e",`try
|
|
787
787
|
set imgData to the clipboard as \xABclass PNGf\xBB
|
|
788
788
|
return "has_image"
|
|
@@ -798,10 +798,10 @@ end try`],{timeout:3e3});if(s.stdout&&s.stdout.toString().trim()==="has_image"){
|
|
|
798
798
|
[Clipboard image attached: ${i.path}]`):r[0].text+=`
|
|
799
799
|
[No image found in clipboard]`}return r.length>1?r:t})()}var lR=[/\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 k$(t){return typeof t!="string"||!t?!1:lR.some(e=>e.test(t))}function uR(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let n=t.split(/(?<=\. )/).filter(c=>c.trim().length>0);if(n.length<6)return{text:t,truncated:!1,repeatCount:0};let s=new Map;for(let c=0;c<=n.length-3;c++){let u=n.slice(c,c+3).join("").trim();u.length>30&&s.set(u,(s.get(u)||0)+1)}let o=0,r="";for(let[c,u]of s)u>o&&(o=u,r=c);if(o<3)return{text:t,truncated:!1,repeatCount:o};let i=`
|
|
800
800
|
|
|
801
|
-
[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,u=-1,d=0;for(;c<2;){let f=t.indexOf(r,d);if(f===-1)break;c++,u=f+r.length,d=f+1}a=u>0?t.slice(0,u)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:o}}function
|
|
801
|
+
[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,u=-1,d=0;for(;c<2;){let f=t.indexOf(r,d);if(f===-1)break;c++,u=f+r.length,d=f+1}a=u>0?t.slice(0,u)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:o}}function Yu(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let n=t.split(`
|
|
802
802
|
`),s=new Map;for(let m of n){let h=m.trim();h.length>=20&&s.set(h,(s.get(h)||0)+1)}let o=0,r="";for(let[m,h]of s)h>o&&(o=h,r=m);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=`
|
|
803
803
|
|
|
804
|
-
\u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,u=0,d=-1,f=0;for(;u<e;){let m=t.indexOf(r,f);if(m===-1)break;u++,d=m+r.length,f=m+1}return{text:d>0?t.slice(0,d)+c:t.slice(0,2e3)+c,truncated:!0,repeatCount:o}}var
|
|
804
|
+
\u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,u=0,d=-1,f=0;for(;u<e;){let m=t.indexOf(r,f);if(m===-1)break;u++,d=m+r.length,f=m+1}return{text:d>0?t.slice(0,d)+c:t.slice(0,2e3)+c,truncated:!0,repeatCount:o}}var Nu=null,Pu=null,Lu=null;function St(){if(Nu===null){let{TOOL_DEFINITIONS:t}=fn();Nu=t}return Pu===null&&(Pu=V1()),Lu===null&&(Lu=z1()),[...Nu,...Pu,...Lu]}var Gu=50;function dR(t){Number.isFinite(t)&&t>0&&(Gu=t)}var Fa=()=>null;function fR(t){Fa=t}var Yr=null,Ku=null,Wo=null,Ba=new Map,pR=1e4,hR=6e3,mR=/\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 gR(t){return!t||typeof t!="string"?t:t.replace(mR,(e,n)=>`${n}=***REDACTED***`)}var yR=7e3,$R=4e3;function wR(t,e=null){let n=gR(t),s=x1(n),o=e==="read_file"?yR:pR,r=e==="read_file"?$R:hR;if(s>o)try{let{compressToolResult:i}=Ht();return i(n,r)}catch{return n}return n}function E$(t){try{let{getActiveModel:e}=We(),n=e(),s=n?`${n.provider}:${n.id}`:"default";if(Ba.has(s))return Ba.get(s);let o=u$(t);return Ba.set(s,o),o}catch{return u$(t)}}function bR(){Ba.clear()}var Gr={hash:null,ts:0},_R=3e4;async function T$(){if(Gr.hash&&Date.now()-Gr.ts<_R)return Gr.hash;try{let t=require("fs").promises,e=require("path"),n=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],o=(await Promise.allSettled(n.map(i=>t.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=mn(),a=i();a&&o.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(ps.existsSync(i)){let a=await t.stat(i);o.push(`brain:${a.mtimeMs}`)}}catch{}let r=o.join("|");return Gr={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function zu(){Yr=null,Ku=null,Gr={hash:null,ts:0},Wo=null}var xR=new Set(["spawn_agents"]),Iu=5,Du=3,ja=2,m$=6e4,ju=12e4,SR=process.env.NEX_STALE_AUTO_SWITCH!=="0";function vR(t){try{let e=require("fs"),n=require("path"),s=n.join(process.cwd(),".nex","plans");e.existsSync(s)||e.mkdirSync(s,{recursive:!0});let o=n.join(s,"current-plan.md");e.writeFileSync(o,t,"utf-8")}catch{}}q1(t=>{D1(t,"allow"),j1(),console.log(`${y.green} \u2713 ${t}: always allow${y.reset}`)});async function kR(t){let e=t.function.name,n=$1(t.function.arguments),s=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!n){let d=St().find(p=>p.function.name===e),f=d?JSON.stringify(d.function.parameters,null,2):"unknown";return W(`${y.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${y.reset}`),{callId:s,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
805
805
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
806
806
|
|
|
807
807
|
Expected JSON schema for "${e}":
|
|
@@ -810,17 +810,17 @@ ${f}
|
|
|
810
810
|
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:s}}}let o=Q1(e,n);if(!o.valid){W(`${y.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
811
811
|
`)[0]}${y.reset}`);let u=(y$.get(e)||0)+1;y$.set(e,u);let d=u>=2?`${o.error}
|
|
812
812
|
|
|
813
|
-
[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:s,fnName:e,args:n,canExecute:!1,errorResult:{role:"tool",content:d,tool_call_id:s}}}let r=o.corrected||n;if(o.corrected){let u=Object.keys(n),d=Object.keys(o.corrected),f=u.filter(p=>!d.includes(p));f.length&&console.log(`${y.dim} \u2713 ${e}: corrected args (${f.join(", ")})${y.reset}`)}if(Jr()&&!b$.has(e))return console.log(`${y.yellow} \u2717 ${e}: blocked in plan mode${y.reset}`),{callId:s,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:s}};let i=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),a=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]);if(Oe&&Ze==="plan"&&!i.has(e)&&!e.startsWith("skill_"))return hs++,W(`${y.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${hs})${y.reset}`),{callId:s,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:s}};if(Oe&&Ze==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return W(`${y.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${y.reset}`),{callId:s,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:s}};let c=I1(e);if(c==="deny")return console.log(`${y.red} \u2717 ${e}: denied by permissions${y.reset}`),{callId:s,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:s}};if(c==="ask"){let u=` Allow ${e}?`;return e==="bash"&&r.command&&(u=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await w$(u,{toolName:e})?{callId:s,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:s,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:s}}}return{callId:s,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function ER(t,e,n={}){let s=await J1(t,e);if(s!==null)return s;let o=await K1(t,e);return o!==null?o:w1(t,e,n)}function TR(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function
|
|
813
|
+
[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:s,fnName:e,args:n,canExecute:!1,errorResult:{role:"tool",content:d,tool_call_id:s}}}let r=o.corrected||n;if(o.corrected){let u=Object.keys(n),d=Object.keys(o.corrected),f=u.filter(p=>!d.includes(p));f.length&&console.log(`${y.dim} \u2713 ${e}: corrected args (${f.join(", ")})${y.reset}`)}if(Jr()&&!b$.has(e))return console.log(`${y.yellow} \u2717 ${e}: blocked in plan mode${y.reset}`),{callId:s,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:s}};let i=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),a=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]);if(Oe&&Ze==="plan"&&!i.has(e)&&!e.startsWith("skill_"))return hs++,W(`${y.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${hs})${y.reset}`),{callId:s,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:s}};if(Oe&&Ze==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return W(`${y.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${y.reset}`),{callId:s,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:s}};let c=I1(e);if(c==="deny")return console.log(`${y.red} \u2717 ${e}: denied by permissions${y.reset}`),{callId:s,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:s}};if(c==="ask"){let u=` Allow ${e}?`;return e==="bash"&&r.command&&(u=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await w$(u,{toolName:e})?{callId:s,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:s,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:s}}}return{callId:s,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function ER(t,e,n={}){let s=await J1(t,e);if(s!==null)return s;let o=await K1(t,e);return o!==null?o:w1(t,e,n)}function TR(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function qu(t,e=!1){e||console.log(h1(t.fnName,t.args));let n=i$("pre-tool",{tool_name:t.fnName}),s=n.results;if(n.blocked){let $=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${n.blockReason}`;e||console.log(`${y.yellow} [hook pre-tool] BLOCKED: ${n.blockReason}${y.reset}`);let w=Wu(t.fnName,t.args,$,!0);return e||console.log(w),{msg:{role:"tool",content:$,tool_call_id:t.callId},summary:w}}if(!e&&s.length>0)for(let $ of s)$.success?console.log(`${y.dim} [hook pre-tool] ${$.command} \u2192 ${$.output||"ok"}${y.reset}`):console.log(`${y.yellow} [hook pre-tool] ${$.command} \u2192 ERROR: ${$.error}${y.reset}`);Ln?.onToolStart&&Ln.onToolStart(t.fnName,t.args);let o=await ER(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)+`
|
|
814
814
|
...(truncated ${i.length-5e4} chars)`:i,c=a.split(`
|
|
815
|
-
`)[0],u=c.startsWith("ERROR")||c.includes("CANCELLED")||c.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),d=
|
|
815
|
+
`)[0],u=c.startsWith("ERROR")||c.includes("CANCELLED")||c.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),d=Wu(t.fnName,t.args,a,u);e||console.log(d),Ln?.onToolEnd&&Ln.onToolEnd(t.fnName,d,!u);let p=i$("post-tool",{tool_name:t.fnName}).results;if(!e&&p.length>0)for(let $ of p)$.success?console.log(`${y.dim} [hook post-tool] ${$.command} \u2192 ${$.output||"ok"}${y.reset}`):console.log(`${y.yellow} [hook post-tool] ${$.command} \u2192 ERROR: ${$.error}${y.reset}`);let h=wR(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let $=t.args.command.trim();!/cat\s*>|<</.test($)&&/\bcat\s+\S/.test($)?h+=`
|
|
816
816
|
HINT: use read_file instead of bash cat \u2014 it is faster, context-efficient, and the preferred tool for reading files.`:/^\s*ls(\s|$)/.test($)&&!/npm|yarn|pnpm|make|git\b/.test($)?h+=`
|
|
817
817
|
HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test($)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test($)&&(h+=`
|
|
818
|
-
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($=>({type:"image",media_type:$.media_type,data:$.base64}))]:h,tool_call_id:t.callId},summary:d}}var RR=[{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
|
|
819
|
-
`)):(
|
|
820
|
-
`)}function Hr(t,e,n,s){if(!Oe)return null;let o=Ze;Ze=t,ec=0,Zn=
|
|
821
|
-
${
|
|
818
|
+
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($=>({type:"image",media_type:$.media_type,data:$.base64}))]:h,tool_call_id:t.callId},summary:d}}var RR=[{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 Fu(t){for(let{re:e,label:n}of RR){let s=t.match(e);if(s){let o=(s[1]||"").trim();return o?`${n}: ${o}`:n}}return null}async function CR(t,e=!1,n={}){let s=new Array(t.length),o=[],r=[],i=null;if(e&&!n.skipSpinner){let c=t.filter(u=>u.canExecute);if(c.length>0){let u;if(c.length===1){let d=c[0],f=TR(d.fnName,d.args);u=`\u23FA ${d.fnName}${f?`(${f})`:""}`}else{let d=c.map(f=>f.fnName).join(", ");u=`\u23FA ${c.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}i=new Bo(u),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let c=r[0],{msg:u,summary:d}=await qu(t[c],e);s[c]=u,o.push(d)}else{let c=r.map(d=>qu(t[d],e)),u=await Promise.all(c);for(let d=0;d<r.length;d++)s[r[d]]=u[d].msg,o.push(u[d].summary)}r=[]}}for(let c=0;c<t.length;c++){let u=t[c];if(!u.canExecute){await a(),s[c]=u.errorResult,o.push(Wu(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(xR.has(u.fnName)){await a(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await qu(u,e);s[c]=d,o.push(f)}else r.push(c)}if(await a(),i&&i.stop(),e&&o.length>0&&!n.skipSummaries)for(let c of o)console.log(c);return{results:s,summaries:o}}var B=[],g$=300,R$=900*1e3;function Pn(t,e){let n=t.get(e);return n?Date.now()-n.ts>R$?(t.delete(e),0):n.count:0}function Js(t,e){let n=t.get(e),s=n&&Date.now()-n.ts<=R$?n.count+1:1;return t.set(e,{count:s,ts:Date.now()}),s}function Bu(t,e,n){t.set(e,{count:n,ts:Date.now()})}var nd=new Map,sd=new Map,Zr=new Map,od=new Map,Qr=new Map,fs=new Map,Vn=new Map,ei=new Map,on=new Map,to=new Map,y$=new Map,Za=new Map,Qa=new Map,rn=0,Kr=0,Ua=0,Xu="",Wa=0,zt=!1,qa=0,Ha=0,Zs=-1,Vu=!1,Ya=0,Ga=!1,cn=0,ln=!1,Jn=0,_n=0,ht=!1,Bt="",zr=0,ds=0,Ka="",Qs=0,eo=0,za="",Ur=0,an=!1,Ju=!1,ti=new Map,ni=new Set,Xr=null,Uu=!1,Wr=0,$$=!1,Ze="plan",ec=0,Oe=!1,hs=0,Zn=null,Zu=null,Qu=null,Vr=0,Ho=null;function Fo(t,e){t===Xu?(Wa++,nr().DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${Wa})${y.reset}
|
|
819
|
+
`)):(Xu=t,Wa=1,W(`${e} \u26A0 ${t}${y.reset}`))}var Xa=[];function AR(t){Xa.push(t.trim())}function OR(){return Xa.length===0?null:Xa.splice(0,Xa.length).join(`
|
|
820
|
+
`)}function Hr(t,e,n,s){if(!Oe)return null;let o=Ze;Ze=t,ec=0,Zn=Hu(t,Ho),cn=0,ln=!1,Jn=0,_n=0,fs.clear(),Vn.clear(),to.clear(),Za.clear(),Qa.clear(),sd.clear(),Zr.clear(),od.clear(),Qr.clear(),nd.clear(),ei.clear();let r;if(t==="implement")Zu=e?.slice(0,800)||"",r=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
|
|
821
|
+
${Zu}
|
|
822
822
|
|
|
823
|
-
Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`;else if(t==="verify"){
|
|
823
|
+
Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`;else if(t==="verify"){Qu=e?.slice(0,500)||"";let i=n?[...n].join(", "):"none";r=`[PHASE: VERIFICATION] Implementation complete. Verify the changes:
|
|
824
824
|
1. Read each modified file and confirm changes are correct
|
|
825
825
|
2. If test command exists (npm test / pytest): run it
|
|
826
826
|
3. If linter exists: run it
|
|
@@ -828,7 +828,7 @@ Now implement the fix/changes. Do not investigate further \u2014 edit files dire
|
|
|
828
828
|
Report PASS (all good) or FAIL (list specific issues).
|
|
829
829
|
|
|
830
830
|
Files modified: ${i}
|
|
831
|
-
Summary: ${
|
|
831
|
+
Summary: ${Qu}`}return W(`${y.cyan} \u21B3 Phase transition: ${o} \u2192 ${t} (model: ${Zn||"default"})${y.reset}`),r?{role:"user",content:r}:null}function MR(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,n=process.env.NEX_COMMIT_LANGUAGE,s=!t||t==="auto"?null:t,o=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
832
832
|
`];s?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${s}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${s} only.`):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"),Va()?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 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=n||"English";return o.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),s&&o.push(`
|
|
833
833
|
This is a hard requirement. Always respond in ${s}. Do NOT switch to any other language \u2014 even if the user writes to you in German, French, or any other language, your reply MUST be in ${s}.`),o.join(`
|
|
834
834
|
`)+`
|
|
@@ -839,7 +839,7 @@ This is a hard requirement. Always respond in ${s}. Do NOT switch to any other l
|
|
|
839
839
|
`;s+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',s+=`| Model | Tier | Auto-assigned for |
|
|
840
840
|
|---|---|---|
|
|
841
841
|
`;for(let o of e)s+=`| ${o.spec} | ${o.tier} | ${n[o.tier]||o.tier} |
|
|
842
|
-
`;return Wo=s,s}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Wo="",""}}var
|
|
842
|
+
`;return Wo=s,s}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Wo="",""}}var ed="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function PR(t){let e=t.indexOf(ed);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+ed.length).trimStart()}}async function td(){let t=await T$()+":"+xn();if(Yr!==null&&t===Ku)return Yr;let e=await b1(process.cwd()),n=M1(),s=X1(),o=Jr()?F1():"",r=MR(),i=N1(),a=sR(xn());return Yr=`${a?`## Model Briefing
|
|
843
843
|
${a}
|
|
844
844
|
|
|
845
845
|
---
|
|
@@ -1279,11 +1279,11 @@ class ErrorBoundary extends React.Component {
|
|
|
1279
1279
|
- Use migrations for schema changes, never manual ALTER TABLE
|
|
1280
1280
|
- Add database-level constraints (unique, foreign key, check) not just app-level
|
|
1281
1281
|
|
|
1282
|
-
`,
|
|
1282
|
+
`,Ku=t,Yr}function C$(){nd.clear(),sd.clear(),Zr.clear(),od.clear(),Qr.clear(),fs.clear(),Vn.clear(),ei.clear(),on.clear(),to.clear(),Za.clear(),Qa.clear(),rn=0,Kr=0,Ua=0,zt=!1,Ha=0,Zs=-1,Vu=!1,Ya=0,Ga=!1,cn=0,ln=!1,Jn=0,_n=0,ht=!1,Bt="",zr=0,Ka="",Qs=0,za="",eo=0,an=!1,Ju=!1,Ze="plan",ec=0,Oe=!1,Zn=null,Zu=null,Qu=null,Vr=0,hs=0,Ho=null,ti.clear(),ni.clear(),Xu="",Wa=0}function LR(){B=[],Xr=null,C$();try{let{resetCompactionFailures:t}=Kl();t()}catch{}}function IR(){B.length>g$&&B.splice(0,B.length-g$)}function DR(){return B.length}function jR(){return B}function qR(t){B=t}async function FR(){let{execFile:t}=require("child_process"),e=require("fs"),n=process.cwd(),s=(f,p)=>new Promise(m=>{t(f,p,{cwd:n,timeout:3e3},(h,g)=>{m(h?"":(g||"").trim())})}),[o]=await Promise.all([s("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(o?o.split(`
|
|
1283
1283
|
`):[]).filter(f=>{let p=f.split(".").pop();return r.has(p)});if(i.length<3)return null;let a={};for(let f of i){let p=f.split(".").pop();a[p]=(a[p]||0)+1}let u=` \u{1F4C1} ${Object.entries(a).sort((f,p)=>p[1]-f[1]).slice(0,4).map(([f,p])=>`${p} .${f}`).join(" \xB7 ")}`,d=tc.join(n,"package.json");if(e.existsSync(d))try{let f=JSON.parse(e.readFileSync(d,"utf-8")),p=Object.keys({...f.dependencies||{},...f.devDependencies||{}});if(p.length>0){let m=p.slice(0,5).join(" \xB7 "),h=p.length>5?` +${p.length-5}`:"";u+=`
|
|
1284
1284
|
\u{1F4E6} ${m}${h}`}}catch{}return u}function BR(t){if(process.platform==="darwin")try{let{execFileSync:e}=require("child_process");e("osascript",["-e",`display notification "${t.replace(/"/g,'\\"')}" with title "nex-code"`],{timeout:3e3,stdio:"ignore"})}catch{}}function Je(t,e,n,s,o,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((u,d)=>u+d,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,c=0;if(o){let u=Date.now()-o;c=Math.round(u/1e3),a+=c>=60?` \xB7 ${Math.floor(c/60)}m ${c%60}s`:` \xB7 ${c}s`}if(n.size>0&&(a+=` \xB7 ${n.size} ${n.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
|
|
1285
1285
|
${y.dim} ${a}${y.reset}`),c>=30&&process.stdout.isTTY){let u=n.size>0?`Done \u2014 ${n.size} ${n.size===1?"file":"files"} modified in ${c}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${c}s`;BR(u)}if(ni.size>0&&ti.size>0)for(let u of ni){let d=ti.get(u);d&&console.log(`${y.dim} \u2714 task #${u} auto-matched: ${d.slice(0,60)}${y.reset}`)}n.size>0?console.log(`${y.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${y.reset}`):!r&&s.size>=5&&n.size===0&&t>=3?console.log(`${y.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${y.reset}`):s.size>0&&t>=2&&console.log(`${y.dim} \u{1F4A1} /save \xB7 /clear${y.reset}`)}async function UR(){if(!process.stdout.isTTY)return{action:"quit"};let t=Uo(),e=xn(),n=Ja.fast?.[t],s=Ja.strong?.[t],o=n&&n!==e,r=s&&s!==e&&s!==n,i=[];i.push({key:"r",label:`Retry with current model ${y.dim}(${e})${y.reset}`}),o&&i.push({key:"f",label:`Switch to ${y.bold}${n}${y.reset} ${y.dim}\u2014 fast, low latency${y.reset}`,model:n}),r&&i.push({key:"s",label:`Switch to ${y.bold}${s}${y.reset} ${y.dim}\u2014 reliable tool-calling, medium speed${y.reset}`,model:s}),i.push({key:"q",label:`${y.dim}Quit${y.reset}`}),console.log(),console.log(`${y.yellow} Stream stale \u2014 all retries exhausted.${y.reset} What would you like to do?`);for(let a of i)console.log(` ${y.cyan}[${a.key}]${y.reset} ${a.label}`);return process.stdout.write(` ${y.yellow}> ${y.reset}`),new Promise(a=>{let c=process.stdin,u=c.isRaw;c.setRawMode(!0),c.resume(),c.setEncoding("utf8");let d=!1,f=p=>{if(d)return;d=!0,c.removeListener("data",f),c.setRawMode(u||!1),c.pause();let m=p.toLowerCase().trim();if(process.stdout.write(`${m}
|
|
1286
|
-
`),p==="")return a({action:"quit"});let h=i.find(g=>g.key===m);!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",f)})}var Ln=null;async function WR(t,e=null,n={}){let s=nR(xn());m$=s.staleWarn,
|
|
1286
|
+
`),p==="")return a({action:"quit"});let h=i.find(g=>g.key===m);!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",f)})}var Ln=null;async function WR(t,e=null,n={}){let s=nR(xn());m$=s.staleWarn,ju=s.staleAbort,Ln=e;let o=t;Xr&&typeof t=="string"&&(o=`${Xr}
|
|
1287
1287
|
|
|
1288
1288
|
${t}`,Xr=null),typeof o=="string"&&k$(o)&&(o+=`
|
|
1289
1289
|
|
|
@@ -1293,59 +1293,59 @@ Files changed: ${Et.synthesis.filesChanged.join(", ")}`:"",ct=Et.synthesis.confl
|
|
|
1293
1293
|
|
|
1294
1294
|
Conflicts:
|
|
1295
1295
|
${Et.synthesis.conflicts.map(Zt=>`- ${Zt}`).join(`
|
|
1296
|
-
`)}`:"";B.push({role:"assistant",content:Tt+ts+ct}),ze(B),Da(B)}return Et}He.isComplex&&process.stdout.isTTY&&console.log(`${y.dim}Hint: ~${He.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${y.reset}`)}catch{}let{setOnChange:c}=la(),u=null,d=0;c((Me,Le)=>{Me==="create"?(u&&u.stop(),u=new p1(Le.name,Le.tasks),u.setStats({tokens:d}),u.start()):Me==="update"&&u?u.updateTask(Le.id,Le.status):Me==="clear"&&u&&(u.stop(),u=null)});let f=await
|
|
1296
|
+
`)}`:"";B.push({role:"assistant",content:Tt+ts+ct}),ze(B),Da(B)}return Et}He.isComplex&&process.stdout.isTTY&&console.log(`${y.dim}Hint: ~${He.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${y.reset}`)}catch{}let{setOnChange:c}=la(),u=null,d=0;c((Me,Le)=>{Me==="create"?(u&&u.stop(),u=new p1(Le.name,Le.tasks),u.setStats({tokens:d}),u.start()):Me==="update"&&u?u.updateTask(Le.id,Le.status):Me==="clear"&&u&&(u.stop(),u=null)});let f=await td(),p=f;try{let{getBrainContext:Me}=xr(),Le=await Me(t);Le&&(p=f+`
|
|
1297
1297
|
`+Le+`
|
|
1298
1298
|
`)}catch(Me){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",Me.message)}let h=Z1(typeof t=="string"?t:"");if(h.length>0){let Me=h.map(Le=>`[Triggered: ${Le.name}]
|
|
1299
1299
|
${Le.instructions}`).join(`
|
|
1300
1300
|
`);p+=`
|
|
1301
1301
|
`+Me+`
|
|
1302
|
-
`}let g=[{role:"system",content:p},...B];g1(xn());let $=new Bo(
|
|
1302
|
+
`}let g=[{role:"system",content:p},...B];g1(xn());let $=new Bo(Mu());$.start();let w=B.length===1,k=w?FR().catch(()=>null):Promise.resolve(null),E=w?P1(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),S=St(),[{messages:x,compressed:C,compacted:H,tokensRemoved:q},ie,le]=await Promise.all([_1(g,S),k,E]),te=bn(g,S);if($.stop(),ie&&console.log(`${y.dim}${ie}${y.reset}`),H)console.log(`${y.dim} [context compacted \u2014 summary (~${q} tokens freed)]${y.reset}`);else if(C){let Me=te.limit>0?Math.round(q/te.limit*100):0;W(`${y.dim} [context compressed \u2014 ~${q} tokens freed (${Me}%)]${y.reset}`)}te.percentage>85&&W(`${y.yellow} \u26A0 Context ${Math.round(te.percentage)}% used (${Math.round(100-te.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${y.reset}`);let T=x;if(le&&w&&(T=[T[0],{role:"user",content:`[Server probe at task start]
|
|
1303
1303
|
${le}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...T.slice(1)]),w){let Me=L1(typeof t=="string"?t:"");Me&&(T=[T[0],{role:"user",content:Me.user},{role:"assistant",content:Me.assistant},...T.slice(1)])}if(bn(T,St()).percentage>=65){let{messages:Le,tokensRemoved:He}=Nn(T,St());He>0&&(T=Le,console.log(`${y.dim} [pre-flight compress \u2014 ${He} tokens freed, now ${Math.round(bn(T,St()).percentage)}% used]${y.reset}`))}let Te=0,G=0,z=0,fe=0,Ee=0,Ae=9,ve=0,be=(()=>{let Me=B.find(Le=>Le.role==="user");return typeof Me?.content=="string"?Me.content:""})(),v=/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(be),L=0;if(!ht){let Me=B.filter(He=>He.role==="user"||He.role==="tool").map(He=>typeof He.content=="string"?He.content:"").join(`
|
|
1304
|
-
`),Le=
|
|
1304
|
+
`),Le=Fu(Me);Le&&(ht=!0,Bt=Le.slice(0,120),W(`${y.yellow} \u26A1 Root cause in briefing: ${Bt} \u2014 fix phase active from start (read budget: 3)${y.reset}`))}!ht&&!an&&/\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(be)&&(an=!0,W(`${y.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${y.reset}`)),B.length<=1&&!n.skipPhaseRouting&&(Oe=A1(),Oe&&(Ho=C1(be)?.id||"coding",Ze="plan",Zn=Hu("plan",Ho),ec=0,Vr=0,hs=0,process.stdout.isTTY&&console.log(`${y.dim} \u21B3 Phase routing: plan(${Zn||"default"}) \u2192 implement \u2192 verify${y.reset}`),W(`${y.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${Zn||"default model"} (category: ${Ho})${y.reset}`)));let O=0,D=new Map,M=new Set,R=new Set,N=new Set,Z=0,ne=0,Q=Date.now(),ge=new y1(oR),ke=ei,pe=n.skillLoop?10:1,qe=3*pe,Pe=5*pe,$t=nd,Ue=5*pe,kt=8*pe,ws=sd,Zo=(Oe?6:4)*pe,gi=(Oe?10:7)*pe,es=Zr,yi=(Oe?5:3)*pe,Dn=(Oe?8:5)*pe,wc=od,uw=(Oe?4:3)*pe,dw=(Oe?6:4)*pe,fw=3*pe,pw=4*pe,ro=fs,hw=(Oe?3:2)*pe,mw=(Oe?5:3)*pe,io=(Oe?6:4)*pe,gw=25,bs=0,yw=6*pe,$w=10*pe,_s=0,Yd=5*pe,xs=0,ww=2*pe,bw=3,bc=0,Qo=10,_w=16,Gd=n.skillLoop?999:s.investigationCap,rt,En=n.maxIterations||(Oe?Vs(Ze):Gu),_c=0,Kd=3,xc=!1,$i=0;e:for(;;){for(xc=!1,rt=0;rt<En&&!Fa()?.aborted;rt++){{let _=St(),b=bn(T,_),oe=O===0?65:78;if(b.percentage>=oe){if(M.size>0||Oe&&Ze!=="plan"){let ce=S1(B,{filesModified:M,currentPhase:Oe?Ze:null});if(ce){let Y=T.findIndex(F=>F._progressSnapshot);Y!==-1&&T.splice(Y,1);let $e=T.findIndex(F=>F.role==="system");T.splice($e+1,0,ce)}}let{messages:P,tokensRemoved:j}=Nn(T,_,O===0);if(j>0&&(T=P,j>50&&console.log(`${y.dim} [auto-compressed \u2014 ~${j} tokens freed, now ${Math.round(bn(T,_).percentage)}%]${y.reset}`),an&&M.size>=3)){let ce=[...M].map($e=>$e.split("/").pop()).slice(0,10).join(", "),Y={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${M.size} files: ${ce}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};T.push(Y)}}}if(zt&&!ht&&zr<2){zr++;let _={role:"user",content:"[SYSTEM] SSH paused \u2014 you have made many consecutive SSH calls. Synthesize your findings so far: summarize what you learned and what the likely issue is. After your synthesis, SSH will be available again for targeted follow-up commands."};T.push(_),B.push(_),W(`${y.yellow} \u26A0 Pre-call SSH-blocked nudge #${zr} injected \u2014 model told to synthesize${y.reset}`)}zt||(zr=0);let Le=!0;O>0&&H1();let He=null;if(u&&u.isActive())u._paused&&u.resume();else if(!u){let _,b=Y1();if(b&&b.total>1){let oe=b.description.length>40?b.description.slice(0,37)+"\u2026":b.description;_=`Plan step ${b.current}/${b.total}: ${oe}`}else _=O>0?`${Mu()} (step ${O+1})`:Mu();He=new Bo(_),He.start()}let Et=!0,Tt="",ts=!1,ct=new G1,Zt,Sc=Date.now(),wi=!1,vc=new AbortController,zd=setInterval(()=>{let _=Date.now()-Sc;if(_>=ju)ct._clearCursorLine(),W(`${y.yellow} \u26A0 Stream stale for ${Math.round(_/1e3)}s \u2014 aborting and retrying${y.reset}`),vc.abort();else if(_>=m$&&!wi){wi=!0,ct._clearCursorLine();let b=Ja.fast?.[Uo()],oe=z>0?` (retry ${z+1}/${ja})`:"",P=Math.round((ju-_)/1e3);W(`${y.yellow} \u26A0 No tokens received for ${Math.round(_/1e3)}s \u2014 waiting...${oe}${y.reset}`),b&&b!==xn()?console.log(`${y.dim} \u{1F4A1} Will auto-switch to ${b} in ~${P}s if no tokens arrive${y.reset}`):console.log(`${y.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${P}s${y.reset}`)}},5e3),Qt="",jn=null;try{let _=E$(St()),b=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),oe=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),P;Jr()?P=_.filter(Y=>b$.has(Y.function.name)):Oe&&Ze==="plan"?P=_.filter(Y=>b.has(Y.function.name)):Oe&&Ze==="verify"?P=_.filter(Y=>oe.has(Y.function.name)):P=_;let j=Fa(),ce=new AbortController;j&&j.addEventListener("abort",()=>ce.abort(),{once:!0}),vc.signal.addEventListener("abort",()=>ce.abort(),{once:!0}),Zt=await r$(T,P,{signal:ce.signal,...Zn?{model:Zn}:{},onThinkingToken:()=>{Sc=Date.now(),wi=!1,Ln?.onThinkingToken&&Ln.onThinkingToken()},onToken:Y=>{if(Sc=Date.now(),wi=!1,Ln?.onToken){Ln.onToken(Y),Tt+=Y;return}if(Tt+=Y,!ts&&Tt.length>400&&Tt.length%250<Y.length+1){let $e=Yu(Tt,3);$e.truncated&&(ts=!0,ct._clearCursorLine?.(),W(`${y.yellow} \u26A0 LLM stream loop detected (${$e.repeatCount}\xD7 repeated) \u2014 suppressing display${y.reset}`))}ts||(Qt+=Y,process.stdout.isTTY?jn||(jn=setTimeout(()=>{Qt&&ct&&ct.push(Qt),Qt="",jn=null},50)):(ct.push(Qt),Qt=""),Et&&(u&&!u._paused?u.pause():He&&He.stop(),Le||(Le=!0),ct.startCursor(),Et=!1))}})}catch(_){if(clearInterval(zd),jn&&(clearTimeout(jn),jn=null),Qt&&ct&&(ct.push(Qt),Qt=""),u&&!u._paused&&u.pause(),He&&He.stop(),ct.stopCursor(),vc.signal.aborted&&!Fa()?.aborted){if(z++,z>ja){if(fe<1){fe++,Fo("Stale retries exhausted \u2014 last-resort force-compress...",y.yellow);let $e=St(),{messages:F,tokensRemoved:X}=Nn(T,$e);T=F,X>50&&W(`${y.dim} [force-compressed \u2014 ~${X} tokens freed]${y.reset}`),z=0,rt--;continue}u&&(u.stop(),u=null);let Y=await UR();if(Y.action==="quit"){c(null),Je(O,D,M,R,Q),ze(B);break}Y.action==="switch"&&(d$(`${Y.provider}:${Y.model}`),console.log(`${y.green} \u2713 Switched to ${Y.provider}:${Y.model}${y.reset}`)),z=0,rt--;continue}let j=z===1?3e3:5e3;if(z>=1&&ve<1){ve++,Fo(`Stale retry ${z}/${ja} \u2014 force-compressing before retry...`,y.yellow);let Y=St(),{messages:$e,tokensRemoved:F}=Nn(T,Y,!0);if(T=$e,F>0&&F>50&&W(`${y.dim} [force-compressed \u2014 ~${F} tokens freed]${y.reset}`),SR){let X=Ja.fast?.[Uo()];X&&X!==xn()&&(d$(`${Uo()}:${X}`),console.log(`${y.cyan} \u26A1 Auto-switched to ${X} to avoid further stale timeouts${y.reset}`),console.log(`${y.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${y.reset}`))}}else W(`${y.yellow} \u26A0 Stale retry ${z}/${ja} \u2014 retrying in ${j/1e3}s...${y.reset}`);let ce=new Bo(`Waiting ${j/1e3}s before retry...`);ce.start(),await new Promise(Y=>setTimeout(Y,j)),ce.stop(),rt--;continue}if(_.name==="AbortError"||_.name==="CanceledError"||_.message?.includes("canceled")||_.message?.includes("aborted")){u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q),ze(B);break}let b=_.message;if(_.code==="ECONNREFUSED"||_.message.includes("ECONNREFUSED"))b="Connection refused \u2014 please check your internet connection or API endpoint";else if(_.code==="ENOTFOUND"||_.message.includes("ENOTFOUND"))b="Network error \u2014 could not reach the API server. Please check your connection";else if(_.code==="ETIMEDOUT"||_.message.includes("timeout"))b="Request timed out \u2014 the API server took too long to respond. Please try again";else if(_.message.includes("401")||_.message.includes("Unauthorized"))b="Authentication failed \u2014 please check your API key in the .env file";else if(_.message.includes("403")||_.message.includes("Forbidden"))b="Access denied \u2014 your API key may not have permission for this model";else if(_.message.includes("404")){b=`Model not found (404): ${xn?xn():"unknown"} \u2014 check your .env MODEL setting or run /models to list available models`,console.log(`${y.red} \u2717 ${b}${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q),ze(B);break}else if(_.message.includes("400")){if(fe<3&&Ee<Ae){fe++,Ee++;let j=O===0&&fe===1,ce=j||fe===3||ve>0;if(j){fe=3;let X=_.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);Fo(`Bad request (400) \u2014 ${X||"system prompt too large"}, compressing...`,y.yellow)}else Fo(ce?`Bad request (400) \u2014 nuclear compression (attempt ${fe}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${fe}/3)`,y.yellow);let Y=St(),{messages:$e,tokensRemoved:F}=Nn(T,Y,ce);T=$e,F>50&&W(`${y.dim} [force-compressed \u2014 ~${F} tokens freed]${y.reset}`),rt--;continue}{let j=T.find(V=>V.role==="system"),ce=T.find(V=>V.role==="user"&&!String(V.content).startsWith("[SYSTEM")&&!String(V.content).startsWith("BLOCKED:")),Y=[j,ce].filter(Boolean),{getUsage:$e}=Ht(),F=Ht().estimateMessagesTokens(Y),X=Ht().estimateMessagesTokens(T);if(F<X){let V=[],se=B.filter(ae=>ae.role==="assistant"&&typeof ae.content=="string"&&ae.content.trim().length>30).slice(-5).map(ae=>ae.content.trim().slice(0,300).replace(/\n+/g," "));se.length>0&&V.push(`Key findings:
|
|
1305
1305
|
`+se.map(ae=>`- ${ae}`).join(`
|
|
1306
1306
|
`));let re=B.filter(ae=>ae.role==="tool"&&typeof ae.content=="string"&&!ae.content.startsWith("BLOCKED:")&&ae.content.trim().length>10).slice(-5).map(ae=>ae.content.trim().split(`
|
|
1307
1307
|
`).slice(0,8).join(`
|
|
1308
1308
|
`).slice(0,500));if(re.length>0&&V.push(`Tool results summary:
|
|
1309
1309
|
`+re.map(ae=>`- ${ae}`).join(`
|
|
1310
|
-
`)),M.size>0){let ae=[...M].map(Fe=>Fe.split("/").slice(-2).join("/")).join(", ");V.unshift(`Already modified: ${ae} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(R.size>0){let ae=[...R].map(Fe=>Fe.split("/").slice(-2).join("/")).join(", ");V.push(`Files already investigated: ${ae}`)}let he=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(he,JSON.stringify({filesWritten:[...M].map(ae=>ae.split("/").slice(-2).join("/")),filesRead:[...R].map(ae=>ae.split("/").slice(-2).join("/")),isCreationTask:an,wipeNumber:Kr+1,timestamp:Date.now()},null,2)),V.push(`Session checkpoint: ${he} \u2014 read it for exact file list`)}catch{}let xe=0;{let Fe=((typeof ce?.content=="string"?ce.content:Array.isArray(ce?.content)?ce.content.filter(ft=>ft.type==="text").map(ft=>ft.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(ft=>ft.trim()).filter(Boolean),Qe=[...M],It=Fe.filter(ft=>!Qe.some(
|
|
1310
|
+
`)),M.size>0){let ae=[...M].map(Fe=>Fe.split("/").slice(-2).join("/")).join(", ");V.unshift(`Already modified: ${ae} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(R.size>0){let ae=[...R].map(Fe=>Fe.split("/").slice(-2).join("/")).join(", ");V.push(`Files already investigated: ${ae}`)}let he=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(he,JSON.stringify({filesWritten:[...M].map(ae=>ae.split("/").slice(-2).join("/")),filesRead:[...R].map(ae=>ae.split("/").slice(-2).join("/")),isCreationTask:an,wipeNumber:Kr+1,timestamp:Date.now()},null,2)),V.push(`Session checkpoint: ${he} \u2014 read it for exact file list`)}catch{}let xe=0;{let Fe=((typeof ce?.content=="string"?ce.content:Array.isArray(ce?.content)?ce.content.filter(ft=>ft.type==="text").map(ft=>ft.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(ft=>ft.trim()).filter(Boolean),Qe=[...M],It=Fe.filter(ft=>!Qe.some(Tc=>Tc.endsWith(ft)||ft.endsWith(Tc.split("/").pop())));xe=It.length;let dt=[...B].reverse().find(ft=>ft.role==="tool"&&typeof ft.content=="string"&&!ft.content.startsWith("BLOCKED:")&&ft.content.length>5),en={completed:Qe.map(ft=>ft.split("/").slice(-2).join("/")),pending:It.length>0?It:Qe.length===0?["(task files not yet identified)"]:[],lastEdit:dt?dt.content.trim().slice(0,120):null};(en.completed.length>0||en.pending.length>0)&&V.unshift(`Work manifest:
|
|
1311
1311
|
${JSON.stringify(en,null,2)}`)}if(V.length>0){let ae={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
|
|
1312
1312
|
${V.join(`
|
|
1313
1313
|
`)}
|
|
1314
1314
|
Continue implementing the fixes based on these findings.`};Y.push(ae)}if(Kr>=3){let ae=M.size>0?`
|
|
1315
|
-
Files modified so far: ${[...M].map(Fe=>Fe.split("/").slice(-1)[0]).join(", ")}`:"";W(`${y.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${y.reset}`),console.log(`${y.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${ae?y.dim+ae:""}${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q,{suppressHint:!0}),ze(B);break}T=Y,Kr++,Zs=10+Math.min(xe*3,7),
|
|
1315
|
+
Files modified so far: ${[...M].map(Fe=>Fe.split("/").slice(-1)[0]).join(", ")}`:"";W(`${y.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${y.reset}`),console.log(`${y.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${ae?y.dim+ae:""}${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q,{suppressHint:!0}),ze(B);break}T=Y,Kr++,Zs=10+Math.min(xe*3,7),Vu=!0,Ya=M.size,Ga=!1,rn=0,L=0;for(let[ae,Fe]of fs){let Qe=Fe?.count??Fe??0;Bu(fs,ae,Qe>=2?Qe:1)}for(let[ae]of Vn)Pn(fs,ae)<2&&Vn.delete(ae);on.clear(),to.clear(),an&&_n>0&&(ln=!0,W(`${y.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${_n} edits already made)${y.reset}`));for(let[ae]of Zr)Bu(Zr,ae,Dn-1);if(Fo(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${X-F} tokens freed)`,y.yellow),Kr>=1){let ae=[...fs.entries()].filter(([,dt])=>dt>=io).map(([dt])=>dt.split("/").slice(-1)[0]),Fe=ae.length>0?`
|
|
1316
1316
|
|
|
1317
|
-
Files already at read cap \u2014 use grep_search instead: ${ae.join(", ")}`:"",It={role:"user",content:zt&&!ht?"[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.${Fe}`};B.push(It),T.push(It)}fe=0,rt--;continue}}b="Context too large to compress \u2014 use /clear to start fresh"}else _.message.includes("500")||_.message.includes("502")||_.message.includes("503")||_.message.includes("504")?b="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(_.message.includes("fetch failed")||_.message.includes("fetch"))&&(b="Network request failed \u2014 please check your internet connection");if(console.log(`${y.red} \u2717 ${b}${y.reset}`),_.message.includes("429")){if(Te++,Te>
|
|
1318
|
-
Use /undo to revert changes made during this session.${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q),ze(B);break}let j=Math.min(2e3*Math.pow(2,G-1),3e4),ce=new Bo(`API temporarily unavailable \u2014 retrying in ${Math.round(j/1e3)}s (${G}/${
|
|
1317
|
+
Files already at read cap \u2014 use grep_search instead: ${ae.join(", ")}`:"",It={role:"user",content:zt&&!ht?"[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.${Fe}`};B.push(It),T.push(It)}fe=0,rt--;continue}}b="Context too large to compress \u2014 use /clear to start fresh"}else _.message.includes("500")||_.message.includes("502")||_.message.includes("503")||_.message.includes("504")?b="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(_.message.includes("fetch failed")||_.message.includes("fetch"))&&(b="Network request failed \u2014 please check your internet connection");if(console.log(`${y.red} \u2717 ${b}${y.reset}`),_.message.includes("429")){if(Te++,Te>Iu){console.log(`${y.red} Rate limit: max retries (${Iu}) exceeded. Try again later or use /budget to check your limits.${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q),ze(B);break}let j=Math.min(1e4*Math.pow(2,Te-1),12e4),ce=new Bo(`Rate limit \u2014 waiting ${Math.round(j/1e3)}s (retry ${Te}/${Iu})`);ce.start(),await new Promise(Y=>setTimeout(Y,j)),ce.stop();continue}let oe=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return We().getActiveProviderName()==="ollama"}catch{return!1}})();if(_.message.includes("socket disconnected")||_.message.includes("TLS")||_.message.includes("ECONNRESET")||_.message.includes("ECONNABORTED")||_.message.includes("ETIMEDOUT")||oe&&(_.message.includes("500")||_.message.includes("502")||_.message.includes("503")||_.message.includes("504")||_.message.includes("401")||_.message.includes("Unauthorized"))||_.code==="ECONNRESET"||_.code==="ECONNABORTED"){if(G++,G>Du){console.log(`${y.red} Network error: max retries (${Du}) exceeded. Check your connection and try again.
|
|
1318
|
+
Use /undo to revert changes made during this session.${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q),ze(B);break}let j=Math.min(2e3*Math.pow(2,G-1),3e4),ce=new Bo(`API temporarily unavailable \u2014 retrying in ${Math.round(j/1e3)}s (${G}/${Du}). Your changes are safe.`);ce.start(),await new Promise(Y=>setTimeout(Y,j)),ce.stop(),rt--;continue}u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q),ze(B);break}if(clearInterval(zd),Te=0,G=0,Et&&(u&&!u._paused&&u.pause(),He&&He.stop()),jn&&(clearTimeout(jn),jn=null),Qt&&ct&&(ct.push(Qt),Qt=""),Tt&&ct.flush(),G=0,z=0,Zt&&Zt.usage){let _=Zt.usage.prompt_tokens||0,b=Zt.usage.completion_tokens||0;a$(Uo(),xn(),_,b),d+=_+b,u&&u.setStats({tokens:d})}else if(Zt&&!Zt.usage){let _=T.map(P=>typeof P.content=="string"?P.content:Array.isArray(P.content)?P.content.map(j=>typeof j=="string"?j:j.text||"").join(""):"").join(" "),b=l$(_),oe=l$(Zt.content||Tt||"");a$(Uo(),xn(),b,oe),d+=b+oe,u&&u.setStats({tokens:d})}let{content:Xd,tool_calls:qn}=Zt,bi=Yu(Xd||""),Vd=bi.truncated?bi.text:Xd;bi.truncated&&W(`${y.yellow} \u26A0 LLM output loop detected (${bi.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${y.reset}`);let _i=uR(Vd||""),Tn=_i.truncated?_i.text:Vd;_i.truncated&&W(`${y.yellow} \u26A0 LLM output loop detected (${_i.repeatCount}\xD7 repeated window) \u2014 response truncated${y.reset}`);let kc={role:"assistant",content:Tn||""};if(qn&&qn.length>0&&(kc.tool_calls=qn),B.push(kc),T.push(kc),!ht&&Tn&&qn&&qn.length>0){let _=Fu(Tn);if(_){ht=!0,Bt=_.slice(0,120),cn=0,ln=!1,Jn=0,W(`${y.yellow} \u26A1 Root cause in model analysis: ${Bt} \u2014 fix phase (read budget: 3)${y.reset}`);let b={role:"user",content:`[SYSTEM] Root cause identified: ${Bt}. Read only the file that needs fixing, then edit it. Do not read other files.`};B.push(b),T.push(b)}}if(!qn||qn.length===0){let _=(Tn||"").trim().length>0||Tt.trim().length>0,b=!1;if(zt&&_&&(qa>=2?W(`${y.yellow} \u26A0 SSH permanently blocked after ${qa} storm warnings \u2014 no further SSH calls allowed${y.reset}`):(zt=!1,rn=Qo-4,b=!0)),b&&_){let P=(Tn||"").trim();if(P.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(P.slice(-200))){let ce={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};T.push(ce),B.push(ce);continue}}if(!_&&O>0&&rt<Gu-1){let P={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};T.push(P),B.push(P);continue}let oe=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if(_&&rt<3&&oe.test((Tn||"").slice(0,600)))if(Vu&&Zs<=0||zt){W(`${y.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${y.reset}`);let j={role:"user",content:"[SYSTEM] Correct \u2014 remote access is currently limited. Summarize what you have found so far and tell the user exactly what specific information (logs, process list, error output) you need from the server to continue."};T.push(j),B.push(j);continue}else{W(`${y.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${y.reset}`);let j={role:"user",content:"[SYSTEM] You have full tool access. Use your tools to investigate and implement the fix directly \u2014 do not say you cannot use tools. If SSH is needed, use a single targeted command that captures the most relevant information rather than multiple sequential calls."};T.push(j),B.push(j);continue}if(n.skillLoop&&_&&O>3&&$i<5){let P=(Tn||Tt||"").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(P.slice(-600))){$i=($i||0)+1,W(`${y.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${$i}${y.reset}`);let ce={role:"user",content:"[SYSTEM] Do NOT stop. You are in an autonomous experiment loop. The user is away and expects you to keep running experiments indefinitely until they interrupt with Ctrl+C. Start the next experiment NOW: hypothesize a new change, checkpoint, edit, run, measure, keep or revert. Think harder \u2014 try a completely different optimization approach."};T.push(ce),B.push(ce);continue}}if(Va()&&!n.skillLoop&&M.size>0&&_&&O>=2){W(`${y.green} \u2713 Headless early exit: ${M.size} file(s) modified, text response received${y.reset}`),Je(O,D,M,R,Q),ze(B);break e}if(Oe&&Ze==="plan"&&hs>=2){W(`${y.cyan} \u21B3 Plan phase: ${hs} consecutive blocks \u2014 auto-advancing to implement${y.reset}`),hs=0;let P=Hr("implement","[auto-advance: task only requires direct action]");if(P){B.push(P),T.push(P),rt=0,En=Vs("implement");continue}}if(Oe&&_){let P=(Tn||Tt||"").trim();if(Ze==="plan"){let j=Hr("implement",P);if(j){B.push(j),T.push(j),rt=0,En=Vs("implement");continue}}else if(Ze==="implement"&&M.size>0){let j=B.find($e=>$e.role==="user"),ce=typeof j?.content=="string"?j.content:"",Y=Hr("verify",P,M,ce);if(Y){B.push(Y),T.push(Y),rt=0,En=Math.min(Vs("verify")+Math.max(0,(M.size-2)*2),20);continue}}else if(Ze==="verify"){let ce=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(P.slice(0,500));if(ce&&Vr<1){Vr++;let Y={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
|
|
1319
1319
|
${P.slice(0,400)}
|
|
1320
1320
|
|
|
1321
|
-
Fix the identified issues. This is the final attempt.`};Ze="implement",Zn=
|
|
1321
|
+
Fix the identified issues. This is the final attempt.`};Ze="implement",Zn=Hu("implement",Ho),B.push(Y),T.push(Y),rt=0,En=Vs("implement"),W(`${y.yellow} \u21B3 Verify \u2192 implement loop-back #${Vr} (issues found)${y.reset}`);continue}if(W(`${y.green} \u2713 Verification phase complete${ce?" (loop-back exhausted)":" (PASS)"}${y.reset}`),!ce){Je(O,D,M,R,Q),ze(B),Da(B);break e}}}if(Jr()&&_&&O===0)if(Ua++,Ua>2)W(`${y.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${y.reset}`);else{let P={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.).
|
|
1322
1322
|
|
|
1323
1323
|
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.`};B.push(P),T.push(P),W(`${y.yellow} \u26A0 Plan rejected (${Ua}/2): no files read \u2014 forcing investigation${y.reset}`);continue}if(Jr()&&_){let P=(Tn||Tt||"").trim();B1(P),vR(P);let j=U1(P);if(j.length>0){let ce=B.find(X=>X.role==="user"),Y=typeof ce?.content=="string"?ce.content.slice(0,120):"Task";W1(Y,j);let $e=j.length===1?"step":"steps",F=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:X,startExecution:V,setPlanMode:se}=wn();process.stdout.write(`
|
|
1324
1324
|
${y.cyan}${y.bold}Plan ready${y.reset} ${y.dim}(${j.length} ${$e})${y.reset} ${y.green}[A]${y.reset}${y.dim}pprove${y.reset} ${y.yellow}[E]${y.reset}${y.dim}dit${y.reset} ${y.red}[R]${y.reset}${y.dim}eject${y.reset} ${y.dim}[\u21B5 = approve]:${y.reset} `);let re=process.stdin.isRaw,he=await new Promise(xe=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",ae=>{try{process.stdin.setRawMode(re||!1)}catch{}let Fe=ae.toString().toLowerCase()[0]||"\r";xe(Fe)})});if(process.stdout.write(`
|
|
1325
|
-
`),he==="r")console.log(`${y.red}Plan rejected.${y.reset} Ask follow-up questions to refine.`);else if(he==="e")console.log(`${y.yellow}Type /plan edit to open in editor, or give feedback.${y.reset}`);else if(X()){V(),se(!1),
|
|
1325
|
+
`),he==="r")console.log(`${y.red}Plan rejected.${y.reset} Ask follow-up questions to refine.`);else if(he==="e")console.log(`${y.yellow}Type /plan edit to open in editor, or give feedback.${y.reset}`);else if(X()){V(),se(!1),zu(),console.log(`${y.green}${y.bold}Approved!${y.reset} Executing ${j.length} ${$e}...`);let xe=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1326
1326
|
|
|
1327
1327
|
Implement the following plan step by step. All tools are now available.
|
|
1328
1328
|
|
|
1329
1329
|
${P}`;B.push({role:"user",content:xe}),T.push({role:"user",content:xe}),F=!0}}else console.log(`
|
|
1330
1330
|
${y.cyan}${y.bold}Plan ready${y.reset} ${y.dim}(${j.length} ${$e} extracted).${y.reset} Type ${y.cyan}/plan approve${y.reset}${y.dim} to execute, or ${y.reset}${y.cyan}/plan edit${y.reset}${y.dim} to review.${y.reset}`);if(F){u&&(u.stop(),u=null),rt--;continue}}else{let ce=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:Y,startExecution:$e,setPlanMode:F}=wn();process.stdout.write(`
|
|
1331
1331
|
${y.cyan}${y.bold}Plan ready.${y.reset} ${y.green}[A]${y.reset}${y.dim}pprove${y.reset} ${y.red}[R]${y.reset}${y.dim}eject${y.reset} ${y.dim}[\u21B5 = approve]:${y.reset} `);let X=process.stdin.isRaw,V=await new Promise(se=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",re=>{try{process.stdin.setRawMode(X||!1)}catch{}se(re.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
|
|
1332
|
-
`),V==="r")console.log(`${y.red}Plan rejected.${y.reset} Ask follow-up questions to refine.`);else if(Y()){$e(),F(!1),
|
|
1332
|
+
`),V==="r")console.log(`${y.red}Plan rejected.${y.reset} Ask follow-up questions to refine.`);else if(Y()){$e(),F(!1),zu(),console.log(`${y.green}${y.bold}Approved!${y.reset} Executing...`);let re=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1333
1333
|
|
|
1334
1334
|
Implement the following plan step by step. All tools are now available.
|
|
1335
1335
|
|
|
1336
1336
|
${getPlanContent()||Zt.content}`;B.push({role:"user",content:re}),T.push({role:"user",content:re}),ce=!0}}else console.log(`
|
|
1337
|
-
${y.cyan}${y.bold}Plan ready.${y.reset} ${y.dim}Type ${y.reset}${y.cyan}/plan approve${y.reset}${y.dim} to execute, or ask follow-up questions to refine.${y.reset}`);if(ce){u&&(u.stop(),u=null),rt--;continue}}}if(u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q),an&&M.size>=3){let P=[...M].map(F=>F.split("/").pop()).slice(0,8).join(", "),j=[...M].some(F=>F.endsWith("package.json")),ce=[...M].some(F=>F.endsWith("requirements.txt")),Y=[...M].some(F=>F.endsWith("package-lock.json")||F.endsWith("yarn.lock")||F.endsWith("pnpm-lock.yaml")),$e=j&&!Y?"npm install not yet run":ce?"pip install not yet run":null;Xr=`[Previous session created ${M.size} files: ${P}`+($e?` \u2014 ${$e}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(an&&!
|
|
1338
|
-
${Y}`),B.push({role:"user",content:P},{role:"assistant",content:Y}))}catch{}ze(B),Da(B);return}O++,ec++,O>=1&&(Le=!1);for(let _ of qn){let b=_.function.name;D.set(b,(D.get(b)||0)+1)}if(O>=30&&!$$){$$=!0,W(`${y.yellow} \u26A0 Tool budget warning: ${O} tool calls used \u2014 nudging model to wrap up${y.reset}`);let _={role:"user",content:"[SYSTEM] \u26A0 You have used "+O+" 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."};B.push(_),T.push(_)}let Re=await Promise.all(qn.map(_=>kR(_)));{let _=bn(T,St()),b=_.percentage,oe=Re.some(Y=>Y.canExecute&&Y.fnName==="read_file"&&!Y.args?.line_end),P=Re.filter(Y=>Y.canExecute&&Y.fnName==="read_file"&&Y.args?.path&&Pn(ro,Y.args.path)>=1&&!Y.args?.line_start).map(Y=>Y.args.path.split("/").slice(-2).join("/")),j=P.length>0;if(b>=70&&oe&&$c<70||b>=85&&$c<85||j){$c=b;let Y=b>=85?"URGENT":"WARNING",$e;j?(Y="WARNING",$e=`Full-file read of ${P.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):oe?$e=`Unbounded read at ${Math.round(b)}% context \u2014 use line_start/line_end to avoid overflow.`:$e="Use targeted reads (line_start/line_end) to save space.";let F={role:"user",content:`[SYSTEM ${Y}] Context ${Math.round(b)}% used (${_.used}/${_.limit} tokens). ${$e}`};if(B.push(F),T.push(F),b>=85){let X=j?` (re-read of: ${P.join(", ")})`:"";W(`${y.yellow} \u26A0 Context ${Math.round(b)}% used \u2014 agent warned to use targeted reads${X}${y.reset}`)}}}let vc=new Map;for(let _ of Re){if(!_.canExecute||_.fnName!=="read_file")continue;let b=_.args?.path;if(!b)continue;let oe=Pn(ro,b),P=vc.get(b)||0,j=oe+P,ce=_.args?.line_start!=null,Y=on.get(b)||0,$e=Y>0,F=2;if(j>=io){let X=b.split("/").slice(-2).join("/"),V=(to.get(b)||0)+1;if(to.set(b,V),V===1)W(`${y.red} \u2716 Blocked: "${X}" read ${j}\xD7 \u2014 hard cap (${io}) reached${y.reset}`);else if(V===2){W(`${y.red} \u2716 Escalated block: "${X}" \u2014 model ignored BLOCKED, injecting system warning${y.reset}`);let se={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${b}") and tried again anyway. This file has reached its read cap (${io}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};B.push(se),T.push(se)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already read ${j}\xD7 (hard cap: ${io}). 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(j>=1&&ce)if($e&&Y<=F){let X=b.split("/").slice(-2).join("/");console.log(`${y.cyan} \u21A9 Targeted re-read: "${X}" (line_start=${_.args.line_start}) \u2014 edit recovery #${Y}${y.reset}`),on.set(b,Y-1)}else if($e&&Y>F){let X=b.split("/").slice(-2).join("/");W(`${y.red} \u2716 Edit recovery blocked: "${X}" \u2014 ${F} recovery reads already used. Use grep to find the exact line numbers, then retry.${y.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 edit recovery budget exhausted (${F} 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 X=_.args.line_start||1,V=_.args.line_end||X+350,se=Vn.get(b)||[],re=!1;for(let[he,xe]of se){let ae=Math.max(X,he),Fe=Math.min(V,xe);if(Fe>ae){let Qe=Fe-ae,It=V-X||1,dt=xe-he||1,en=Qe/dt>=.7&&Qe/It<.7,ft=V-X<=gw;if(Qe>=It||!ft&&(Qe/It>=.7||Qe/dt>=.7)){let Ec=b.split("/").slice(-2).join("/"),tf=`${b}:${X}-${V}`,co=(Za.get(tf)||0)+1;if(Za.set(tf,co),W(en?`${y.red} \u2716 Blocked superread: "${Ec}" lines ${X}-${V} subsumes already-read ${he}-${xe} \u2014 use line_start=${xe+1} to skip known content (block #${co})${y.reset}`:`${y.red} \u2716 Blocked duplicate read: "${Ec}" lines ${X}-${V} (\u226570% overlap with lines ${he}-${xe} already in context, block #${co})${y.reset}`),co>=2){W(`${y.red} \u2716 Escalated range-block: "${Ec}" lines ${X}-${V} \u2014 model ignored BLOCKED, injecting system warning${y.reset}`);let nf={role:"user",content:en?`[SYSTEM] Read blocked ${co}\xD7 for read_file("${b}", lines ${X}-${V}). Lines ${he}-${xe} were already read. Use line_start=${xe+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${co}\xD7 for read_file("${b}", lines ${X}-${V}). Lines ${he}-${xe} were already read and will NOT change. Use grep_search to find specific content instead.`};B.push(nf),T.push(nf)}_.canExecute=!1,_.errorResult={role:"tool",content:en?`BLOCKED: read_file("${b}", lines ${X}-${V}) re-reads lines ${he}-${xe} already in context. Use line_start=${xe+1} to read only the new content beyond line ${xe}.`:`BLOCKED: read_file("${b}", lines ${X}-${V}) is a duplicate \u2014 lines ${he}-${xe} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:_.callId},re=!0;break}}}if(!re){let he=se.length,xe=2;if(he>=3){let Fe=b.split("/").slice(-2).join("/");W(`${y.red} \u2716 Blocked file-scroll: "${Fe}" \u2014 ${he} sections already read. Use grep to find specific content.${y.reset}`);let Qe=Pn(es,b)>=Dn;_.canExecute=!1,_.errorResult={role:"tool",content:Qe?`BLOCKED: read_file("${b}") denied \u2014 you have already read ${he} 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("${b}") denied \u2014 you have already read ${he} 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 he>=xe&&(_._scrollWarn={sectionCount:he+1,path:b})}}else if(j>=1){let X=on.get(b)||0;if(X>0){let V=b.split("/").slice(-2).join("/");console.log(`${y.cyan} \u21A9 Full re-read: "${V}" \u2014 test-failure recovery (${X} remaining)${y.reset}`);let se=X-1;se<=0?on.delete(b):on.set(b,se)}else{let V=b.split("/").slice(-2).join("/"),se=(to.get(b)||0)+1;if(to.set(b,se),se===1)W(`${y.red} \u2716 Blocked unbounded re-read: "${V}" \u2014 already in context. Use line_start/line_end for specific sections.${y.reset}`);else if(se===2){W(`${y.red} \u2716 Escalated block: "${V}" \u2014 model ignored unbounded re-read block, injecting system warning${y.reset}`);let re={role:"user",content:`[SYSTEM] read_file("${b}") 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.`};B.push(re),T.push(re)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already in context (read ${j}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:_.callId}}}_.canExecute&&vc.set(b,(vc.get(b)||0)+1)}if(ds>=3)for(let _ of Re)_.canExecute&&(_.fnName!=="read_file"&&_.fnName!=="edit_file"||(W(`${y.red} \u2716 Blocked ${_.fnName} \u2014 ${ds} consecutive file-not-found errors, must search first${y.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${ds} 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 Re){if(!_.canExecute||_.fnName!=="bash")continue;let b=(_.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(b)&&!/npm|yarn|pnpm|make|git/.test(b)){W(`${y.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${y.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(b)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(b)&&(W(`${y.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${y.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 Re)_.canExecute&&(_.fnName!=="ssh_exec"&&_.fnName!=="bash"||/\bsed\s+-n\b/.test(_.args?.command||"")&&(W(`${y.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${y.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 Re){if(!_.canExecute||_.fnName!=="write_file")continue;let b=_.args?.path,oe=_.args?.content||"";if(b)try{let P=require("fs"),j=require("path").resolve(process.cwd(),b);if(P.existsSync(j)){let ce=P.statSync(j).size,Y=Buffer.byteLength(oe,"utf8"),$e=ce>0?Y/ce:1;if($e<.6&&ce>200){let F=b.split("/").slice(-2).join("/");console.log(`${y.red} \u2716 write_file shrink guard: "${F}" would shrink to ${Math.round($e*100)}% of original \u2014 likely context loss${y.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: write_file("${b}") denied \u2014 new content is only ${Math.round($e*100)}% of current file size (${ce} \u2192 ${Y} 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 Jd=new Map;for(let _ of Re){if(!_.canExecute||_.fnName!=="grep")continue;let b=_.args?.path;if(!b)continue;let oe=Jd.get(b)||0,P=Pn(es,b)+oe,j=Pn(ro,b)>=1,ce=j?Math.min(3,Dn):Dn;if(P>=ce){let Y=b.split("/").slice(-2).join("/");W(`${y.red} \u2716 Blocked grep: "${Y}" grepped ${P}\xD7 with different patterns \u2014 flood threshold exceeded${y.reset}`);let $e=Pn(ro,b),F=$e>=io;if(F){let X={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${b}". You have already read ${$e} sections and tried ${P} 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.`};B.push(X),T.push(X),W(`${y.red} \u2716 Deadlock detected: "${Y}" \u2014 both read and grep blocked, injecting deadlock-break${y.reset}`)}_.canExecute=!1,_.errorResult={role:"tool",content:F?`BLOCKED: grep("${b}") denied \u2014 ${P} 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.`:j?`BLOCKED: grep("${b}") denied \u2014 file was already read and ${P} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${b}") denied \u2014 ${P} patterns already tried. Work with the grep results already in your context.`,tool_call_id:_.callId}}_.canExecute&&Jd.set(b,oe+1)}let xw=5,Zd=new Map;for(let _ of Re){if(!_.canExecute||_.fnName!=="ssh_exec")continue;let oe=(_.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),P=Zd.get(oe)||0,j=Pn($t,oe)+P;j>=xw&&(W(`${y.yellow} \u26A0 Blocked ssh_exec: same command run ${j}\xD7 \u2014 result already in context${y.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${j} 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&&Zd.set(oe,P+1)}if(zt){let _=Re.filter(P=>P.canExecute&&P.fnName==="ssh_exec"),b=Re.some(P=>P.canExecute&&P.fnName!=="ssh_exec"),oe=v&&L<3;if(_.length>0&&!b&&oe&&Ha<1)zt=!1,Ha++,rn=Math.max(0,Qo-2),W(`${y.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Ha}/1)]${y.reset}`);else for(let P of _)P.canExecute=!1,P.errorResult={role:"tool",content:ht?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Qo}+ calls). Root cause is known (${Bt}). 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 (${Qo}+ 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:P.callId}}if(v&&L<3&&!zt){for(let _ of Re)if(_.canExecute&&["bash","read_file","find_files"].includes(_.fnName)){L++;{let b=St(),{messages:oe}=Nn(T,b);T=oe}W(`${y.yellow} \u26A0 Server-local guard: blocking local ${_.fnName} \u2014 use ssh_exec on 94.130.37.43${y.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(!Oe&&ln&&an&&_n>=1){let _=["read_file","grep","search_files","glob","list_directory","find_files"];for(let b of Re)b.canExecute&&_.includes(b.fnName)&&(W(`${y.red} \u2716 Creation hard-block: ${b.fnName} denied \u2014 cap fired, files already written${y.reset}`),b.canExecute=!1,b.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:b.callId})}if(Zs>=0){let _=Re.filter(b=>b.canExecute).length;if(_>0&&(Zs-=_,Zs<0))if(!Ga&&M.size>Ya){Ga=!0,Zs=5,W(`${y.green} \u2713 Post-wipe progress detected (${M.size-Ya} files modified) \u2014 granting 5 bonus tool calls${y.reset}`);let b={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};B.push(b),T.push(b)}else{W(`${y.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${y.reset}`);for(let oe of Re)oe.canExecute&&(oe.canExecute=!1,oe.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:oe.callId});let b={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."};B.push(b),T.push(b)}}let Sw=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 Re){if(!_.canExecute||Sw.has(_.fnName))continue;let b=JSON.stringify(_.args||{}),oe=`${_.fnName}|${b}`,P=Pn(Qa,oe);P>=2?(W(`${y.red} \u2716 Blocked duplicate: ${_.fnName}(${b.substring(0,80)}) \u2014 called ${P+1}\xD7 with identical args${y.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${_.fnName}() with these exact arguments has already been called ${P}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:_.callId}):P===1&&W(`${y.yellow} \u26A0 Duplicate tool call: ${_.fnName}(${b.substring(0,80)}) \u2014 2nd call with identical args${y.reset}`),Js(Qa,oe)}{let _=new Set;for(let b of Re){if(!b.canExecute||!["edit_file","patch_file"].includes(b.fnName))continue;let oe=b.args?.path;oe&&(N.has(oe)||_.has(oe)?(b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: "${oe}" 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:b.callId},W(`${y.yellow} \u26A0 Map-first gate: blocked re-edit of "${oe.split("/").slice(-1)[0]}" \u2014 re-read required${y.reset}`)):_.add(oe))}}let er=u?{skipSpinner:!0,skipSummaries:!0}:{},vw=Re.some(_=>_.fnName==="ask_user"),Qd=!er.skipSummaries&&!Le,xi=null,ao=null;Qd&&!vw?(Le=!0,er.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(ao=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write(Ia(Re,O,!1,"blink")),xi=!0):Ln||process.stdout.write(Ia(Re,O,!1)+`
|
|
1337
|
+
${y.cyan}${y.bold}Plan ready.${y.reset} ${y.dim}Type ${y.reset}${y.cyan}/plan approve${y.reset}${y.dim} to execute, or ask follow-up questions to refine.${y.reset}`);if(ce){u&&(u.stop(),u=null),rt--;continue}}}if(u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q),an&&M.size>=3){let P=[...M].map(F=>F.split("/").pop()).slice(0,8).join(", "),j=[...M].some(F=>F.endsWith("package.json")),ce=[...M].some(F=>F.endsWith("requirements.txt")),Y=[...M].some(F=>F.endsWith("package-lock.json")||F.endsWith("yarn.lock")||F.endsWith("pnpm-lock.yaml")),$e=j&&!Y?"npm install not yet run":ce?"pip install not yet run":null;Xr=`[Previous session created ${M.size} files: ${P}`+($e?` \u2014 ${$e}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(an&&!Ju&&O>0){let P=[...M].some(re=>re.endsWith("package.json")),j=[...M].some(re=>re.endsWith("requirements.txt")||re.endsWith("Pipfile")||re.endsWith("pyproject.toml")),ce=[...M].some(re=>re.endsWith("package-lock.json")||re.endsWith("yarn.lock")||re.endsWith("pnpm-lock.yaml")),Y=B.flatMap(re=>{let he=Array.isArray(re.tool_calls)?re.tool_calls:[],xe=Array.isArray(re.content)?re.content.filter(ae=>ae?.type==="tool_use"):[];return[...he,...xe]}).filter(re=>{let he=re.function?.name||re.name||"";return he==="bash"||he==="Bash"}).map(re=>{try{let he=re.function?.arguments??re.input??{};return(typeof he=="string"?JSON.parse(he):he)?.command||""}catch{return""}}),$e=Y.some(re=>/pip\s+install|python\s+-m\s+venv/.test(re)),F=Y.some(re=>/npm\s+install/.test(re)),V=[...M].some(re=>/\/App\.(js|ts|jsx|tsx)$/.test(re))&&!P&&!F;if(j&&!$e||P&&!ce&&!F||V){Ju=!0;let re=[];j&&!$e&&re.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),V?re.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):P&&!ce&&!F&&re.push("npm install");let he=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${re.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;W(`${y.dim} [post-creation] bootstrapping environment (${re.join(", ")})${y.reset}`),B.push({role:"user",content:he}),T.push({role:"user",content:he});continue}}if(O>0&&!n._isSummaryTurn&&O1(Tn))try{W(`${y.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${y.reset}`);let P=M.size>0?"Write a closing summary (3+ sentences): what files changed and why, what the result is, anything the user should know or do next.":"Write a closing diagnosis (3+ sentences): what you investigated, what you found, and what the user should do next or what the root cause is.",j=[...T,{role:"user",content:P}],Y=((await r$(j,[],{}))?.content||"").trim();Y&&(console.log(`
|
|
1338
|
+
${Y}`),B.push({role:"user",content:P},{role:"assistant",content:Y}))}catch{}ze(B),Da(B);return}O++,ec++,O>=1&&(Le=!1);for(let _ of qn){let b=_.function.name;D.set(b,(D.get(b)||0)+1)}if(O>=30&&!$$){$$=!0,W(`${y.yellow} \u26A0 Tool budget warning: ${O} tool calls used \u2014 nudging model to wrap up${y.reset}`);let _={role:"user",content:"[SYSTEM] \u26A0 You have used "+O+" 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."};B.push(_),T.push(_)}let Re=await Promise.all(qn.map(_=>kR(_)));{let _=bn(T,St()),b=_.percentage,oe=Re.some(Y=>Y.canExecute&&Y.fnName==="read_file"&&!Y.args?.line_end),P=Re.filter(Y=>Y.canExecute&&Y.fnName==="read_file"&&Y.args?.path&&Pn(ro,Y.args.path)>=1&&!Y.args?.line_start).map(Y=>Y.args.path.split("/").slice(-2).join("/")),j=P.length>0;if(b>=70&&oe&&bc<70||b>=85&&bc<85||j){bc=b;let Y=b>=85?"URGENT":"WARNING",$e;j?(Y="WARNING",$e=`Full-file read of ${P.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):oe?$e=`Unbounded read at ${Math.round(b)}% context \u2014 use line_start/line_end to avoid overflow.`:$e="Use targeted reads (line_start/line_end) to save space.";let F={role:"user",content:`[SYSTEM ${Y}] Context ${Math.round(b)}% used (${_.used}/${_.limit} tokens). ${$e}`};if(B.push(F),T.push(F),b>=85){let X=j?` (re-read of: ${P.join(", ")})`:"";W(`${y.yellow} \u26A0 Context ${Math.round(b)}% used \u2014 agent warned to use targeted reads${X}${y.reset}`)}}}let Ec=new Map;for(let _ of Re){if(!_.canExecute||_.fnName!=="read_file")continue;let b=_.args?.path;if(!b)continue;let oe=Pn(ro,b),P=Ec.get(b)||0,j=oe+P,ce=_.args?.line_start!=null,Y=on.get(b)||0,$e=Y>0,F=2;if(j>=io){let X=b.split("/").slice(-2).join("/"),V=(to.get(b)||0)+1;if(to.set(b,V),V===1)W(`${y.red} \u2716 Blocked: "${X}" read ${j}\xD7 \u2014 hard cap (${io}) reached${y.reset}`);else if(V===2){W(`${y.red} \u2716 Escalated block: "${X}" \u2014 model ignored BLOCKED, injecting system warning${y.reset}`);let se={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${b}") and tried again anyway. This file has reached its read cap (${io}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};B.push(se),T.push(se)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already read ${j}\xD7 (hard cap: ${io}). 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(j>=1&&ce)if($e&&Y<=F){let X=b.split("/").slice(-2).join("/");console.log(`${y.cyan} \u21A9 Targeted re-read: "${X}" (line_start=${_.args.line_start}) \u2014 edit recovery #${Y}${y.reset}`),on.set(b,Y-1)}else if($e&&Y>F){let X=b.split("/").slice(-2).join("/");W(`${y.red} \u2716 Edit recovery blocked: "${X}" \u2014 ${F} recovery reads already used. Use grep to find the exact line numbers, then retry.${y.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 edit recovery budget exhausted (${F} 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 X=_.args.line_start||1,V=_.args.line_end||X+350,se=Vn.get(b)||[],re=!1;for(let[he,xe]of se){let ae=Math.max(X,he),Fe=Math.min(V,xe);if(Fe>ae){let Qe=Fe-ae,It=V-X||1,dt=xe-he||1,en=Qe/dt>=.7&&Qe/It<.7,ft=V-X<=gw;if(Qe>=It||!ft&&(Qe/It>=.7||Qe/dt>=.7)){let Rc=b.split("/").slice(-2).join("/"),tf=`${b}:${X}-${V}`,co=(Za.get(tf)||0)+1;if(Za.set(tf,co),W(en?`${y.red} \u2716 Blocked superread: "${Rc}" lines ${X}-${V} subsumes already-read ${he}-${xe} \u2014 use line_start=${xe+1} to skip known content (block #${co})${y.reset}`:`${y.red} \u2716 Blocked duplicate read: "${Rc}" lines ${X}-${V} (\u226570% overlap with lines ${he}-${xe} already in context, block #${co})${y.reset}`),co>=2){W(`${y.red} \u2716 Escalated range-block: "${Rc}" lines ${X}-${V} \u2014 model ignored BLOCKED, injecting system warning${y.reset}`);let nf={role:"user",content:en?`[SYSTEM] Read blocked ${co}\xD7 for read_file("${b}", lines ${X}-${V}). Lines ${he}-${xe} were already read. Use line_start=${xe+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${co}\xD7 for read_file("${b}", lines ${X}-${V}). Lines ${he}-${xe} were already read and will NOT change. Use grep_search to find specific content instead.`};B.push(nf),T.push(nf)}_.canExecute=!1,_.errorResult={role:"tool",content:en?`BLOCKED: read_file("${b}", lines ${X}-${V}) re-reads lines ${he}-${xe} already in context. Use line_start=${xe+1} to read only the new content beyond line ${xe}.`:`BLOCKED: read_file("${b}", lines ${X}-${V}) is a duplicate \u2014 lines ${he}-${xe} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:_.callId},re=!0;break}}}if(!re){let he=se.length,xe=2;if(he>=3){let Fe=b.split("/").slice(-2).join("/");W(`${y.red} \u2716 Blocked file-scroll: "${Fe}" \u2014 ${he} sections already read. Use grep to find specific content.${y.reset}`);let Qe=Pn(es,b)>=Dn;_.canExecute=!1,_.errorResult={role:"tool",content:Qe?`BLOCKED: read_file("${b}") denied \u2014 you have already read ${he} 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("${b}") denied \u2014 you have already read ${he} 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 he>=xe&&(_._scrollWarn={sectionCount:he+1,path:b})}}else if(j>=1){let X=on.get(b)||0;if(X>0){let V=b.split("/").slice(-2).join("/");console.log(`${y.cyan} \u21A9 Full re-read: "${V}" \u2014 test-failure recovery (${X} remaining)${y.reset}`);let se=X-1;se<=0?on.delete(b):on.set(b,se)}else{let V=b.split("/").slice(-2).join("/"),se=(to.get(b)||0)+1;if(to.set(b,se),se===1)W(`${y.red} \u2716 Blocked unbounded re-read: "${V}" \u2014 already in context. Use line_start/line_end for specific sections.${y.reset}`);else if(se===2){W(`${y.red} \u2716 Escalated block: "${V}" \u2014 model ignored unbounded re-read block, injecting system warning${y.reset}`);let re={role:"user",content:`[SYSTEM] read_file("${b}") 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.`};B.push(re),T.push(re)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already in context (read ${j}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:_.callId}}}_.canExecute&&Ec.set(b,(Ec.get(b)||0)+1)}if(ds>=3)for(let _ of Re)_.canExecute&&(_.fnName!=="read_file"&&_.fnName!=="edit_file"||(W(`${y.red} \u2716 Blocked ${_.fnName} \u2014 ${ds} consecutive file-not-found errors, must search first${y.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${ds} 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 Re){if(!_.canExecute||_.fnName!=="bash")continue;let b=(_.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(b)&&!/npm|yarn|pnpm|make|git/.test(b)){W(`${y.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${y.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(b)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(b)&&(W(`${y.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${y.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 Re)_.canExecute&&(_.fnName!=="ssh_exec"&&_.fnName!=="bash"||/\bsed\s+-n\b/.test(_.args?.command||"")&&(W(`${y.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${y.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 Re){if(!_.canExecute||_.fnName!=="write_file")continue;let b=_.args?.path,oe=_.args?.content||"";if(b)try{let P=require("fs"),j=require("path").resolve(process.cwd(),b);if(P.existsSync(j)){let ce=P.statSync(j).size,Y=Buffer.byteLength(oe,"utf8"),$e=ce>0?Y/ce:1;if($e<.6&&ce>200){let F=b.split("/").slice(-2).join("/");console.log(`${y.red} \u2716 write_file shrink guard: "${F}" would shrink to ${Math.round($e*100)}% of original \u2014 likely context loss${y.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: write_file("${b}") denied \u2014 new content is only ${Math.round($e*100)}% of current file size (${ce} \u2192 ${Y} 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 Jd=new Map;for(let _ of Re){if(!_.canExecute||_.fnName!=="grep")continue;let b=_.args?.path;if(!b)continue;let oe=Jd.get(b)||0,P=Pn(es,b)+oe,j=Pn(ro,b)>=1,ce=j?Math.min(3,Dn):Dn;if(P>=ce){let Y=b.split("/").slice(-2).join("/");W(`${y.red} \u2716 Blocked grep: "${Y}" grepped ${P}\xD7 with different patterns \u2014 flood threshold exceeded${y.reset}`);let $e=Pn(ro,b),F=$e>=io;if(F){let X={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${b}". You have already read ${$e} sections and tried ${P} 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.`};B.push(X),T.push(X),W(`${y.red} \u2716 Deadlock detected: "${Y}" \u2014 both read and grep blocked, injecting deadlock-break${y.reset}`)}_.canExecute=!1,_.errorResult={role:"tool",content:F?`BLOCKED: grep("${b}") denied \u2014 ${P} 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.`:j?`BLOCKED: grep("${b}") denied \u2014 file was already read and ${P} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${b}") denied \u2014 ${P} patterns already tried. Work with the grep results already in your context.`,tool_call_id:_.callId}}_.canExecute&&Jd.set(b,oe+1)}let xw=5,Zd=new Map;for(let _ of Re){if(!_.canExecute||_.fnName!=="ssh_exec")continue;let oe=(_.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),P=Zd.get(oe)||0,j=Pn($t,oe)+P;j>=xw&&(W(`${y.yellow} \u26A0 Blocked ssh_exec: same command run ${j}\xD7 \u2014 result already in context${y.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${j} 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&&Zd.set(oe,P+1)}if(zt){let _=Re.filter(P=>P.canExecute&&P.fnName==="ssh_exec"),b=Re.some(P=>P.canExecute&&P.fnName!=="ssh_exec"),oe=v&&L<3;if(_.length>0&&!b&&oe&&Ha<1)zt=!1,Ha++,rn=Math.max(0,Qo-2),W(`${y.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Ha}/1)]${y.reset}`);else for(let P of _)P.canExecute=!1,P.errorResult={role:"tool",content:ht?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Qo}+ calls). Root cause is known (${Bt}). 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 (${Qo}+ 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:P.callId}}if(v&&L<3&&!zt){for(let _ of Re)if(_.canExecute&&["bash","read_file","find_files"].includes(_.fnName)){L++;{let b=St(),{messages:oe}=Nn(T,b);T=oe}W(`${y.yellow} \u26A0 Server-local guard: blocking local ${_.fnName} \u2014 use ssh_exec on 94.130.37.43${y.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(!Oe&&ln&&an&&_n>=1){let _=["read_file","grep","search_files","glob","list_directory","find_files"];for(let b of Re)b.canExecute&&_.includes(b.fnName)&&(W(`${y.red} \u2716 Creation hard-block: ${b.fnName} denied \u2014 cap fired, files already written${y.reset}`),b.canExecute=!1,b.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:b.callId})}if(Zs>=0){let _=Re.filter(b=>b.canExecute).length;if(_>0&&(Zs-=_,Zs<0))if(!Ga&&M.size>Ya){Ga=!0,Zs=5,W(`${y.green} \u2713 Post-wipe progress detected (${M.size-Ya} files modified) \u2014 granting 5 bonus tool calls${y.reset}`);let b={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};B.push(b),T.push(b)}else{W(`${y.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${y.reset}`);for(let oe of Re)oe.canExecute&&(oe.canExecute=!1,oe.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:oe.callId});let b={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."};B.push(b),T.push(b)}}let Sw=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 Re){if(!_.canExecute||Sw.has(_.fnName))continue;let b=JSON.stringify(_.args||{}),oe=`${_.fnName}|${b}`,P=Pn(Qa,oe);P>=2?(W(`${y.red} \u2716 Blocked duplicate: ${_.fnName}(${b.substring(0,80)}) \u2014 called ${P+1}\xD7 with identical args${y.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${_.fnName}() with these exact arguments has already been called ${P}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:_.callId}):P===1&&W(`${y.yellow} \u26A0 Duplicate tool call: ${_.fnName}(${b.substring(0,80)}) \u2014 2nd call with identical args${y.reset}`),Js(Qa,oe)}{let _=new Set;for(let b of Re){if(!b.canExecute||!["edit_file","patch_file"].includes(b.fnName))continue;let oe=b.args?.path;oe&&(N.has(oe)||_.has(oe)?(b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: "${oe}" 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:b.callId},W(`${y.yellow} \u26A0 Map-first gate: blocked re-edit of "${oe.split("/").slice(-1)[0]}" \u2014 re-read required${y.reset}`)):_.add(oe))}}let er=u?{skipSpinner:!0,skipSummaries:!0}:{},vw=Re.some(_=>_.fnName==="ask_user"),Qd=!er.skipSummaries&&!Le,xi=null,ao=null;Qd&&!vw?(Le=!0,er.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(ao=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write(Ia(Re,O,!1,"blink")),xi=!0):Ln||process.stdout.write(Ia(Re,O,!1)+`
|
|
1339
1339
|
`)):Qd&&(Le=!0,er.skipSpinner=!0),u&&u._paused&&u.resume();let Si=null;if(xi&&process.stdout.isTTY&&Re.some(b=>b.canExecute&&(b.fnName==="bash"||b.fnName==="ssh_exec"))){let b=Date.now();Si=setInterval(()=>{let oe=Math.round((Date.now()-b)/1e3);if(oe>=3){let P=`${Ia(Re,O,!1,"blink")} ${y.dim}[${oe}s]${y.reset}`;ao!==null?process.stdout.write(`\x1B[${ao};1H\x1B[2K${P}`):process.stdout.write(`\r\x1B[2K${P}`)}},1e3)}let{results:wt,summaries:kw}=await CR(Re,!0,{...er,skipSummaries:!0});if(Si&&(clearInterval(Si),Si=null),xi){xi=null;let _=Ia(Re,O,!1);ao!==null?process.stdout.write(`\x1B[${ao};1H\x1B[2K${_}
|
|
1340
1340
|
`):process.stdout.write(`\r\x1B[2K${_}
|
|
1341
1341
|
`),ao=null}if(!er.skipSummaries){let _=kw.filter((P,j)=>!(Re[j]&&Re[j].fnName==="ask_user"));for(let P of _)console.log(P);let b=Re.filter(P=>P&&P.fnName!=="ask_user").map(P=>P.fnName),oe=ge.record(0,b,R,M);oe&&rR(oe)}for(let _ of Re){if(_.canExecute||!_.errorResult)continue;let b=typeof _.errorResult.content=="string"?_.errorResult.content:"";if((b.startsWith("BLOCKED:")||b.startsWith("PLAN MODE:")||b.startsWith("PLAN PHASE:"))&&(_s++,_s>=Yd)){W(`${y.red} \u2716 Loop abort: ${_s} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q,{suppressHint:!0}),ze(B);return}}for(let _=0;_<Re.length;_++){let b=Re[_];if(!b.canExecute)continue;let oe=wt[_].content,P=oe.split(`
|
|
1342
|
-
`)[0],j=!P.startsWith("ERROR")&&!P.startsWith("CANCELLED")&&!P.startsWith("Command failed")&&!P.startsWith("EXIT");if(!j&&(b.fnName==="edit_file"||b.fnName==="patch_file")&&b.args?.path&&P.includes("old_text not found")){let F=on.get(b.args.path)||0;on.set(b.args.path,F+1)}if(!j&&b.fnName==="bash"&&ei.size>0){let F=(b.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(F))for(let[V]of ei)on.has(V)||(on.set(V,1),W(`${y.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${V.split("/").pop()}"${y.reset}`))}if(!j&&(b.fnName==="read_file"||b.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(P)){if(ds++,ds>=2){W(`${y.yellow} \u26A0 File-not-found streak: ${ds} consecutive misses \u2014 forcing search${y.reset}`);let F={role:"user",content:`[SYSTEM] ${ds} 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.`};B.push(F),T.push(F)}}else j&&(b.fnName==="read_file"||b.fnName==="edit_file"||b.fnName==="search_files"||b.fnName==="glob_files")&&(ds=0);if(j&&b.fnName==="write_file"&&b.args?.path){let F=b.args.path.split("/").pop(),X=b.args.path.includes("/tests/")||b.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(F)&&!X){W(`${y.yellow} \u26A0 Temp file: "${F}" \u2014 delete with bash rm when done to keep the workspace clean${y.reset}`);let se={role:"user",content:`[HINT] "${b.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${b.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};B.push(se),T.push(se)}}if(j&&["write_file","edit_file","patch_file"].includes(b.fnName)&&b.args&&b.args.path){on.delete(b.args.path),M.add(b.args.path);let F=Js(ke,b.args.path),X=b.args.path.split("/").slice(-2).join("/");if(F===qe){W(`${y.yellow} \u26A0 Loop warning: "${X}" edited ${F}\xD7 \u2014 possible edit loop${y.reset}`);let V={role:"user",content:`[SYSTEM WARNING] "${b.args.path}" edited ${F}\xD7. One more edit max, then move on.`};B.push(V),T.push(V)}else if(F>=Pe){W(`${y.red} \u2716 Loop abort: "${X}" edited ${F}\xD7 \u2014 aborting to prevent runaway loop${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q,{suppressHint:!0}),ze(B);return}}if(j&&b.canExecute&&Oe&&(hs=0),j&&b.canExecute&&!(Oe&&Ze==="plan")){let F=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(b.fnName)){cn=0,ln=!1,Jn=0,_n++;let ae=b.args?.path||b.args?.file_path;ae&&(
|
|
1342
|
+
`)[0],j=!P.startsWith("ERROR")&&!P.startsWith("CANCELLED")&&!P.startsWith("Command failed")&&!P.startsWith("EXIT");if(!j&&(b.fnName==="edit_file"||b.fnName==="patch_file")&&b.args?.path&&P.includes("old_text not found")){let F=on.get(b.args.path)||0;on.set(b.args.path,F+1)}if(!j&&b.fnName==="bash"&&ei.size>0){let F=(b.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(F))for(let[V]of ei)on.has(V)||(on.set(V,1),W(`${y.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${V.split("/").pop()}"${y.reset}`))}if(!j&&(b.fnName==="read_file"||b.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(P)){if(ds++,ds>=2){W(`${y.yellow} \u26A0 File-not-found streak: ${ds} consecutive misses \u2014 forcing search${y.reset}`);let F={role:"user",content:`[SYSTEM] ${ds} 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.`};B.push(F),T.push(F)}}else j&&(b.fnName==="read_file"||b.fnName==="edit_file"||b.fnName==="search_files"||b.fnName==="glob_files")&&(ds=0);if(j&&b.fnName==="write_file"&&b.args?.path){let F=b.args.path.split("/").pop(),X=b.args.path.includes("/tests/")||b.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(F)&&!X){W(`${y.yellow} \u26A0 Temp file: "${F}" \u2014 delete with bash rm when done to keep the workspace clean${y.reset}`);let se={role:"user",content:`[HINT] "${b.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${b.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};B.push(se),T.push(se)}}if(j&&["write_file","edit_file","patch_file"].includes(b.fnName)&&b.args&&b.args.path){on.delete(b.args.path),M.add(b.args.path);let F=Js(ke,b.args.path),X=b.args.path.split("/").slice(-2).join("/");if(F===qe){W(`${y.yellow} \u26A0 Loop warning: "${X}" edited ${F}\xD7 \u2014 possible edit loop${y.reset}`);let V={role:"user",content:`[SYSTEM WARNING] "${b.args.path}" edited ${F}\xD7. One more edit max, then move on.`};B.push(V),T.push(V)}else if(F>=Pe){W(`${y.red} \u2716 Loop abort: "${X}" edited ${F}\xD7 \u2014 aborting to prevent runaway loop${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q,{suppressHint:!0}),ze(B);return}}if(j&&b.canExecute&&Oe&&(hs=0),j&&b.canExecute&&!(Oe&&Ze==="plan")){let F=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(b.fnName)){cn=0,ln=!1,Jn=0,_n++;let ae=b.args?.path||b.args?.file_path;ae&&(Bu(fs,ae,1),Vn.delete(ae),N.add(ae))}else F.includes(b.fnName)&&(cn++,ln&&Jn++);let V=s.postEditCap,se=Oe&&Ze==="implement"?Math.min(Gd,6):Gd,re=ht?3:an?_n>0?2:4:_n>0?V:se,he=3,xe=!Oe&&ln&&(ht||an&&_n>=1||Jn>=he);if(Ur<2&&!ln&&cn>=3&&M.size===0){let ae=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,Fe=Date.now()-Q,Qe=Ur===0?.4:.65;if(ae>0&&Fe>ae*Qe){Ur++;let It=Math.round(Fe/6e4),dt=Math.round(Fe/ae*100);W(`${y.yellow} \u26A0 Time nudge #${Ur}: ${It}m elapsed (${dt}%), ${cn} reads, 0 edits${y.reset}`);let en={role:"user",content:Ur===1?`[SYSTEM] ${dt}% of available time used and no files edited yet. Start implementing now using edit_file or write_file \u2014 you have enough context.`:`[SYSTEM] ${dt}% 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.`};B.push(en),T.push(en)}}if(xe&&F.includes(b.fnName)){let ae=ht?`root cause already identified (${Bt})`:Jn>=he?`${cn} consecutive reads without an edit`:`${_n} file edit(s) already made`;W(`${y.red} \u2716 Blocked read-only tool: cap fired, ${ae}${y.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:ht?`BLOCKED: root cause already identified (${Bt}). Use edit_file to fix the issue \u2014 do not read more files.`:an?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":Jn>=he?`BLOCKED: You have read ${cn} 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: ${_n} 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:b.callId}}else if(cn>=re&&!ln){if(ln=!0,W(`${y.yellow} \u26A0 Investigation cap: ${cn} read-only calls without an edit \u2014 forcing implementation${y.reset}`),Oe&&Ze==="plan"){let Qe=[...T].reverse().find(en=>en.role==="assistant"),It=typeof Qe?.content=="string"?Qe.content:"",dt=Hr("implement",It);dt&&(B.push(dt),T.push(dt),rt=0,En=Vs("implement"))}let ae;ht?ae=`[SYSTEM] Root cause was already identified (${Bt}). Edit the file now \u2014 do not read more files.`:zt?ae="[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.":ae="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let Fe={role:"user",content:ae};B.push(Fe),T.push(Fe)}}if((b.fnName==="bash"||b.fnName==="ssh_exec")&&b.args&&b.args.command){let F=b.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),X=Js($t,F);if(X===Ue){W(`${y.yellow} \u26A0 Loop warning: same bash command run ${X}\xD7 \u2014 possible debug loop${y.reset}`);let V={role:"user",content:`[SYSTEM WARNING] Same bash command ${X}\xD7. Debug loop detected \u2014 try a different approach.`};B.push(V),T.push(V)}else if(X>=kt){W(`${y.red} \u2716 Loop abort: same bash command run ${X}\xD7 \u2014 aborting runaway debug loop${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q,{suppressHint:!0}),ze(B);return}}if(b.fnName==="ssh_exec"){rn++;{let V=(wt[_]?.content??"").split(`
|
|
1343
1343
|
`).map(se=>se.trim()).find(se=>se.length>0&&!se.startsWith("**")&&(se.startsWith("EXIT")||/^[\w./-]+:\s/.test(se)||se.startsWith("bash:")||se.startsWith("sh:")))??"";if(V){if(V===Ka?Qs++:(Ka=V,Qs=1),Qs===3&&!zt){W(`${y.yellow} \u26A0 SSH repeated-error: "${V.slice(0,60)}" returned ${Qs}\xD7 \u2014 nudging to change approach${y.reset}`);let se={role:"user",content:`[SYSTEM WARNING] The last ${Qs} SSH commands all failed with the same error: "${V}". 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).`};B.push(se),T.push(se)}}else Ka="",Qs=0}if(rn>=_w){W(`${y.red} \u2716 SSH storm abort: ${rn} consecutive ssh_exec calls \u2014 aborting${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q,{suppressHint:!0}),ze(B);return}else if(rn===Qo){{let V=St(),{messages:se}=Nn(T,V);T=se}zt=!0,qa++,W(`${y.yellow} \u26A0 SSH storm warning (#${qa}): ${rn} consecutive ssh_exec calls \u2014 blocking further SSH${y.reset}`);let X={role:"user",content:ht?`[SYSTEM WARNING] ${rn} consecutive SSH calls. Root cause identified (${Bt}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${rn} 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.`};B.push(X),T.push(X)}}else b.canExecute&&(rn=0);if(b.fnName==="bash"&&b.canExecute){let V=(wt[_]?.content??"").split(`
|
|
1344
|
-
`).map(se=>se.trim()).find(se=>se.length>0&&(se.startsWith("EXIT")||/^[\w./-]+:\s/.test(se)||se.startsWith("bash:")||se.startsWith("sh:")))??"";if(V){if(V===za?eo++:(za=V,eo=1),eo===3){W(`${y.yellow} \u26A0 Bash repeated-error: "${V.slice(0,60)}" returned ${eo}\xD7 \u2014 nudging to change approach${y.reset}`);let se={role:"user",content:`[SYSTEM WARNING] The last ${eo} bash commands all failed with the same error: "${V}". 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).`};B.push(se),T.push(se)}}else za="",eo=0}if(b.fnName==="bash"&&b.canExecute&&!
|
|
1345
|
-
...(truncated ${j-Y} chars \u2014 per-message budget)`},b-=j-Y)}}}for(let _ of wt)B.push(_),T.push(_);if(!ht)for(let _=0;_<wt.length;_++){if(!Re[_]||Re[_].fnName!=="ssh_exec")continue;let b=wt[_];if(!b||typeof b.content!="string")continue;let oe=
|
|
1346
|
-
${y.yellow}\u26A0 Max iterations reached.${y.reset}`),await w$(" Continue for 20 more turns?")){En=20;continue e}console.log(`${y.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${y.reset}`)}break e}}A$.exports={processInput:WR,clearConversation:LR,getConversationLength:DR,getConversationMessages:jR,setConversationMessages:qR,setAbortSignalGetter:fR,setMaxIterations:dR,invalidateSystemPromptCache:
|
|
1347
|
-
`),await t(a,i,d)}catch(u){if(n=u,!O$(u)||r>=e.length-1)throw u;if(i==="ollama"&&
|
|
1348
|
-
`),await t(a,i,f)}catch(p){if(n=p,!O$(p))throw p}}continue}}throw s>0&&s===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):n||new Error("No configured provider available")}async function iC(t,e,n={}){return un(),P$((s,o,r)=>s.stream(t,e,{model:r,signal:n.signal,...n}))}async function aC(t,e,n={}){if(un(),n.provider){let s=mt[n.provider];if(!s||!s.isConfigured())throw new Error(`Provider '${n.provider}' is not available`);let o={model:n.model||ot,...n};try{return await s.chat(t,e,o)}catch(r){if(typeof s.stream=="function")try{return await s.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return P$(async(s,o,r)=>{try{return await s.chat(t,e,{model:r,...n})}catch(i){if(typeof s.stream=="function")try{return await s.stream(t,e,{model:r,...n,onToken:()=>{}})}catch{}throw i}})}function cC(){un();let t=[];for(let[e,n]of Object.entries(mt))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function lC(){for(let t of Object.keys(mt))delete mt[t];Ut=null,ot=null,si=[]}L$.exports={registerProvider:Yo,getProvider:VR,getActiveProvider:
|
|
1344
|
+
`).map(se=>se.trim()).find(se=>se.length>0&&(se.startsWith("EXIT")||/^[\w./-]+:\s/.test(se)||se.startsWith("bash:")||se.startsWith("sh:")))??"";if(V){if(V===za?eo++:(za=V,eo=1),eo===3){W(`${y.yellow} \u26A0 Bash repeated-error: "${V.slice(0,60)}" returned ${eo}\xD7 \u2014 nudging to change approach${y.reset}`);let se={role:"user",content:`[SYSTEM WARNING] The last ${eo} bash commands all failed with the same error: "${V}". 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).`};B.push(se),T.push(se)}}else za="",eo=0}if(b.fnName==="bash"&&b.canExecute&&!Uu&&b.args?.command){let F=wt[_]?.content??"";if(/git\s+commit\b/.test(b.args.command)&&!F.startsWith("EXIT")&&!F.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(F)||F.includes("files changed")||F.includes("file changed")||F.includes("insertions(+)")||F.includes("create mode"))){Uu=!0,Wr=0,W(`${y.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${y.reset}`);let se={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."};B.push(se),T.push(se)}}if(Uu&&b.fnName==="bash"&&b.args?.command&&/git\s+(status|diff|log|show)\b/.test(b.args.command)&&(Wr++,Wr>2)){W(`${y.yellow} \u26A0 Post-commit git verification blocked (call ${Wr})${y.reset}`);let X={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(Wr-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};B.push(X),T.push(X)}if(j&&b.fnName==="grep"&&b.args&&b.args.pattern){let F=`${b.args.pattern}|${b.args.path||""}`,X=Js(ws,F);if(X===Zo){W(`${y.yellow} \u26A0 Loop warning: grep pattern "${b.args.pattern.slice(0,40)}" run ${X}\xD7 \u2014 possible search loop${y.reset}`);let V={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${X}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};B.push(V),T.push(V)}else if(X>=gi){W(`${y.red} \u2716 Loop abort: grep pattern run ${X}\xD7 \u2014 aborting runaway search loop${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q,{suppressHint:!0}),ze(B);return}if(b.args.path){let V=Js(es,b.args.path),se=Pn(ro,b.args.path)>=1;if(V===(se?1:yi)){let he=b.args.path.split("/").slice(-2).join("/");W(`${y.yellow} \u26A0 Loop warning: "${he}" grepped ${V}\xD7 with different patterns \u2014 context flood risk${y.reset}`);let xe={role:"user",content:se?`[SYSTEM NOTE] "${b.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] "${b.args.path}" grepped ${V}\xD7 \u2014 use the search results already in context instead of searching again.`};B.push(xe),T.push(xe)}}}if(j&&(b.fnName==="glob"||b.fnName==="glob_files"||b.fnName==="search_files")&&b.args){let F=b.args.pattern||b.args.query||b.args.path||"",X=Js(wc,F);if(X===uw){W(`${y.yellow} \u26A0 Loop warning: glob pattern "${F.slice(0,40)}" run ${X}\xD7 \u2014 possible search loop${y.reset}`);let se={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${X}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};B.push(se),T.push(se)}else if(X>=dw){W(`${y.red} \u2716 Loop abort: glob pattern run ${X}\xD7 \u2014 aborting runaway search loop${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q,{suppressHint:!0}),ze(B);return}let V=F.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(se=>se.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(se));for(let se of V){let re=se.toLowerCase();Qr.has(re)||Qr.set(re,new Set);let he=Qr.get(re);if(he.add(F),he.size===pw){W(`${y.red} \u2716 Glob core-term block: ${he.size} different patterns all searching for "${re}" \u2014 search loop${y.reset}`);let xe={role:"user",content:`[SYSTEM WARNING] You have searched for "${re}" using ${he.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.`};B.push(xe),T.push(xe)}else if(he.size===fw){W(`${y.yellow} \u26A0 Glob core-term warning: ${he.size} different patterns searching for "${re}"${y.reset}`);let xe={role:"user",content:`[SYSTEM WARNING] ${he.size} different glob patterns all target "${re}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};B.push(xe),T.push(xe)}}}let ce=(b.args?.command||b.args?.cmd||b.args?.script||"").toLowerCase(),Y=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(ce)||/\/(health|status|ping|ready|alive)\b/.test(ce);if(j&&(b.fnName==="bash"||b.fnName==="ssh_exec")&&Y&&oe.includes('"valid":true')){{let X=St();if(bn(T,X).percentage>=60){let{messages:se,tokensRemoved:re}=Nn(T,X);re>0&&(T=se,console.log(`${y.dim} [pre-stop-compress \u2014 ~${re} tokens freed before STOP injection, now ${Math.round(bn(T,X).percentage)}%]${y.reset}`))}}let F={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.'};B.push(F),T.push(F),console.log(`${y.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${y.reset}`)}if(oe.startsWith("BLOCKED:")){if(_s++,_s>=Yd){W(`${y.red} \u2716 Loop abort: ${_s} consecutive blocked calls \u2014 model not heeding BLOCKED messages${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q,{suppressHint:!0}),ze(B);return}}else _s=0;if(j)bs=0,xc=!0;else if(bs++,bs===yw){W(`${y.yellow} \u26A0 Loop warning: ${bs} consecutive tool errors \u2014 possible stuck loop${y.reset}`);let F={role:"user",content:`[SYSTEM WARNING] ${bs} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};B.push(F),T.push(F)}else if(bs>=$w){W(`${y.red} \u2716 Loop abort: ${bs} consecutive errors \u2014 aborting stuck loop${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q,{suppressHint:!0}),ze(B);return}if(j&&b.fnName==="read_file"&&b.args&&b.args.path){R.add(b.args.path),N.delete(b.args.path);let F=Js(ro,b.args.path);{let re=b.args.line_start!=null&&b.args.line_start||1,he=b.args.line_start!=null?b.args.line_end||re+350:350;Vn.has(b.args.path)||Vn.set(b.args.path,[]),Vn.get(b.args.path).push([re,he])}if(b._scrollWarn){let{sectionCount:re,path:he}=b._scrollWarn,xe={role:"user",content:`[SYSTEM WARNING] "${he}" \u2014 you have now read ${re} 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.`};B.push(xe),T.push(xe),W(`${y.yellow} \u26A0 Scroll warning: "${he.split("/").slice(-2).join("/")}" \u2014 ${re} sections read \u2014 use grep instead${y.reset}`)}let X=b.args.path.split("/").slice(-2).join("/"),V=!b.args?.line_start&&!b.args?.line_end,se=Oe&&Ze==="plan";if(!se&&V&&F===hw){{let he=St();if(bn(T,he).percentage>=60){let{messages:ae}=Nn(T,he);T=ae}}W(`${y.yellow} \u26A0 Loop warning: "${X}" read unbounded ${F}\xD7 \u2014 use line_start/line_end${y.reset}`);let re={role:"user",content:`[SYSTEM WARNING] "${b.args.path}" read ${F}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};B.push(re),T.push(re)}else if(!se&&V&&F>=mw){W(`${y.red} \u2716 Loop abort: "${X}" read unbounded ${F}\xD7 \u2014 aborting runaway read loop${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q,{suppressHint:!0}),ze(B);return}}if(b.fnName==="spawn_agents"){let F=(oe.match(/\bStatus: done\b/g)||[]).length;if((oe.match(/\bStatus: truncated\b/g)||[]).length>0&&F===0){if(xs++,xs===ww){W(`${y.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${xs}\xD7 in a row${y.reset}`);let V={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${xs}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};B.push(V),T.push(V)}else if(xs>=bw){console.log(`${y.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${xs}\xD7 \u2014 aborting stuck swarm${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q,{suppressHint:!0}),ze(B);return}}else F>0&&(xs=0)}}{let b=wt.reduce((oe,P)=>oe+(typeof P.content=="string"?P.content.length:0),0);if(b>2e5){let oe=wt.map((P,j)=>({i:j,len:typeof P.content=="string"?P.content.length:0})).sort((P,j)=>j.len-P.len);for(let{i:P,len:j}of oe){if(b<=2e5)break;let ce=b-2e5,Y=Math.max(j-ce,500);Y<j&&typeof wt[P].content=="string"&&(wt[P]={...wt[P],content:wt[P].content.substring(0,Y)+`
|
|
1345
|
+
...(truncated ${j-Y} chars \u2014 per-message budget)`},b-=j-Y)}}}for(let _ of wt)B.push(_),T.push(_);if(!ht)for(let _=0;_<wt.length;_++){if(!Re[_]||Re[_].fnName!=="ssh_exec")continue;let b=wt[_];if(!b||typeof b.content!="string")continue;let oe=Fu(b.content);if(oe){ht=!0,Bt=oe.slice(0,120),cn=0,ln=!1,Jn=0,W(`${y.yellow} \u26A1 Root cause detected: ${Bt} \u2014 fix phase (read budget: 3)${y.reset}`);let P={role:"user",content:`[SYSTEM] Root cause identified: ${Bt}. Read only the file that needs fixing, then edit it. Do not read other files.`};B.push(P),T.push(P);break}}for(let _=0;_<wt.length;_++){let b=Re[_];if(!b)continue;let oe=typeof wt[_]?.content=="string"?wt[_].content:"";if(b.fnName==="create_task"){let P=oe.match(/Task #(\d+) created/),j=typeof b.args?.subject=="string"?b.args.subject:"";P&&j&&ti.set(P[1],j)}else if((b.fnName==="write_file"||b.fnName==="edit_file")&&!oe.startsWith("BLOCKED:")&&oe.trim().length>0){let j=(typeof b.args?.path=="string"?b.args.path:typeof b.args?.file_path=="string"?b.args.file_path:"").split("/").pop().toLowerCase(),ce=j.split(/[._\-/]/).filter(Y=>Y.length>2);for(let[Y,$e]of ti){if(ni.has(Y))continue;let F=$e.toLowerCase().split(/\W+/).filter(V=>V.length>3);ce.filter(V=>F.some(se=>se.includes(V)||V.includes(se))).length>=1&&(ni.add(Y),W(`${y.green} \u2714 Auto-matched task #${Y} to ${j}: ${$e.slice(0,60)}${y.reset}`))}}}{let _=St();if(bn(T,_).percentage>=78){let{messages:oe,tokensRemoved:P}=Nn(T,_);P>0&&(T=oe,console.log(`${y.dim} [auto-compressed \u2014 ~${P} tokens freed, now ${Math.round(bn(T,_).percentage)}%]${y.reset}`))}}if(Va()&&!n.skillLoop&&(Re.some(b=>b&&["write_file","edit_file","patch_file"].includes(b.fnName))?Z=0:(Z===0&&(ne=M.size),Z++),Z>=8&&O>=4&&M.size===ne)){W(`${y.green} \u2713 Stagnation exit: ${Z} read-only iterations, no new file changes${y.reset}`),u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q),ze(B);break e}let ef=OR();if(ef){let _={role:"user",content:`[User note mid-run]: ${ef}`};B.push(_),T.push(_),console.log(`${y.cyan} \u270E Context added${y.reset}`)}}if(rt>=En){if(u&&(u.stop(),u=null),c(null),Je(O,D,M,R,Q),ze(B),Da(B),Oe&&Ze==="plan"){let Et=[...B].reverse().find(ct=>ct.role==="assistant"),Tt=typeof Et?.content=="string"?Et.content:"",ts=Hr("implement",Tt);if(ts){B.push(ts),T=[{role:"system",content:await td()},...B],En=Vs("implement"),W(`${y.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${y.reset}`);continue e}}else if(Oe&&Ze==="verify"){W(`${y.yellow} \u26A0 Verify budget exhausted \u2014 completing session${y.reset}`);break e}let{getActiveProviderName:Me}=We();if(Me()==="ollama"&&_c<Kd){if(M.size===0&&!xc){console.log(`${y.yellow} \u26A0 Max iterations reached with no progress. Stopping.${y.reset}`);break e}_c++,En=20,console.log(`${y.dim} \u2500\u2500 auto-extending (+20 turns, ext ${_c}/${Kd}) \u2500\u2500${y.reset}`);continue e}if(console.log(`
|
|
1346
|
+
${y.yellow}\u26A0 Max iterations reached.${y.reset}`),await w$(" Continue for 20 more turns?")){En=20;continue e}console.log(`${y.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${y.reset}`)}break e}}A$.exports={processInput:WR,clearConversation:LR,getConversationLength:DR,getConversationMessages:jR,setConversationMessages:qR,setAbortSignalGetter:fR,setMaxIterations:dR,invalidateSystemPromptCache:zu,clearToolFilterCache:bR,getCachedFilteredTools:E$,buildSystemPrompt:td,splitSystemPrompt:PR,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:ed,getProjectContextHash:T$,buildUserContent:v$,_detectImageURLs:_$,_downloadImageURL:x$,_grabClipboardImage:S$,detectFrustration:k$,detectAndTruncateLoop:Yu,injectMidRunNote:AR,resetSessionTracking:C$}});var We=K((dN,L$)=>{var{OllamaProvider:HR}=Pf(),{OpenAIProvider:YR}=jf(),{AnthropicProvider:GR}=Uf(),{GeminiProvider:KR}=Gf(),{LocalProvider:zR}=Xf(),{checkBudget:XR}=wo(),ad={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"}},rd=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),M$={};for(let[t,e]of Object.entries(ad))for(let n of Object.values(e))M$[n]=t;function id(t,e){let n=M$[t];return n&&ad[n][e]||t}var mt={},Ut=null,ot=null,si=[];function un(){if(Object.keys(mt).length>0)return;Yo("ollama",new HR),Yo("openai",new YR),Yo("anthropic",new GR),Yo("gemini",new KR),Yo("local",new zR);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;mt[t]?(Ut=t,ot=e||mt[t].defaultModel):(Ut="ollama",ot="kimi-k2.5");let n=process.env.FALLBACK_CHAIN;n&&(si=n.split(",").map(s=>s.trim()).filter(Boolean))}function Yo(t,e){mt[t]=e}function VR(t){return un(),mt[t]||null}function cd(){return un(),mt[Ut]||null}function JR(){return un(),Ut}function ZR(){return un(),ot}function QR(){un();let t=cd();if(!t)return{id:ot,name:ot,provider:Ut};let e=t.getModel(ot);return e?{...e,provider:Ut}:{id:ot,name:ot,provider:Ut}}function N$(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(mt[n]||["ollama","openai","anthropic","gemini","local"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function eC(t){un();let{provider:e,model:n}=N$(t);if(e){let o=mt[e];return o&&(o.getModel(n)||e==="local"||e==="ollama")?(Ut=e,ot=n,nc(),!0):!1}let s=cd();if(s&&s.getModel(n))return ot=n,nc(),!0;for(let[o,r]of Object.entries(mt))if(r.getModel(n))return Ut=o,ot=n,nc(),!0;return!1}function nc(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Se();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Ht();t()}catch{}}function tC(){un();let t=new Set;for(let e of Object.values(mt))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function nC(){return un(),Object.entries(mt).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===Ut&&n.id===ot}))}))}function sC(){un();let t=[];for(let[e,n]of Object.entries(mt)){let s=n.isConfigured();for(let o of Object.values(n.getModels()))t.push({spec:`${e}:${o.id}`,name:o.name,provider:e,configured:s})}return t}function oC(t){si=Array.isArray(t)?t:[]}function rC(){return[...si]}function O$(t){let e=t.message||"",n=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ECONNRESET"||n==="EHOSTUNREACH"||n==="ENETUNREACH"||n==="EPIPE"||n==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function P$(t){let e=[Ut,...si.filter(r=>r!==Ut)],n,s=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],a=mt[i];if(!a||!a.isConfigured())continue;o++;let c=XR(i);if(!c.allowed){s++,n=new Error(`Budget limit reached for ${i}: $${c.spent.toFixed(2)} / $${c.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?id(ot,i):ot;return u&&d!==ot&&process.stderr.write(` [fallback: ${i}:${d}]
|
|
1347
|
+
`),await t(a,i,d)}catch(u){if(n=u,!O$(u)||r>=e.length-1)throw u;if(i==="ollama"&&rd.length>0){let d=isFallback?id(ot,i):ot;for(let f of rd)if(f!==d)try{return process.stderr.write(` [ollama fallback: ${f}]
|
|
1348
|
+
`),await t(a,i,f)}catch(p){if(n=p,!O$(p))throw p}}continue}}throw s>0&&s===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):n||new Error("No configured provider available")}async function iC(t,e,n={}){return un(),P$((s,o,r)=>s.stream(t,e,{model:r,signal:n.signal,...n}))}async function aC(t,e,n={}){if(un(),n.provider){let s=mt[n.provider];if(!s||!s.isConfigured())throw new Error(`Provider '${n.provider}' is not available`);let o={model:n.model||ot,...n};try{return await s.chat(t,e,o)}catch(r){if(typeof s.stream=="function")try{return await s.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return P$(async(s,o,r)=>{try{return await s.chat(t,e,{model:r,...n})}catch(i){if(typeof s.stream=="function")try{return await s.stream(t,e,{model:r,...n,onToken:()=>{}})}catch{}throw i}})}function cC(){un();let t=[];for(let[e,n]of Object.entries(mt))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function lC(){for(let t of Object.keys(mt))delete mt[t];Ut=null,ot=null,si=[]}L$.exports={registerProvider:Yo,getProvider:VR,getActiveProvider:cd,getActiveProviderName:JR,getActiveModelId:ZR,getActiveModel:QR,setActiveModel:eC,getModelNames:tC,parseModelSpec:N$,listProviders:nC,listAllModels:sC,callStream:iC,callChat:aC,getConfiguredProviders:cC,setFallbackChain:oC,getFallbackChain:rC,resolveModelForProvider:id,MODEL_EQUIVALENTS:ad,OLLAMA_FALLBACK_MODELS:rd,_reset:lC}});var ld=K((fN,I$)=>{"use strict";var In=require("fs"),sc=require("path"),uC=require("readline"),{T:Go}=Rt(),Ce=Go.reset,oi=Go.bold,vt=Go.dim,oc=Go.yellow,ai=Go.cyan,ri=Go.green;function dC(t){return(e,n="")=>new Promise(s=>{let o=n?` ${vt}[${n}]${Ce}`:"";t.question(` ${ai}${e}${o}${Ce}: `,r=>s(r.trim()||n))})}function ii(t,e){return new Promise(n=>{e&&e.pause(),process.stdout.write(` ${ai}${t}${Ce}: `);let s=process.stdin,o=s.isRaw,r="";s.setRawMode(!0),s.resume(),s.setEncoding("utf8");let i=a=>{a==="\r"||a===`
|
|
1349
1349
|
`?(s.setRawMode(o||!1),s.removeListener("data",i),process.stdout.write(`
|
|
1350
1350
|
`),e&&e.resume(),n(r)):a===""?(process.stdout.write(`
|
|
1351
1351
|
`),process.exit(0)):a==="\x7F"?r.length>0&&(r=r.slice(0,-1),process.stdout.write("\b \b")):(r+=a,process.stdout.write("*"))};s.on("data",i)})}async function fC({rl:t=null,force:e=!1}={}){if(!e){let p=In.existsSync(sc.join(process.cwd(),".env"))||In.existsSync(sc.join(__dirname,"..",".env")),m=process.env.ANTHROPIC_API_KEY||process.env.OPENAI_API_KEY||process.env.GEMINI_API_KEY||process.env.OPENROUTER_API_KEY,h=process.env.DEFAULT_PROVIDER||process.env.DEFAULT_MODEL;if(p||m||h)return}let n=!t,s=t||uC.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),o=dC(s),r=!e;console.log(),console.log(r?`${oc}${oi} \u2726 Welcome to nex-code! No configuration found.${Ce}`:`${ai}${oi} \u2726 nex-code \u2014 Provider & API Key Setup${Ce}`),console.log(`${vt} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${Ce}`),r&&console.log(` Let's set you up in 60 seconds.
|
|
@@ -1371,20 +1371,20 @@ ${oc} No key entered \u2014 cancelled.${Ce}
|
|
|
1371
1371
|
${ri} \u2713 Saved to ${u}${Ce}`),a.some(h=>h.includes("API_KEY"))&&console.log(`${vt} (key stored locally \u2014 never committed)${Ce}`)}if(process.env.DEFAULT_PROVIDER)try{let{setActiveModel:p}=We(),m=process.env.DEFAULT_MODEL?`${process.env.DEFAULT_PROVIDER}:${process.env.DEFAULT_MODEL}`:process.env.DEFAULT_PROVIDER;p(m),console.log(`${ri} \u2713 Switched to ${m} for this session${Ce}`)}catch{}console.log(`
|
|
1372
1372
|
${ri} \u2713 Setup complete!${Ce}`),console.log(`
|
|
1373
1373
|
${ai}\u{1F4A1} Tip: Run ${oi}/benchmark${Ce} ${ai}to automatically find and use the best models for your tasks.${Ce}
|
|
1374
|
-
`)}I$.exports={runSetupWizard:fC}});var
|
|
1374
|
+
`)}I$.exports={runSetupWizard:fC}});var pd=K((pN,W$)=>{"use strict";var Sn=require("fs"),ci=require("path"),{atomicWrite:q$}=Bn(),pC=20,hC=3,F$=3,mC=14400*1e3;function li(){return ci.join(process.cwd(),".nex","dream-logs")}function ud(){return ci.join(li(),"_meta.json")}function gC(){let t=li();return Sn.existsSync(t)||Sn.mkdirSync(t,{recursive:!0}),t}function B$(t){if(!Array.isArray(t)||t.length===0)return null;let e={},n={},s={},o={},r=0,i=0,a=0,c=0;for(let u of t){if(u.role==="user"&&a++,u.role==="assistant"&&c++,u.role==="assistant"&&Array.isArray(u.content)){for(let d of u.content)if(d&&d.type==="tool_use"){let f=d.name||"unknown";e[f]=(e[f]||0)+1,r++;let p=d.input||{},m=p.path||p.file_path||p.filePath||"";m&&((f==="read_file"||f==="glob"||f==="grep"||f==="search_files")&&(s[m]=(s[m]||0)+1),(f==="write_file"||f==="edit_file"||f==="patch_file")&&(o[m]=(o[m]||0)+1))}}if(u.role==="assistant"&&Array.isArray(u.tool_calls))for(let d of u.tool_calls){let f=d.function?.name||d.name||"unknown";e[f]=(e[f]||0)+1,r++}if(u.role==="tool"){let d=typeof u.content=="string"?u.content:"";if(d.includes("Error")||d.includes("error")||d.includes("FAILED")||d.includes("failed")||d.includes("not found")||d.includes("permission denied")){let f=u.name||"unknown";n[f]=(n[f]||0)+1,i++}}}return r<hC?null:{timestamp:new Date().toISOString(),userMessages:a,assistantMessages:c,totalToolCalls:r,totalErrors:i,toolCalls:e,toolErrors:n,filesAccessed:D$(s,10),filesModified:D$(o,10)}}function yC(t){let e=B$(t);if(!e)return null;let n=gC(),s=`dream-${Date.now()}.json`,o=ci.join(n,s);try{return q$(o,JSON.stringify(e,null,2)),bC(n),o}catch{return null}}function $C(){let t=ud();if(!Sn.existsSync(t))return!0;try{let o=JSON.parse(Sn.readFileSync(t,"utf-8")),r=new Date(o.lastConsolidation||0).getTime();if(Date.now()-r<mC)return!1}catch{return!0}let e=dd(),n=fd();return e.filter(o=>!n.processed?.includes(o)).length>=F$}function wC(){let t=dd(),e=fd(),n=t.filter(h=>!e.processed?.includes(h));if(n.length<F$)return{insights:[],memoriesWritten:0};let s=[];for(let h of n)try{let g=JSON.parse(Sn.readFileSync(ci.join(li(),h),"utf-8"));s.push(g)}catch{}if(s.length===0)return{insights:[],memoriesWritten:0};let o=[],r=0,i={},a={},c={};for(let h of s){for(let[g,$]of Object.entries(h.toolCalls||{}))i[g]=(i[g]||0)+$;for(let[g,$]of Object.entries(h.toolErrors||{}))a[g]=(a[g]||0)+$;for(let[g,$]of Object.entries(h.filesAccessed||{}))c[g]=(c[g]||0)+$}let u=[];for(let[h,g]of Object.entries(a)){let $=i[h]||g,w=g/$;w>.3&&g>=3&&u.push({tool:h,errors:g,calls:$,rate:Math.round(w*100)})}if(u.length>0){let h=u.sort((w,k)=>k.rate-w.rate).map(w=>`- ${w.tool}: ${w.rate}% error rate (${w.errors}/${w.calls} calls)`).join(`
|
|
1375
1375
|
`),g=`High-error tools detected across ${s.length} sessions:
|
|
1376
1376
|
${h}`;o.push(g),j$("dream-error-prone-tools","Tools with high error rates across recent sessions",g)&&r++}let d=s.length,f={};for(let h of s){let g=new Set;for(let $ of Object.keys(h.filesAccessed||{}))g.has($)||(f[$]=(f[$]||0)+1,g.add($))}let p=Object.entries(f).filter(([h,g])=>g>d*.5&&(c[h]||0)>5).map(([h,g])=>({file:h,sessions:g,reads:c[h]||0})).sort((h,g)=>g.sessions-h.sessions).slice(0,10);if(p.length>0){let h=p.map(w=>`- ${w.file}: accessed in ${w.sessions}/${d} sessions (${w.reads} total reads)`).join(`
|
|
1377
1377
|
`),g=`Frequently accessed files across ${d} sessions:
|
|
1378
|
-
${h}`;o.push(g),j$("dream-hot-files","Files accessed frequently across multiple sessions",g)&&r++}let m=s.map(h=>h.userMessages===0?null:h.totalToolCalls/h.userMessages).filter(Boolean);if(m.length>=3){let h=m.reduce(($,w)=>$+w,0)/m.length,g=s.reduce(($,w)=>$+(w.totalErrors||0),0)/s.length;if(h>15){let $=`High tool-call density: avg ${h.toFixed(1)} tool calls per user message across ${s.length} sessions. Consider more targeted investigation.`;o.push($)}if(g>5){let $=`High error rate: avg ${g.toFixed(1)} errors per session across ${s.length} sessions.`;o.push($)}}return U$({lastConsolidation:new Date().toISOString(),processed:[...e.processed||[],...n],totalConsolidations:(e.totalConsolidations||0)+1}),{insights:o,memoriesWritten:r}}function D$(t,e=10){return Object.fromEntries(Object.entries(t).sort(([,n],[,s])=>s-n).slice(0,e))}function
|
|
1378
|
+
${h}`;o.push(g),j$("dream-hot-files","Files accessed frequently across multiple sessions",g)&&r++}let m=s.map(h=>h.userMessages===0?null:h.totalToolCalls/h.userMessages).filter(Boolean);if(m.length>=3){let h=m.reduce(($,w)=>$+w,0)/m.length,g=s.reduce(($,w)=>$+(w.totalErrors||0),0)/s.length;if(h>15){let $=`High tool-call density: avg ${h.toFixed(1)} tool calls per user message across ${s.length} sessions. Consider more targeted investigation.`;o.push($)}if(g>5){let $=`High error rate: avg ${g.toFixed(1)} errors per session across ${s.length} sessions.`;o.push($)}}return U$({lastConsolidation:new Date().toISOString(),processed:[...e.processed||[],...n],totalConsolidations:(e.totalConsolidations||0)+1}),{insights:o,memoriesWritten:r}}function D$(t,e=10){return Object.fromEntries(Object.entries(t).sort(([,n],[,s])=>s-n).slice(0,e))}function dd(){let t=li();if(!Sn.existsSync(t))return[];try{return Sn.readdirSync(t).filter(e=>e.startsWith("dream-")&&e.endsWith(".json")).sort()}catch{return[]}}function bC(t){try{let e=Sn.readdirSync(t).filter(n=>n.startsWith("dream-")&&n.endsWith(".json")).sort();for(;e.length>pC;){let n=e.shift();Sn.unlinkSync(ci.join(t,n))}}catch{}}function fd(){let t=ud();if(!Sn.existsSync(t))return{};try{return JSON.parse(Sn.readFileSync(t,"utf-8"))}catch{return{}}}function U$(t){try{q$(ud(),JSON.stringify(t,null,2))}catch{}}function j$(t,e,n){try{let{saveMemory:s}=mn();return s("feedback",t,n,e).ok}catch{return!1}}W$.exports={extractSessionStats:B$,writeDreamLog:yC,shouldConsolidate:$C,consolidate:wC,_getDreamDir:li,_listDreamLogs:dd,_readMeta:fd,_writeMeta:U$}});var K$=K((hN,G$)=>{"use strict";var rc=require("fs"),{T:vn,isDark:_C}=Rt(),Xt="\x1B[0m",xC=!_C,SC=process.env.FOOTER_DEBUG==="1"||process.env.FOOTER_DEBUG==="2",vC=process.env.FOOTER_DEBUG==="2",Ko=null;function ms(...t){SC&&(Ko||(Ko=rc.openSync("/tmp/footer-debug.log","w",384)),rc.writeSync(Ko,t.join(" ")+`
|
|
1379
1379
|
`))}function H$(t,e){if(!vC||typeof e!="string")return;Ko||(Ko=rc.openSync("/tmp/footer-debug.log","w",384));let n=e.replace(/\x1b\[([^a-zA-Z]*)([a-zA-Z])/g,(s,o,r)=>`<ESC[${o}${r}>`).replace(/\x1b([^[])/g,(s,o)=>`<ESC${o}>`).replace(/\r/g,"<CR>").replace(/\n/g,`<LF>
|
|
1380
1380
|
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,s=>`<${s.charCodeAt(0).toString(16).padStart(2,"0")}>`);rc.writeSync(Ko,`${t}: ${n}
|
|
1381
|
-
`)}function Y$(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var
|
|
1381
|
+
`)}function Y$(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var hd=class{constructor(){this._active=!1,this._rl=null,this._origWrite=null,this._origPrompt=null,this._origSetPr=null,this._origRefreshLine=null,this._origLog=null,this._origError=null,this._origStderrWrite=null,this._drawing=!1,this._offResize=null,this._cursorOnInputRow=!1,this._inRefreshLine=!1,this._lastOutputRow=1,this._prevTermRows=0,this._prevTermCols=0,this._consistencyTimer=null,this._dirty=!1,this._statusModel="",this._statusBranch="",this._statusProject="",this._statusMode=""}setStatusInfo({model:e,branch:n,project:s,mode:o}={}){e!==void 0&&(this._statusModel=e),n!==void 0&&(this._statusBranch=n),s!==void 0&&(this._statusProject=s),o!==void 0&&(this._statusMode=o),this._active&&this.drawFooter()}get _rows(){return process.stdout.rows||24}get _cols(){return process.stdout.columns||80}get _scrollEnd(){return this._rows-2}get _rowStatus(){return this._rows-1}get _rowInput(){return this._rows}_goto(e,n=1){return`\x1B[${e};${n}H`}_statusLine(){let e=this._cols,n=this._statusModel,s=this._statusBranch,o=this._statusProject,r=this._statusMode;if(!n)return vn.footer_sep+"\u2500".repeat(e)+Xt;let i=` ${vn.footer_divider}\xB7${Xt} `,a=[];n&&a.push(`${vn.footer_model}${n}${Xt}`),s&&a.push(`${vn.footer_branch}${s}${Xt}`),o&&a.push(`${vn.footer_project}${o}${Xt}`);let c=a.join(i),u=[n,s,o].filter(Boolean).join(" \xB7 ").length,d="\u2500 ";if(r){let m=r.length,h=Math.max(0,e-d.length-u-1-1-m-3),g="\u2500".repeat(h);return`${vn.footer_sep}${d}${Xt}${c}${vn.footer_sep} ${g} ${Xt}${vn.footer_mode}${r}${Xt}${vn.footer_sep} \u2500\u2500${Xt}`}let f=Math.max(0,e-d.length-u-2),p="\u2500".repeat(f);return`${vn.footer_sep}${d}${Xt}${c}${vn.footer_sep} ${p}${Xt}`}drawFooter(e){!this._origWrite||this._drawing||(this._drawing=!0,this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K"+this._statusLine(e)+"\x1B8"),this._drawing=!1)}_setScrollRegion(){if(xC)return;let e=Math.max(1,this._scrollEnd);this._origWrite(`\x1B[1;${e}r`)}_clearScrollRegion(){this._origWrite&&this._origWrite("\x1B[r")}_eraseStatus(){this._origWrite&&this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K\x1B8")}rawWrite(e){return H$("RAW",e),this._origWrite?this._origWrite(e):process.stdout.write(e)}_relayout(e){if(!this._origWrite)return;let n=this._origWrite,s=this._rows,o=this._cols,r=Math.max(1,s-2);ms("RELAYOUT:",e,"rows="+s,"cols="+o,"scrollEnd="+r,"cursorOnInput="+this._cursorOnInputRow),this._prevTermRows=s,this._prevTermCols=o;let i=Math.min(this._lastOutputRow+1,r+1),a="";for(let c=i;c<=s;c++)a+=this._goto(c)+"\x1B[2K";n(a),this._setScrollRegion(),this._lastOutputRow=Math.min(this._lastOutputRow,r),this.drawFooter(),this._cursorOnInputRow&&this._rl&&this._rl.prompt(!0),this._dirty=!1}activate(e){if(!process.stdout.isTTY)return;this._rl=e,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._prevTermRows=this._rows,this._prevTermCols=this._cols,this._origWrite("\x1B[r"),this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let n=this,s=process.stdout.write.bind(process.stdout);this._origWrite=s,process.stdout.write=function(h,...g){if(H$("PATCH",h),!n._active||typeof h!="string")return s(h,...g);if(n._inRefreshLine){let S=h.replace(/\n/g,"");return S?s(S,...g):!0}if(n._cursorOnInputRow){if(h.length<=4&&!h.includes(`
|
|
1382
1382
|
`)&&!h.includes("\r"))return ms("STDOUT: input-row intercept:",JSON.stringify(h)),n._origRefreshLine&&n._doRefreshLine(),!0;ms("STDOUT: non-echo on input row, anchoring to workspace, data="+JSON.stringify(h).slice(0,100)),n._cursorOnInputRow=!1,s(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd)))}let $=n._cols||80,w=0,k=h.split(`
|
|
1383
1383
|
`);for(let S=0;S<k.length;S++){let x=Y$(k[S]);x>0&&(w+=Math.floor((x-1)/$))}let E=k.length-1;return E+w>0&&(n._lastOutputRow=Math.min(n._lastOutputRow+E+w,n._scrollEnd)),s(h,...g)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(h,...g){if(!n._active)return n._origStderrWrite(h,...g);if(typeof h=="string"&&h.includes("\r")){let w=Math.min(n._lastOutputRow+1,n._scrollEnd);if(n._cursorOnInputRow){n._origWrite("\x1B7"),n._origWrite(n._goto(w));let k=n._origStderrWrite(h,...g);return n._origWrite("\x1B8"),k}n._origWrite(n._goto(w))}let $=n._origStderrWrite(h,...g);return typeof h=="string"&&h.includes(`
|
|
1384
|
-
`)&&!/\x1b\[\d+A/.test(h)&&n._cursorOnInputRow&&(n.drawFooter(),n._origWrite(n._goto(n._rowInput)+"\x1B[2K")),$},this._origLog=console.log,this._origError=console.error;function o(...h){if(!n._active){n._origLog(...h);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origLog(...h),n.drawFooter(),s(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}function r(...h){if(!n._active){n._origError(...h);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origError(...h),n.drawFooter(),s(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}console.log=o,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(h){n._origSetPr(h),n._active&&n.drawFooter(h)},this._origPrompt=e.prompt.bind(e),e.prompt=function(h){if(!n._active)return n._origPrompt(h);ms("PROMPT: goto rowInput="+n._rowInput),e.prevRows=0,s(n._goto(n._rowInput)+Xt+"\x1B[2K"),n._cursorOnInputRow=!0,n._origPrompt(h)};let i=e.question.bind(e);e.question=function(h,g){if(!n._active)return i(h,g);s(n._goto(n._rowInput)+"\x1B[2K"),e.prevRows=0,n._cursorOnInputRow=!0,i(h,$=>{s(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!1,n.drawFooter(),g($)})};let a=Object.getPrototypeOf(e),c=Object.getOwnPropertySymbols(a).find(h=>h.toString()==="Symbol(_refreshLine)"),u=c?a[c].bind(e):e._refreshLine?e._refreshLine.bind(e):null;if(this._origRefreshLine=u,this._doRefreshLine=function(){if(!n._active||!u)return;if(n._rows!==n._prevTermRows||n._cols!==n._prevTermCols){n._dirty=!0;return}e.prevRows=0,s(n._goto(n._rowInput)+Xt+"\x1B[2K");let h=n._cols,g=e._prompt||"",$=Y$(g),w=h-$-1;n._inRefreshLine=!0;try{if(e.line.length<=w){ms("REFRESH: short line, len="+e.line.length),u();return}ms("REFRESH: long line, len="+e.line.length+", max="+w);let k=e.line,E=e.cursor,S=Math.max(1,w-1),x=Math.max(0,E-S),C=(x>0?"\xAB":"")+k.slice(x,x+S+(x>0?0:1));e.line=C,e.cursor=C.length,u(),e.line=k,e.cursor=E}finally{n._inRefreshLine=!1}},u){let h=this._doRefreshLine;c&&Object.defineProperty(e,c,{value:h,writable:!0,configurable:!0}),e._refreshLine=h}e.on("line",()=>{n._active&&(ms("LINE: leaving input row"),n._cursorOnInputRow=!1,s(n._goto(n._rowInput)+"\x1B[2K"),s(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n.drawFooter())});let d=null,f=null,p=()=>{d=null,n._relayout("resize"),f&&clearTimeout(f),f=setTimeout(()=>{f=null,n._relayout("resize-cleanup")},300)},m=()=>{n._dirty=!0,d&&clearTimeout(d),d=setTimeout(p,80)};process.stdout.on("resize",m),this._offResize=()=>{process.stdout.off("resize",m),d&&(clearTimeout(d),d=null),f&&(clearTimeout(f),f=null)},this._consistencyTimer=setInterval(()=>{if(!n._active)return;let h=n._rows,g=n._cols;(n._dirty||h!==n._prevTermRows||g!==n._prevTermCols)&&(ms("CONSISTENCY: dirty="+n._dirty+" rows="+h+"/"+n._prevTermRows+" cols="+g+"/"+n._prevTermCols),n._relayout("consistency"))},800)}deactivate(){if(this._active){if(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._consistencyTimer&&(clearInterval(this._consistencyTimer),this._consistencyTimer=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine)){let e=Object.getOwnPropertySymbols(Object.getPrototypeOf(this._rl)).find(n=>n.toString()==="Symbol(_refreshLine)");e&&delete this._rl[e],delete this._rl._refreshLine,this._origRefreshLine=null}this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null}}};G$.exports={StickyFooter:
|
|
1384
|
+
`)&&!/\x1b\[\d+A/.test(h)&&n._cursorOnInputRow&&(n.drawFooter(),n._origWrite(n._goto(n._rowInput)+"\x1B[2K")),$},this._origLog=console.log,this._origError=console.error;function o(...h){if(!n._active){n._origLog(...h);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origLog(...h),n.drawFooter(),s(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}function r(...h){if(!n._active){n._origError(...h);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origError(...h),n.drawFooter(),s(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}console.log=o,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(h){n._origSetPr(h),n._active&&n.drawFooter(h)},this._origPrompt=e.prompt.bind(e),e.prompt=function(h){if(!n._active)return n._origPrompt(h);ms("PROMPT: goto rowInput="+n._rowInput),e.prevRows=0,s(n._goto(n._rowInput)+Xt+"\x1B[2K"),n._cursorOnInputRow=!0,n._origPrompt(h)};let i=e.question.bind(e);e.question=function(h,g){if(!n._active)return i(h,g);s(n._goto(n._rowInput)+"\x1B[2K"),e.prevRows=0,n._cursorOnInputRow=!0,i(h,$=>{s(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!1,n.drawFooter(),g($)})};let a=Object.getPrototypeOf(e),c=Object.getOwnPropertySymbols(a).find(h=>h.toString()==="Symbol(_refreshLine)"),u=c?a[c].bind(e):e._refreshLine?e._refreshLine.bind(e):null;if(this._origRefreshLine=u,this._doRefreshLine=function(){if(!n._active||!u)return;if(n._rows!==n._prevTermRows||n._cols!==n._prevTermCols){n._dirty=!0;return}e.prevRows=0,s(n._goto(n._rowInput)+Xt+"\x1B[2K");let h=n._cols,g=e._prompt||"",$=Y$(g),w=h-$-1;n._inRefreshLine=!0;try{if(e.line.length<=w){ms("REFRESH: short line, len="+e.line.length),u();return}ms("REFRESH: long line, len="+e.line.length+", max="+w);let k=e.line,E=e.cursor,S=Math.max(1,w-1),x=Math.max(0,E-S),C=(x>0?"\xAB":"")+k.slice(x,x+S+(x>0?0:1));e.line=C,e.cursor=C.length,u(),e.line=k,e.cursor=E}finally{n._inRefreshLine=!1}},u){let h=this._doRefreshLine;c&&Object.defineProperty(e,c,{value:h,writable:!0,configurable:!0}),e._refreshLine=h}e.on("line",()=>{n._active&&(ms("LINE: leaving input row"),n._cursorOnInputRow=!1,s(n._goto(n._rowInput)+"\x1B[2K"),s(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n.drawFooter())});let d=null,f=null,p=()=>{d=null,n._relayout("resize"),f&&clearTimeout(f),f=setTimeout(()=>{f=null,n._relayout("resize-cleanup")},300)},m=()=>{n._dirty=!0,d&&clearTimeout(d),d=setTimeout(p,80)};process.stdout.on("resize",m),this._offResize=()=>{process.stdout.off("resize",m),d&&(clearTimeout(d),d=null),f&&(clearTimeout(f),f=null)},this._consistencyTimer=setInterval(()=>{if(!n._active)return;let h=n._rows,g=n._cols;(n._dirty||h!==n._prevTermRows||g!==n._prevTermCols)&&(ms("CONSISTENCY: dirty="+n._dirty+" rows="+h+"/"+n._prevTermRows+" cols="+g+"/"+n._prevTermCols),n._relayout("consistency"))},800)}deactivate(){if(this._active){if(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._consistencyTimer&&(clearInterval(this._consistencyTimer),this._consistencyTimer=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine)){let e=Object.getOwnPropertySymbols(Object.getPrototypeOf(this._rl)).find(n=>n.toString()==="Symbol(_refreshLine)");e&&delete this._rl[e],delete this._rl._refreshLine,this._origRefreshLine=null}this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null}}};G$.exports={StickyFooter:hd}});var V$=K((mN,X$)=>{var{C:Xe}=Ye(),{listProviders:kC,getActiveProviderName:EC,getActiveModelId:TC,setActiveModel:RC}=We();function z$(t,e,n={}){let{title:s="Select",hint:o="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=n;return new Promise(r=>{let i=e.map((w,k)=>w.isHeader?-1:k).filter(w=>w>=0);if(i.length===0){r(null);return}let a=e.findIndex(w=>w.isCurrent),c=a>=0?i.indexOf(a):0;c<0&&(c=0);let u=process.stdout.rows?Math.max(process.stdout.rows-6,5):20,d=0;function f(){let w=i[c];return w<d?d=w:w>=d+u&&(d=w-u+1),{start:d,end:Math.min(e.length,d+u)}}let p=0;function m(){if(p>0){process.stdout.write(`\x1B[${p}A`);for(let x=0;x<p;x++)process.stdout.write(`\x1B[2K
|
|
1385
1385
|
`);process.stdout.write(`\x1B[${p}A`)}let w=[];w.push(` ${Xe.bold}${Xe.cyan}${s}${Xe.reset}`),w.push(` ${Xe.dim}${o}${Xe.reset}`),w.push("");let{start:k,end:E}=f();k>0&&w.push(` ${Xe.dim}\u2191 more${Xe.reset}`);for(let x=k;x<E;x++){let C=e[x];if(C.isHeader){w.push(` ${Xe.bold}${Xe.dim}${C.label}${Xe.reset}`);continue}let H=i[c]===x,q=H?`${Xe.cyan}> `:" ",ie=C.isCurrent?` ${Xe.yellow}<current>${Xe.reset}`:"";H?w.push(`${q}${Xe.bold}${C.label}${Xe.reset}${ie}`):w.push(`${q}${Xe.dim}${C.label}${Xe.reset}${ie}`)}E<e.length&&w.push(` ${Xe.dim}\u2193 more${Xe.reset}`);let S=w.join(`
|
|
1386
1386
|
`);process.stdout.write(S+`
|
|
1387
|
-
`),p=w.length}t.pause();let h=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",$),process.stdin.isTTY&&h!==void 0&&process.stdin.setRawMode(h),t.resume()}function $(w,k){if(k){if(k.name==="up"||k.ctrl&&k.name==="p"){c>0&&(c--,m());return}if(k.name==="down"||k.ctrl&&k.name==="n"){c<i.length-1&&(c++,m());return}if(k.name==="return"){let E=e[i[c]];g(),r(E?E.value:null);return}if(k.name==="escape"||k.ctrl&&k.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",$),m()})}async function CC(t){let e=kC(),n=EC(),s=TC(),o=[];for(let i of e)if(i.models.length!==0){o.push({label:i.provider,value:null,isHeader:!0});for(let a of i.models){let c=i.provider===n&&a.id===s;o.push({label:` ${a.name} (${i.provider}:${a.id})`,value:`${i.provider}:${a.id}`,isCurrent:c})}}let r=await z$(t,o,{title:"Select Model"});return r?(RC(r),console.log(`${Xe.green}Switched to ${r}${Xe.reset}`),!0):(console.log(`${Xe.dim}Cancelled${Xe.reset}`),!1)}X$.exports={pickFromList:z$,showModelPicker:CC}});var
|
|
1387
|
+
`),p=w.length}t.pause();let h=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",$),process.stdin.isTTY&&h!==void 0&&process.stdin.setRawMode(h),t.resume()}function $(w,k){if(k){if(k.name==="up"||k.ctrl&&k.name==="p"){c>0&&(c--,m());return}if(k.name==="down"||k.ctrl&&k.name==="n"){c<i.length-1&&(c++,m());return}if(k.name==="return"){let E=e[i[c]];g(),r(E?E.value:null);return}if(k.name==="escape"||k.ctrl&&k.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",$),m()})}async function CC(t){let e=kC(),n=EC(),s=TC(),o=[];for(let i of e)if(i.models.length!==0){o.push({label:i.provider,value:null,isHeader:!0});for(let a of i.models){let c=i.provider===n&&a.id===s;o.push({label:` ${a.name} (${i.provider}:${a.id})`,value:`${i.provider}:${a.id}`,isCurrent:c})}}let r=await z$(t,o,{title:"Select Model"});return r?(RC(r),console.log(`${Xe.green}Switched to ${r}${Xe.reset}`),!0):(console.log(`${Xe.dim}Cancelled${Xe.reset}`),!1)}X$.exports={pickFromList:z$,showModelPicker:CC}});var gd=K((yN,o0)=>{var J$=require("fs"),AC=require("path"),{atomicWrite:OC,withFileLockSync:MC}=Bn(),{callChat:Z$}=We(),{remember:NC,listMemories:gN,recall:PC}=mn(),md=4,LC=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
1388
1388
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
1389
1389
|
|
|
1390
1390
|
Return ONLY valid JSON in this exact format:
|
|
@@ -1412,7 +1412,7 @@ Rules:
|
|
|
1412
1412
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
1413
1413
|
- Return ONLY the JSON, no markdown, no explanation`;function Q$(t){return t.filter(e=>(e.role==="user"||e.role==="assistant")&&typeof e.content=="string"&&e.content.trim().length>10).slice(-40).map(e=>`[${e.role.toUpperCase()}]: ${e.content.substring(0,700)}`).join(`
|
|
1414
1414
|
|
|
1415
|
-
`)}async function e0(t){if(t.filter(o=>o.role==="user").length<
|
|
1415
|
+
`)}async function e0(t){if(t.filter(o=>o.role==="user").length<md)return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=Q$(t);if(!n.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=[{role:"system",content:LC},{role:"user",content:`Conversation to analyze:
|
|
1416
1416
|
|
|
1417
1417
|
${n}`}];try{let i=((await Z$(s,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let a=JSON.parse(i[0]);return{memories:Array.isArray(a.memories)?a.memories:[],nex_additions:Array.isArray(a.nex_additions)?a.nex_additions:[],summary:typeof a.summary=="string"?a.summary:null}}catch(o){return{memories:[],nex_additions:[],summary:null,error:o.message}}}function t0(t){let e=[];for(let{key:n,value:s}of t||[]){if(!n||!s||typeof n!="string"||typeof s!="string")continue;let o=n.trim().replace(/\s+/g,"-").substring(0,60),r=s.trim().substring(0,200);if(!o||!r)continue;let i=PC(o);i!==r&&(NC(o,r),e.push({key:o,value:r,action:i?"updated":"added"}))}return e}function n0(t){if(!t||t.length===0)return[];let e=AC.join(process.cwd(),"NEX.md");return MC(e,()=>{let n="";try{J$.existsSync(e)&&(n=J$.readFileSync(e,"utf-8"))}catch{}let s=[],o=n;for(let r of t){if(!r||typeof r!="string")continue;let i=r.trim();if(!i)continue;let a=i.substring(0,35).toLowerCase();n.toLowerCase().includes(a)||(s.push(i),o=o?o.endsWith(`
|
|
1418
1418
|
`)?o+i:o+`
|
|
@@ -1452,24 +1452,24 @@ Rules:
|
|
|
1452
1452
|
---
|
|
1453
1453
|
- Maximum 3 documents per session. Quality over quantity.
|
|
1454
1454
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
1455
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function s0(t){if(t.filter(o=>o.role==="user").length<
|
|
1455
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function s0(t){if(t.filter(o=>o.role==="user").length<md)return{documents:[],skip_reason:"Session too short"};let n=Q$(t);if(!n.trim())return{documents:[],skip_reason:"No usable content"};let s=[{role:"system",content:DC},{role:"user",content:`Conversation to analyze:
|
|
1456
1456
|
|
|
1457
1457
|
${n}`}];try{let i=((await Z$(s,[],{temperature:0,maxTokens:2e3})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{documents:[],error:"No JSON in response"};let a=JSON.parse(i[0]);return{documents:Array.isArray(a.documents)?a.documents:[],skip_reason:a.skip_reason}}catch(o){return{documents:[],error:o.message}}}async function jC(t){let e=await s0(t);if(e.error)return{written:[],skipped:[],error:e.error};if(!e.documents||e.documents.length===0)return{written:[],skipped:[],skip_reason:e.skip_reason};let{writeDocument:n,readDocument:s}=xr(),o=[],r=[];for(let i of e.documents){if(!i.name||!i.content)continue;let a=i.name.trim().replace(/\.md$/,"").replace(/[^a-z0-9-]/g,"-").substring(0,60);if(!a)continue;let c=s(a);if(c.content){let d=`
|
|
1458
1458
|
|
|
1459
1459
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
1460
1460
|
|
|
1461
|
-
${i.content}`;n(a,c.content+d),o.push({name:a,reason:i.reason||"",action:"updated"})}else n(a,i.content),o.push({name:a,reason:i.reason||"",action:"created"})}return{written:o,skipped:r}}o0.exports={learnFromSession:IC,learnBrainFromSession:jC,reflectOnSession:e0,reflectBrain:s0,applyMemories:t0,applyNexAdditions:n0,LEARN_MIN_MESSAGES:
|
|
1461
|
+
${i.content}`;n(a,c.content+d),o.push({name:a,reason:i.reason||"",action:"updated"})}else n(a,i.content),o.push({name:a,reason:i.reason||"",action:"created"})}return{written:o,skipped:r}}o0.exports={learnFromSession:IC,learnBrainFromSession:jC,reflectOnSession:e0,reflectBrain:s0,applyMemories:t0,applyNexAdditions:n0,LEARN_MIN_MESSAGES:md}});var gs=K(($N,r0)=>{var{C:De}=Ye();function qC(t){return t.tree&&t.tree.branches?t.tree:{branches:{main:{messages:t.messages||[],parentBranch:null,forkIndex:0}},activeBranch:"main"}}function FC(t){let e=t.branches[t.activeBranch];return e?e.messages:[]}function BC(t,e){let n=t.branches[t.activeBranch];n&&(n.messages=e)}function UC(t,e,n){let s=t.activeBranch,o=t.branches[s].messages;if(e<0||e>=o.length)throw new Error(`Fork index ${e} out of range (0-${o.length-1})`);return n||(n=`branch-${Object.keys(t.branches).filter(a=>a.startsWith("branch-")).reduce((a,c)=>{let u=parseInt(c.replace("branch-",""),10);return isNaN(u)?a:Math.max(a,u)},0)+1}`),t.branches[n]={messages:o.slice(0,e+1),parentBranch:s,forkIndex:e},t.activeBranch=n,{tree:t,branchName:n}}function WC(t,e){if(!t.branches[e])throw new Error(`Branch "${e}" not found. Available: ${Object.keys(t.branches).join(", ")}`);return t.activeBranch=e,t}function HC(t,e){let n=t.branches[t.activeBranch];if(!n)throw new Error("No active branch");if(e<0||e>=n.messages.length)throw new Error(`Index ${e} out of range (0-${n.messages.length-1})`);let s=n.messages.length-(e+1);return n.messages=n.messages.slice(0,e+1),{tree:t,truncated:s}}function YC(t,e){if(e==="main")throw new Error('Cannot delete the "main" branch');if(e===t.activeBranch)throw new Error("Cannot delete the active branch. Switch to another branch first.");if(!t.branches[e])throw new Error(`Branch "${e}" not found`);return delete t.branches[e],t}function GC(t){let e=[];e.push(`${De.bold}${De.cyan}Session Tree${De.reset}
|
|
1462
1462
|
`);let n=Object.keys(t.branches);for(let s of n){let o=t.branches[s],r=s===t.activeBranch,i=r?`${De.green}* `:" ",a=r?`${De.green}${De.bold}${s}${De.reset}`:`${De.cyan}${s}${De.reset}`,c=o.messages.length,u=o.parentBranch?` ${De.dim}(forked from ${o.parentBranch}@${o.forkIndex})${De.reset}`:"";e.push(`${i}${a} \u2014 ${c} messages${u}`);let f=o.messages.filter(p=>p.role==="user").slice(-2);for(let p of f){let m=typeof p.content=="string"?p.content.substring(0,60):"[multimodal]";e.push(` ${De.dim}> ${m}${m.length>=60?"...":""}${De.reset}`)}}return e.join(`
|
|
1463
1463
|
`)}function KC(t,e=20){let n=t.branches[t.activeBranch];if(!n)return"No active branch.";let s=n.messages,o=[];o.push(`${De.bold}${De.cyan}Timeline: ${t.activeBranch}${De.reset} (${s.length} messages)
|
|
1464
1464
|
`);let r=Math.max(0,s.length-e);for(let i=r;i<s.length;i++){let a=s[i],c=a.role,u=c==="user"?De.green:c==="assistant"?De.cyan:c==="system"?De.yellow:De.dim,d="";if(typeof a.content=="string")d=a.content.substring(0,70).replace(/\n/g," ");else if(Array.isArray(a.content)){let p=a.content.find(m=>m.type==="text"||m.type==="tool_result");d=p?(p.text||p.content||"").substring(0,70):"[blocks]"}d.length>=70&&(d+="...");let f=a.tool_calls&&a.tool_calls.length>0?` ${De.dim}[${a.tool_calls.length} tool calls]${De.reset}`:"";o.push(` ${De.dim}${String(i).padStart(3)}${De.reset} ${u}${c.padEnd(9)}${De.reset} ${d}${f}`)}return r>0&&o.splice(1,0,` ${De.dim}... ${r} earlier messages not shown${De.reset}`),o.join(`
|
|
1465
1465
|
`)}r0.exports={initTree:qC,getActiveMessages:FC,setActiveMessages:BC,createBranch:UC,switchBranch:WC,gotoMessage:HC,deleteBranch:YC,renderTree:GC,renderTimeline:KC}});var d0=K((wN,u0)=>{var{spawn:zC}=require("child_process"),i0=require("path"),a0=require("fs"),XC=require("os"),ys=new Map;function c0(t){return typeof t!="string"?t:t.replace(/\$\{([^}]+)\}/g,(e,n)=>process.env[n]!==void 0?process.env[n]:"")}function l0(t){let e=t||process.env.NEX_MCP_CONFIG||null,n=e?[e]:[i0.join(process.cwd(),".nex","mcp.json"),i0.join(XC.homedir(),".nex","mcp.json")];for(let s of n)if(a0.existsSync(s))try{return JSON.parse(a0.readFileSync(s,"utf-8"))}catch{}return{servers:{}}}function ic(t,e,n={},s=1e4){return new Promise((o,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:n})+`
|
|
1466
1466
|
`,c="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},s);function d(p){c+=p.toString();let m=c.split(`
|
|
1467
1467
|
`);for(let h of m)if(h.trim())try{let g=JSON.parse(h);if(g.id===i){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):o(g.result);return}}catch{}c=m[m.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(a)}catch(p){f(),r(new Error(`MCP write failed: ${p.message}`))}})}async function VC(t){let n=l0(t).servers||{},s=[];for(let[o,r]of Object.entries(n)){if(ys.has(o)){let d=ys.get(o);s.push({name:o,tools:d.tools.length});continue}let i={};for(let[d,f]of Object.entries(r.env||{}))i[d]=c0(f);let a=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],c={};for(let d of a)process.env[d]!==void 0&&(c[d]=process.env[d]);let u;try{u=zC(r.command,r.args||[],{stdio:["pipe","pipe","pipe"],env:{...c,...i}})}catch(d){console.warn(`[mcp-client] Failed to spawn '${o}': ${d.message}`),s.push({name:o,tools:0,error:d.message});continue}try{await ic(u,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.4.8"}});let d=await ic(u,"tools/list",{}),f=d&&d.tools||[];ys.set(o,{name:o,proc:u,tools:f,config:r}),s.push({name:o,tools:f.length})}catch(d){console.warn(`[mcp-client] Server '${o}' failed to initialize: ${d.message}`);try{u.kill()}catch{}s.push({name:o,tools:0,error:d.message})}}return s}async function JC(t,e,n={}){let s=ys.get(t);if(!s)throw new Error(`MCP server not connected: ${t}`);let o=await ic(s.proc,"tools/call",{name:e,arguments:n});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
1468
|
-
`):JSON.stringify(o)}function ZC(){let t=[];for(let[e,n]of ys)for(let s of n.tools)t.push({type:"function",function:{name:`mcp_${e}_${s.name}`,description:`[MCP:${e}] ${s.description||""}`,parameters:s.inputSchema||{type:"object",properties:{}}}});return t}function QC(){for(let[t,e]of ys){try{e.proc.kill()}catch{}ys.delete(t)}}function eA(){let t=[];for(let[e,n]of ys)t.push({name:e,connected:!0,toolCount:n.tools.length});return t}u0.exports={loadMcpServers:VC,callMcpTool:JC,getMcpTools:ZC,shutdownMcpServers:QC,listMcpServers:eA,_interpolateEnv:c0,_readConfig:l0,_sendRequest:ic}});var m0=K((_N,h0)=>{var Pt=require("fs"),Xo=require("path"),bN=require("os"),tA=require("readline"),{C:de}=Ye(),f0=".nex",
|
|
1468
|
+
`):JSON.stringify(o)}function ZC(){let t=[];for(let[e,n]of ys)for(let s of n.tools)t.push({type:"function",function:{name:`mcp_${e}_${s.name}`,description:`[MCP:${e}] ${s.description||""}`,parameters:s.inputSchema||{type:"object",properties:{}}}});return t}function QC(){for(let[t,e]of ys){try{e.proc.kill()}catch{}ys.delete(t)}}function eA(){let t=[];for(let[e,n]of ys)t.push({name:e,connected:!0,toolCount:n.tools.length});return t}u0.exports={loadMcpServers:VC,callMcpTool:JC,getMcpTools:ZC,shutdownMcpServers:QC,listMcpServers:eA,_interpolateEnv:c0,_readConfig:l0,_sendRequest:ic}});var m0=K((_N,h0)=>{var Pt=require("fs"),Xo=require("path"),bN=require("os"),tA=require("readline"),{C:de}=Ye(),f0=".nex",yd=null;function nA(t){yd=t}function Lt(t,e=""){let n=e?` ${de.dim}[${e}]${de.reset}`:"",s=` ${de.cyan}${t}${n}${de.reset}: `;return new Promise(o=>{let r=i=>{let a=i.trim()||e;o(a)};if(yd)yd.question(s,r);else{let i=tA.createInterface({input:process.stdin,output:process.stdout});i.question(s,a=>{i.close(),r(a)})}})}function zo(t,e=!0){return Lt(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(s=>s.toLowerCase()!=="n"&&s.toLowerCase()!=="no")}async function $d(t,e,n){let s=e.map((a,c)=>`${de.dim}${c+1})${de.reset} ${a}`).join(" ");console.log(` ${de.cyan}${t}${de.reset}`),console.log(` ${s}`);let o=n?e.indexOf(n)+1:1,r=await Lt("Enter number",String(o)),i=parseInt(r,10)-1;return e[Math.max(0,Math.min(i,e.length-1))]}async function sA(){let t=Xo.join(process.cwd(),f0),e=Xo.join(t,"servers.json"),n={};if(Pt.existsSync(e))try{n=JSON.parse(Pt.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
1469
1469
|
${de.bold}${de.cyan}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557${de.reset}`),console.log(`${de.bold}${de.cyan}\u2551 nex-code Server Setup Wizard \u2551${de.reset}`),console.log(`${de.bold}${de.cyan}\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${de.reset}
|
|
1470
1470
|
`);let s=Object.keys(n);if(s.length>0&&(console.log(`${de.dim}Existing profiles: ${s.join(", ")}${de.reset}`),!await zo("Add or update a server profile?",!0))){console.log(`${de.dim}No changes made.${de.reset}
|
|
1471
1471
|
`);return}let o={...n},r=!0;for(;r;){console.log(`
|
|
1472
|
-
${de.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${de.reset}`);let c=await Lt("Profile name (e.g. prod, staging, macbook)");if(!c){console.log(`${de.red} Name is required.${de.reset}`);continue}let u=await Lt("Host / IP address");if(!u){console.log(`${de.red} Host is required.${de.reset}`);continue}let d=await Lt("SSH user","root"),f=await Lt("SSH port","22"),p=parseInt(f,10)||22,m=await Lt("SSH key path (leave empty for SSH agent)",""),h=await
|
|
1472
|
+
${de.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${de.reset}`);let c=await Lt("Profile name (e.g. prod, staging, macbook)");if(!c){console.log(`${de.red} Name is required.${de.reset}`);continue}let u=await Lt("Host / IP address");if(!u){console.log(`${de.red} Host is required.${de.reset}`);continue}let d=await Lt("SSH user","root"),f=await Lt("SSH port","22"),p=parseInt(f,10)||22,m=await Lt("SSH key path (leave empty for SSH agent)",""),h=await $d("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await zo("Allow sudo commands?",!0),$={host:u,user:d};p!==22&&($.port=p),m&&($.key=m),h!=="other"&&($.os=h),g&&($.sudo=!0),o[c]=$,console.log(`
|
|
1473
1473
|
${de.green}\u2713${de.reset} Profile "${c}" added: ${d}@${u}${p!==22?`:${p}`:""}${h!=="other"?` [${h}]`:""}`),r=await zo(`
|
|
1474
1474
|
Add another server?`,!1)}Pt.existsSync(t)||Pt.mkdirSync(t,{recursive:!0}),Pt.writeFileSync(e,JSON.stringify(o,null,2)+`
|
|
1475
1475
|
`,"utf-8"),console.log(`
|
|
@@ -1482,13 +1482,13 @@ ${de.dim}Use /servers to list profiles, /servers ping to check connectivity.${de
|
|
|
1482
1482
|
`)}async function p0(t,e){let n=e||Xo.join(process.cwd(),f0),s=Xo.join(n,"deploy.json"),o={};if(Pt.existsSync(s))try{o=JSON.parse(Pt.readFileSync(s,"utf-8"))}catch{}if(!t){let u=Xo.join(n,"servers.json");if(Pt.existsSync(u))try{t=JSON.parse(Pt.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
1483
1483
|
${de.bold}${de.cyan}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557${de.reset}`),console.log(`${de.bold}${de.cyan}\u2551 Deploy Config Wizard \u2551${de.reset}`),console.log(`${de.bold}${de.cyan}\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${de.reset}
|
|
1484
1484
|
`);let i=Object.keys(o);i.length>0&&console.log(`${de.dim}Existing deploy configs: ${i.join(", ")}${de.reset}`);let a={...o},c=!0;for(;c;){console.log(`
|
|
1485
|
-
${de.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${de.reset}`);let u=await Lt("Config name (e.g. prod, staging)");if(!u){console.log(`${de.red} Name is required.${de.reset}`);continue}let d;r.length>0?d=await
|
|
1485
|
+
${de.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${de.reset}`);let u=await Lt("Config name (e.g. prod, staging)");if(!u){console.log(`${de.red} Name is required.${de.reset}`);continue}let d;r.length>0?d=await $d("Target server",r,r[0]):d=await Lt("Target server (profile name or user@host)");let f=await $d("Deploy method",["rsync","git"],"rsync"),p="",m=[],h="";if(f==="rsync"){p=await Lt("Local path to sync (e.g. dist/ or ./build)","dist/");let S=await Lt("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env");m=S?S.split(",").map(x=>x.trim()).filter(Boolean):[]}else h=await Lt("Branch to pull (leave empty for current remote branch)","main");let g=await Lt(f==="git"?"Remote repo path (e.g. /home/deploy/my-app)":"Remote destination path (e.g. /var/www/app)");if(!g){console.log(`${de.red} Remote path is required.${de.reset}`);continue}let $=await Lt("Command to run on remote after deploy (leave empty to skip)",""),w=await Lt("Health check URL or remote command (leave empty to skip)",""),k={server:d,method:f,remote_path:g};f==="rsync"?(k.local_path=p,m.length>0&&(k.exclude=m)):h&&(k.branch=h),$&&(k.deploy_script=$),w&&(k.health_check=w),a[u]=k;let E=f==="git"?`${d}:${g}${h?` (${h})`:""}`:`${p.endsWith("/")?p:p+"/"} \u2192 ${d}:${g}`;console.log(`
|
|
1486
1486
|
${de.green}\u2713${de.reset} Deploy config "${u}": [${f}] ${E}`),$&&console.log(` ${de.dim} Then: ${$}${de.reset}`),w&&console.log(` ${de.dim} Health: ${w}${de.reset}`),c=await zo(`
|
|
1487
1487
|
Add another deploy config?`,!1)}Pt.existsSync(n)||Pt.mkdirSync(n,{recursive:!0}),Pt.writeFileSync(s,JSON.stringify(a,null,2)+`
|
|
1488
1488
|
`,"utf-8"),console.log(`
|
|
1489
1489
|
${de.green}\u2713 Saved .nex/deploy.json (${Object.keys(a).length} config${Object.keys(a).length!==1?"s":""})${de.reset}`),console.log(`${de.dim}Use: deploy prod (or with explicit params)${de.reset}
|
|
1490
|
-
`)}h0.exports={runServerWizard:sA,runDeployWizard:p0,setWizardRL:nA}});var Vo=K((xN,$0)=>{"use strict";var lc=require("os"),ui=require("path"),gt=require("fs"),oA=require("axios"),rA=require("https"),ac=ui.join(lc.homedir(),".nex-code","known-models.json"),iA="https://ollama.com/api/tags",aA=60,cA={"qwen3-coder:480b":131072,"devstral-2:123b":131072,"devstral-small-2:24b":131072,"kimi-k2:1t":262144,"kimi-k2.5":262144,"kimi-k2-thinking":262144,"minimax-m2.7:cloud":2e5,"minimax-m2.7":2e5,"minimax-m2.5":131072,"minimax-m2.1":2e5,"minimax-m2":2e5,"qwen3.5:397b":262144,"qwen3.5:35b-a3b":262144,"deepseek-v3.2":131072,"deepseek-v3.1:671b":131072,"cogito-2.1:671b":131072,"glm-5":128e3,"glm-5:cloud":128e3,"glm-4.7":128e3,"glm-4.6":128e3,"qwen3-vl:235b":131072,"qwen3-vl:235b-instruct":131072,"qwen3-coder-next":262144,"qwen3-next:80b":131072,"mistral-large-3:675b":131072,"ministral-3:14b":131072,"ministral-3:8b":131072,"ministral-3:3b":32768,"nemotron-3-nano:30b":131072,"nemotron-3-super":262144,"rnj-1:8b":131072,"gpt-oss:120b":131072,"gpt-oss:20b":131072,"gemma3:4b":131072,"gemma3:12b":131072,"gemma3:27b":131072,"gemini-3-flash-preview":131072};function
|
|
1491
|
-
`);return`${
|
|
1490
|
+
`)}h0.exports={runServerWizard:sA,runDeployWizard:p0,setWizardRL:nA}});var Vo=K((xN,$0)=>{"use strict";var lc=require("os"),ui=require("path"),gt=require("fs"),oA=require("axios"),rA=require("https"),ac=ui.join(lc.homedir(),".nex-code","known-models.json"),iA="https://ollama.com/api/tags",aA=60,cA={"qwen3-coder:480b":131072,"devstral-2:123b":131072,"devstral-small-2:24b":131072,"kimi-k2:1t":262144,"kimi-k2.5":262144,"kimi-k2-thinking":262144,"minimax-m2.7:cloud":2e5,"minimax-m2.7":2e5,"minimax-m2.5":131072,"minimax-m2.1":2e5,"minimax-m2":2e5,"qwen3.5:397b":262144,"qwen3.5:35b-a3b":262144,"deepseek-v3.2":131072,"deepseek-v3.1:671b":131072,"cogito-2.1:671b":131072,"glm-5":128e3,"glm-5:cloud":128e3,"glm-4.7":128e3,"glm-4.6":128e3,"qwen3-vl:235b":131072,"qwen3-vl:235b-instruct":131072,"qwen3-coder-next":262144,"qwen3-next:80b":131072,"mistral-large-3:675b":131072,"ministral-3:14b":131072,"ministral-3:8b":131072,"ministral-3:3b":32768,"nemotron-3-nano:30b":131072,"nemotron-3-super":262144,"rnj-1:8b":131072,"gpt-oss:120b":131072,"gpt-oss:20b":131072,"gemma3:4b":131072,"gemma3:12b":131072,"gemma3:27b":131072,"gemini-3-flash-preview":131072};function wd(){try{if(gt.existsSync(ac))return JSON.parse(gt.readFileSync(ac,"utf-8"))}catch{}return{benchmarked:[],lastChecked:null}}function lA(t){let e=ui.dirname(ac);gt.existsSync(e)||gt.mkdirSync(e,{recursive:!0}),gt.writeFileSync(ac,JSON.stringify(t,null,2))}function uA(t){let e=wd(),n=new Set(e.benchmarked);for(let s of t)n.add(s);e.benchmarked=[...n],e.lastChecked=new Date().toISOString(),lA(e)}async function g0(){let t=process.env.OLLAMA_API_KEY;if(!t)throw new Error("OLLAMA_API_KEY not set");let e=new rA.Agent({keepAlive:!0});return((await oA.get(iA,{headers:{Authorization:`Bearer ${t}`},timeout:15e3,httpsAgent:e})).data?.models||[]).map(s=>(s.name||s.model||"").replace(/:latest$/,"")).filter(Boolean)}async function dA(){let t=await g0(),e=wd(),n=new Set(e.benchmarked),s=t.filter(o=>!n.has(o));return{allCloud:t,newModels:s,store:e}}var bd="<!-- nex-benchmark-start -->",cc="<!-- nex-benchmark-end -->",fA={"qwen3-vl:235b":"Overall #1 \u2014 frontier tool selection, data + agentic tasks","qwen3-vl:235b-instruct":"Best latency/score balance \u2014 recommended default","devstral-2:123b":"Sysadmin + SSH tasks, reliable coding","devstral-small-2:24b":"Fast sub-agents, simple lookups","ministral-3:8b":"Fastest strong model \u2014 2.2s latency, 70+ score","qwen3-coder:480b":"Heavy coding sessions, large context","kimi-k2:1t":"Large repos (>100K tokens)","kimi-k2.5":"Large repos \u2014 faster than k2:1t","minimax-m2.7:cloud":"Complex swarm / multi-agent sessions","minimax-m2.5":"Multi-agent, large context","qwen3.5:35b-a3b":"Fast MoE with 256K context","gpt-oss:20b":"Fast small model, good overall score"};function pA(t){return t?t>=25e4?"256K":t>=19e4?"200K":t>=128e3?"131K":t>=64e3?"64K":`${Math.round(t/1024)}K`:"?"}function y0(t,e){let n=["\u{1F947}","\u{1F948}","\u{1F949}"],s=(e||new Date().toISOString()).split("T")[0],o=t.filter(r=>r.score>=aA).map((r,i)=>{let a=n[i]||"\u2014",c=pA(cA[r.model]),u=fA[r.model]||"\u2014",d=`${(r.avgLatency/1e3).toFixed(1)}s`,f=i===0?`**${r.score}**`:String(r.score);return`| ${a} | \`${r.model}\` | ${f} | ${d} | ${c} | ${u} |`}).join(`
|
|
1491
|
+
`);return`${bd}
|
|
1492
1492
|
<!-- Updated: ${s} \u2014 run \`/benchmark --discover\` after new Ollama Cloud releases -->
|
|
1493
1493
|
|
|
1494
1494
|
| Rank | Model | Score | Avg Latency | Context | Best For |
|
|
@@ -1497,7 +1497,7 @@ ${o}
|
|
|
1497
1497
|
|
|
1498
1498
|
> Rankings are nex-code-specific: tool name accuracy, argument validity, schema compliance.
|
|
1499
1499
|
> Toolathon (Minimax SOTA) measures different task types \u2014 run \`/benchmark --discover\` after model releases.
|
|
1500
|
-
${cc}`}function hA(t,e){if(!gt.existsSync(e))return!1;let n=gt.readFileSync(e,"utf-8"),s=n.indexOf(
|
|
1500
|
+
${cc}`}function hA(t,e){if(!gt.existsSync(e))return!1;let n=gt.readFileSync(e,"utf-8"),s=n.indexOf(bd),o=n.indexOf(cc);if(s===-1||o===-1)return!1;let r=n.slice(0,s),i=n.slice(o+cc.length),a=y0(t);return gt.writeFileSync(e,r+a+i),!0}function mA(t){let e=ui.join(lc.homedir(),".nex-code","models.env");if(!gt.existsSync(e)||t.length===0)return{updated:!1,reason:"models.env not found or empty summary"};let n=t[0],s=gt.readFileSync(e,"utf-8"),r=s.match(/^DEFAULT_MODEL=(\S+)/m)?.[1];if(r===n.model)return{updated:!1,reason:"winner unchanged"};let i=t.find(c=>c.model===r);if(i&&n.score-i.score<5)return{updated:!1,reason:`margin ${(n.score-i.score).toFixed(1)}pts < 5pts threshold`};let a=new Date().toISOString().split("T")[0];return s=s.replace(/^DEFAULT_MODEL=\S+/m,`DEFAULT_MODEL=${n.model}`).replace(/^# Last reviewed:.*$/m,`# Last reviewed: ${a} (after /benchmark, ${n.model} wins nex-code tasks)`),gt.writeFileSync(e,s),{updated:!0,previousModel:r,newModel:n.model}}function gA(t){let{saveRoutingConfig:e}=us(),n=ui.join(lc.homedir(),".nex-code","models.env"),s=[],o=Object.entries(t).filter(([,a])=>a.score>0);if(o.length===0)return{saved:!1,envUpdated:!1,changes:[]};let r={};for(let[a,c]of o)r[a]=c.model,s.push(`${a}: ${c.model} (${c.score}/100)`);e(r);let i=!1;if(gt.existsSync(n)){let a=gt.readFileSync(n,"utf-8"),u=Object.entries({coding:"NEX_ROUTE_CODING",frontend:"NEX_ROUTE_FRONTEND",sysadmin:"NEX_ROUTE_SYSADMIN",data:"NEX_ROUTE_DATA",agentic:"NEX_ROUTE_AGENTIC"}).filter(([p])=>t[p]&&t[p].score>0).map(([p,m])=>`${m}=${t[p].model} # ${p} score: ${t[p].score}/100`).join(`
|
|
1501
1501
|
`),d="# \u2500\u2500 Task-type routing (auto-updated by /benchmark) \u2500\u2500",f="# \u2500\u2500 end routing \u2500\u2500";if(a.includes(d)){let p=a.indexOf(d),m=a.indexOf(f);m!==-1&&(a=a.slice(0,p)+`${d}
|
|
1502
1502
|
${u}
|
|
1503
1503
|
${f}`+a.slice(m+f.length))}else a+=`
|
|
@@ -1506,12 +1506,12 @@ ${u}
|
|
|
1506
1506
|
${f}
|
|
1507
1507
|
`;gt.writeFileSync(n,a),i=!0}return{saved:!0,envUpdated:i,changes:s}}var yA=/thinking|reasoning|instruct|planner|orchestrat/i;function $A(t){return yA.test(t)}function wA(t){if(!t||t.length===0)return{updated:!1};let e=ui.join(lc.homedir(),".nex-code","models.env");if(!gt.existsSync(e))return{updated:!1};let n=gt.readFileSync(e,"utf-8"),s=n.match(/^NEX_ORCHESTRATOR_MODEL=(.+)$/m),o=s?s[1].trim():null,i=[...t].sort((d,f)=>f.overall-d.overall)[0],a=o?t.find(d=>d.model===o):null,c=a?a.overall:0;if(i.model===o)return{updated:!1};if(c>0&&i.overall<c*1.05)return{updated:!1};let u=`NEX_ORCHESTRATOR_MODEL=${i.model}`;return s?n=n.replace(/^NEX_ORCHESTRATOR_MODEL=.+$/m,u):n+=`
|
|
1508
1508
|
${u}
|
|
1509
|
-
`,gt.writeFileSync(e,n),{updated:!0,previousModel:o,newModel:i.model}}$0.exports={findNewModels:dA,fetchCloudModels:g0,loadKnownModels:yd,markBenchmarked:uA,updateReadme:hA,updateModelsEnv:mA,updateRoutingConfig:gA,generateBenchmarkBlock:y0,checkOrchestratorCandidate:$A,updateOrchestratorModel:wA,SENTINEL_START:$d,SENTINEL_END:cc}});var $s=K((SN,R0)=>{"use strict";var{C:J}=Ye(),bA=We(),{TOOL_DEFINITIONS:w0}=fn(),{saveRoutingConfig:_A}=us(),_d=[{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 n=e?.function?.parameters||{},s=n.required||[],o=Object.keys(n.properties||{});return s.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>o.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"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}],b0=[{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)}],fc=[..._d,...b0],wd=["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 xA(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return wd;let s=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(s)||s.length===0?wd:s.filter(o=>typeof o.score=="number"&&o.score>=60).sort((o,r)=>r.score-o.score).slice(0,12).map(o=>o.model)}catch{return wd}}var xd=xA(),SA=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],_0=(()=>{let t=xd.slice(0,3);return t.length>=3?t:SA})(),vA=14,uc={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},kA="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 bd(t,e){let n={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},s=[{role:"system",content:kA},{role:"user",content:t.prompt}],o=Date.now();try{let r=await bA.callChat(s,w0,{provider:"ollama",model:e,temperature:0,timeout:9e4});n.latencyMs=Date.now()-o;let i=r.tool_calls||[];if(t.expectedTool===null){let a=i.length===0;n.producedToolCall=a,n.correctTool=a,n.validArgs=!0,n.schemaCompliant=!0}else if(i.length>0){let a=i[0],c=a.function?.name||"unknown",u=a.function?.arguments||{};n.producedToolCall=!0,n.toolCalled=c;let d=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(n.correctTool=d.includes(c),n.correctTool){let f=w0.find(p=>p.function?.name===c);if(n.validArgs=!!t.validateArgs(u,f),f){let p=f.function?.parameters||{},m=p.required||[],h=Object.keys(p.properties||{});n.schemaCompliant=m.every(g=>u[g]!==void 0)&&Object.keys(u).every(g=>h.includes(g))}}}}catch(r){n.latencyMs=Date.now()-o,n.error=r.message.slice(0,120)}return n}function Jo(t){return t.error?0:((t.producedToolCall?uc.producedToolCall:0)+(t.correctTool?uc.correctTool:0)+(t.validArgs?uc.validArgs:0)+(t.schemaCompliant?uc.schemaCompliant:0))*100}var x0={coding:"coding",search:"coding",shell:"coding",schema:"coding","multi-step":"coding",reasoning:"coding",frontend:"frontend",sysadmin:"sysadmin",data:"data",agentic:"agentic",resilience:"coding",ssh:"sysadmin",git:"coding","phase-plan":"plan","phase-verify":"verify"};function Sd(t){return Object.entries(t).map(([e,n])=>{let s=n.map(Jo),o=s.reduce((a,c)=>a+c,0)/s.length,r=a=>Math.round(n.filter(a).length/n.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=n.filter(d=>x0[d.category]===a);if(c.length===0)continue;let u=c.map(Jo).reduce((d,f)=>d+f,0)/c.length;i[a]=Math.round(u*10)/10}return{model:e,score:Math.round(o*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(n.reduce((a,c)=>a+c.latencyMs,0)/n.length),errorCount:n.filter(a=>a.error).length,categoryScores:i,results:n}}).sort((e,n)=>n.score-e.score)}function S0(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,$)=>$.categoryScores[a]-g.categoryScores[a]);if(c.length===0)continue;let d=(c[0]?.results||[]).filter(g=>x0[g.category]===a).length;if(d<4)continue;let f=c[0],p=c[1];if(f.categoryScores[a]>=95&&d<8&&p&&f.categoryScores[a]-p.categoryScores[a]<15){let $=t.filter(w=>w.categoryScores[a]!==void 0).find(w=>w.categoryScores[a]<95);$&&(e[a]={model:$.model,score:$.categoryScores[a],avgLatency:$.avgLatency,_flukePrevented:!0});continue}let h=c.filter(g=>f.categoryScores[a]-g.categoryScores[a]<=5).sort((g,$)=>g.avgLatency-$.avgLatency)[0];e[a]={model:h.model,score:h.categoryScores[a],avgLatency:h.avgLatency}}return e}function v0(t,e){let n=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,s=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],o=s.reduce((d,f)=>d+f.width+1,0)+1,r="\u2500".repeat(o);console.log(`
|
|
1509
|
+
`,gt.writeFileSync(e,n),{updated:!0,previousModel:o,newModel:i.model}}$0.exports={findNewModels:dA,fetchCloudModels:g0,loadKnownModels:wd,markBenchmarked:uA,updateReadme:hA,updateModelsEnv:mA,updateRoutingConfig:gA,generateBenchmarkBlock:y0,checkOrchestratorCandidate:$A,updateOrchestratorModel:wA,SENTINEL_START:bd,SENTINEL_END:cc}});var $s=K((SN,R0)=>{"use strict";var{C:J}=Ye(),bA=We(),{TOOL_DEFINITIONS:w0}=fn(),{saveRoutingConfig:_A}=us(),Sd=[{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 n=e?.function?.parameters||{},s=n.required||[],o=Object.keys(n.properties||{});return s.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>o.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"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}],b0=[{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)}],fc=[...Sd,...b0],_d=["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 xA(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return _d;let s=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(s)||s.length===0?_d:s.filter(o=>typeof o.score=="number"&&o.score>=60).sort((o,r)=>r.score-o.score).slice(0,12).map(o=>o.model)}catch{return _d}}var vd=xA(),SA=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],_0=(()=>{let t=vd.slice(0,3);return t.length>=3?t:SA})(),vA=14,uc={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},kA="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 xd(t,e){let n={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},s=[{role:"system",content:kA},{role:"user",content:t.prompt}],o=Date.now();try{let r=await bA.callChat(s,w0,{provider:"ollama",model:e,temperature:0,timeout:9e4});n.latencyMs=Date.now()-o;let i=r.tool_calls||[];if(t.expectedTool===null){let a=i.length===0;n.producedToolCall=a,n.correctTool=a,n.validArgs=!0,n.schemaCompliant=!0}else if(i.length>0){let a=i[0],c=a.function?.name||"unknown",u=a.function?.arguments||{};n.producedToolCall=!0,n.toolCalled=c;let d=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(n.correctTool=d.includes(c),n.correctTool){let f=w0.find(p=>p.function?.name===c);if(n.validArgs=!!t.validateArgs(u,f),f){let p=f.function?.parameters||{},m=p.required||[],h=Object.keys(p.properties||{});n.schemaCompliant=m.every(g=>u[g]!==void 0)&&Object.keys(u).every(g=>h.includes(g))}}}}catch(r){n.latencyMs=Date.now()-o,n.error=r.message.slice(0,120)}return n}function Jo(t){return t.error?0:((t.producedToolCall?uc.producedToolCall:0)+(t.correctTool?uc.correctTool:0)+(t.validArgs?uc.validArgs:0)+(t.schemaCompliant?uc.schemaCompliant:0))*100}var x0={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 kd(t){return Object.entries(t).map(([e,n])=>{let s=n.map(Jo),o=s.reduce((a,c)=>a+c,0)/s.length,r=a=>Math.round(n.filter(a).length/n.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=n.filter(d=>x0[d.category]===a);if(c.length===0)continue;let u=c.map(Jo).reduce((d,f)=>d+f,0)/c.length;i[a]=Math.round(u*10)/10}return{model:e,score:Math.round(o*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(n.reduce((a,c)=>a+c.latencyMs,0)/n.length),errorCount:n.filter(a=>a.error).length,categoryScores:i,results:n}}).sort((e,n)=>n.score-e.score)}function S0(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,$)=>$.categoryScores[a]-g.categoryScores[a]);if(c.length===0)continue;let d=(c[0]?.results||[]).filter(g=>x0[g.category]===a).length;if(d<4)continue;let f=c[0],p=c[1];if(f.categoryScores[a]>=95&&d<8&&p&&f.categoryScores[a]-p.categoryScores[a]<15){let $=t.filter(w=>w.categoryScores[a]!==void 0).find(w=>w.categoryScores[a]<95);$&&(e[a]={model:$.model,score:$.categoryScores[a],avgLatency:$.avgLatency,_flukePrevented:!0});continue}let h=c.filter(g=>f.categoryScores[a]-g.categoryScores[a]<=5).sort((g,$)=>g.avgLatency-$.avgLatency)[0];e[a]={model:h.model,score:h.categoryScores[a],avgLatency:h.avgLatency}}return e}function v0(t,e){let n=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,s=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],o=s.reduce((d,f)=>d+f.width+1,0)+1,r="\u2500".repeat(o);console.log(`
|
|
1510
1510
|
${J.bold}${n}${J.reset}`),console.log(r);let i=s.map(d=>d.label.padEnd(d.width)).join(" ");if(console.log(`${J.dim}${i}${J.reset}`),console.log(r),t.forEach((d,f)=>{let p=String(f+1).padEnd(s[0].width),m=d.model.slice(0,s[1].width).padEnd(s[1].width),h=String(d.score).padEnd(s[2].width),g=`${d.toolCallRate}%`.padEnd(s[3].width),$=`${d.correctRate}%`.padEnd(s[4].width),w=`${d.validArgsRate}%`.padEnd(s[5].width),k=`${d.schemaRate}%`.padEnd(s[6].width),E=`${(d.avgLatency/1e3).toFixed(1)}s`.padEnd(s[7].width),S=d.errorCount>0?`${J.red}${d.errorCount}${J.reset}`:`${J.dim}0${J.reset}`,x=d.score>=80?J.green:d.score>=60?J.yellow:J.red,C=f===0?`${J.yellow}${p}${J.reset}`:`${J.dim}${p}${J.reset}`;console.log(`${C} ${x}${m}${J.reset} ${J.bold}${x}${h}${J.reset} ${g} ${$} ${w} ${k} ${J.dim}${E}${J.reset} ${S}`)}),console.log(r),t.length>0){let d=t[0];if(console.log(`
|
|
1511
1511
|
${J.bold}${J.green}Winner: ${d.model}${J.reset} score ${d.score}/100`),t.length>1){let f=(d.score-t[1].score).toFixed(1);console.log(`${J.dim}+${f} pts over ${t[1].model}${J.reset}`)}}let a=t.filter(d=>d.results.some(f=>!f.error&&(!f.correctTool||!f.validArgs)));if(a.length>0){console.log(`${J.bold}Failing tasks:${J.reset}`);for(let d of a){let f=d.results.filter(h=>!h.error&&(!h.correctTool||!h.validArgs));if(f.length===0)continue;let p=d.model.slice(0,22),m=f.map(h=>{if(!h.correctTool){let g=h.toolCalled||"(none)";return`${J.dim}${h.taskId}${J.reset} ${J.red}\u2192${g}${J.reset}`}return`${J.dim}${h.taskId}${J.reset} ${J.yellow}bad-args${J.reset}`});console.log(` ${J.dim}${p.padEnd(22)}${J.reset} ${m.join(" ")}`)}console.log()}let c=["coding","frontend","sysadmin","data","agentic"];if(t.some(d=>Object.keys(d.categoryScores).length>1)){console.log(`
|
|
1512
1512
|
${J.bold}Best model per task type:${J.reset}`);for(let d of c){let f=t.filter(g=>g.categoryScores[d]!==void 0).sort((g,$)=>$.categoryScores[d]-g.categoryScores[d]);if(f.length===0)continue;let p=f[0],m=p.categoryScores[d],h=m>=80?J.green:m>=60?J.yellow:J.red;console.log(` ${J.dim}${d.padEnd(10)}${J.reset} ${h}${p.model}${J.reset} ${J.dim}${m}/100${J.reset}`)}}console.log()}function k0(t){if(!(!t||t.length<2))try{let e=S0(t),{loadRoutingConfig:n}=us(),s=n(),o={...s},r=[],i=new Set(["plan","verify"]);for(let[a,{model:c,score:u}]of Object.entries(e)){let d=i.has(a),f=d?s.phases&&s.phases[a]:s[a];f&&f!==c&&!t.find(m=>m.model===f)||(d?(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&&(_A(o),console.log(`
|
|
1513
1513
|
${J.dim} Routing updated: ${r.join(", ")}${J.reset}`),console.log(`
|
|
1514
|
-
${J.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${J.reset}`))}catch{}}async function EA({models:t,quick:e=!1,onProgress:n,parallelModels:s=1}={}){let o=e?
|
|
1514
|
+
${J.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${J.reset}`))}catch{}}async function EA({models:t,quick:e=!1,onProgress:n,parallelModels:s=1}={}){let o=e?Sd.slice(0,vA):fc,r=t?.length>0?t:e?_0:vd,i={};for(let c of r)i[c]=[];if(s<=1)for(let c of r)for(let u of o){n?.({model:c,task:u.id,done:!1});let d=await xd(u,c);i[c].push(d),n?.({model:c,task:u.id,done:!0,score:Jo(d),error:d.error})}else{let c=Math.min(s,r.length),u=[...r],d=Array.from({length:c},async()=>{for(;u.length>0;){let f=u.shift();if(!f)break;for(let p of o){n?.({model:f,task:p.id,done:!1});let m=await xd(p,f);i[f].push(m),n?.({model:f,task:p.id,done:!0,score:Jo(m),error:m.error})}}});await Promise.all(d)}let a=kd(i);return v0(a,o.length),k0(a),a}async function TA({newModels:t,existingRanking:e=[],onProgress:n}={}){if(!t||t.length===0)return e;let s={};for(let i of t){s[i]=[];for(let a of fc){n?.({model:i,task:a.id,done:!1});let c=await xd(a,i);s[i].push(c),n?.({model:i,task:a.id,done:!0,score:Jo(c),error:c.error})}}let r=[...kd(s)];for(let i of e)r.find(a=>a.model===i.model)||r.push(i);return r.sort((i,a)=>a.score-i.score),v0(r,fc.length),k0(r),r}var dc=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function E0(t){let e=require("fs"),s=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(s))return console.log(`${J.yellow}No scenarios configured.${J.reset} Create ${J.dim}.nex/benchmark-config.json${J.reset} to define your benchmark scenarios.
|
|
1515
1515
|
Example:
|
|
1516
1516
|
{
|
|
1517
1517
|
"scenarios": [
|
|
@@ -1534,18 +1534,18 @@ ${J.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will
|
|
|
1534
1534
|
${J.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${J.reset}`);for(let i of r){let a=(i.date||"").replace("T"," ").substring(0,16),c=(i.version||"?").padEnd(8),u=(i.model||"?").substring(0,12).padEnd(12),d=`${i.score}/10`.padStart(6),f=i.grade||"?",p=i.issues&&i.issues.length>0?`${J.yellow}\u26A0 ${i.issues.slice(0,2).map(h=>h.substring(0,30)).join(", ")}${J.reset}`:`${J.green}\u2713${J.reset}`,m=i.score>=8?J.green:i.score>=6?J.yellow:J.red;console.log(` ${J.dim}${a}${J.reset} ${J.dim}v${c}${J.reset} ${J.dim}${u}${J.reset} ${m}${d} ${f}${J.reset} ${p}`)}console.log()}async function OA({dryRun:t=!1,model:e,cwd:n,onProgress:s}={}){let o=lo(),r=E0(n);if(t){console.log(`
|
|
1535
1535
|
${J.bold}Scenario Benchmark \u2014 Scenarios (dry-run):${J.reset}
|
|
1536
1536
|
`);for(let c of r)console.log(` ${J.cyan}${c.id.padEnd(20)}${J.reset} ${J.dim}${c.name}${J.reset} maxTurns=${c.maxTurns}`),console.log(` ${J.dim}${c.prompt.substring(0,80)}${J.reset}`);return console.log(),[]}let i=(()=>{if(e)return typeof e=="object"?e.id||"unknown":e;try{let{getActiveModel:c}=bo(),u=c?c():null;return u?typeof u=="object"?u.id||"unknown":u:"unknown"}catch{return"unknown"}})(),a=[];for(let c of r){s?.({id:c.id,name:c.name,done:!1}),console.log(`
|
|
1537
|
-
${J.dim}Running scenario: ${c.name}...${J.reset}`);let{messages:u,timedOut:d}=await RA(c,{model:i,cwd:n}),f;d||u.length===0?f={score:0,grade:"F",issues:[d?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:f=T0(u,c);let p={id:c.id,name:c.name,score:f.score,grade:f.grade,issues:f.issues,bonuses:f.bonuses};a.push(p),s?.({id:c.id,name:c.name,done:!0,score:f.score,grade:f.grade});try{let{appendScoreHistory:m}=Ca();m(f.score,{version:o.version,model:i,sessionName:`bench:${c.id}`,issues:f.issues})}catch{}}return CA(a,o.version,i),a}R0.exports={runBenchmark:EA,runDiscoverBenchmark:TA,buildSummary:
|
|
1537
|
+
${J.dim}Running scenario: ${c.name}...${J.reset}`);let{messages:u,timedOut:d}=await RA(c,{model:i,cwd:n}),f;d||u.length===0?f={score:0,grade:"F",issues:[d?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:f=T0(u,c);let p={id:c.id,name:c.name,score:f.score,grade:f.grade,issues:f.issues,bonuses:f.bonuses};a.push(p),s?.({id:c.id,name:c.name,done:!0,score:f.score,grade:f.grade});try{let{appendScoreHistory:m}=Ca();m(f.score,{version:o.version,model:i,sessionName:`bench:${c.id}`,issues:f.issues})}catch{}}return CA(a,o.version,i),a}R0.exports={runBenchmark:EA,runDiscoverBenchmark:TA,buildSummary:kd,buildCategoryWinners:S0,TASKS:Sd,PHASE_TASKS:b0,ALL_TASKS:fc,scoreResult:Jo,DEFAULT_MODELS:vd,QUICK_MODELS:_0,runScenarioBenchmark:OA,showScoreTrend:AA,loadScenarios:E0,DEFAULT_SCENARIOS:dc,scoreScenario:T0}});var D0=K((vN,I0)=>{"use strict";var MA=require("os"),O0=require("path"),Ed=require("fs"),{callWithRetry:C0}=ga(),{parseModelSpec:NA}=We(),{extractJSON:A0,DECOMPOSE_PROMPT:PA,SYNTHESIZE_PROMPT:LA}=Br(),{C:Vt}=Ye(),pc=O0.join(MA.homedir(),".nex-code","orchestrator-bench.json"),M0=[{id:"decompose_multi_bug",type:"decompose",prompt:"Fix 4 bugs: (1) 500 error on SmartThings API call, (2) invalid time format on Sunday schedule, (3) Google Auth callback fails with CORS, (4) contact search returns empty",expectedSubTasks:4,maxSubTasks:5},{id:"decompose_feature_mix",type:"decompose",prompt:"Add dark mode toggle to settings page, fix the broken login redirect, improve search performance by adding an index, update API docs for the new endpoints",expectedSubTasks:4,maxSubTasks:5},{id:"decompose_overlapping",type:"decompose",prompt:"Refactor auth.js to use JWT instead of sessions, update all tests that import auth.js, and add rate limiting to the login endpoint in auth.js",expectedSubTasks:3,maxSubTasks:4},{id:"decompose_single",type:"decompose",prompt:"Fix the broken CSS on the login page \u2014 the submit button is not aligned",expectedSubTasks:1,maxSubTasks:4},{id:"synthesize_clean",type:"synthesize",prompt:"Fix login and search bugs",subResults:[{task:"Fix login redirect",status:"done",result:"Changed auth.js line 42: fixed redirect URL to use req.originalUrl instead of hardcoded /",toolsUsed:["read_file","edit_file"]},{task:"Fix search index",status:"done",result:"Added index on users.email column in migration 20260323. Updated search.js to use indexed query.",toolsUsed:["write_file","edit_file"]}],expectedConflicts:0},{id:"synthesize_conflicts",type:"synthesize",prompt:"Fix config loading and add env validation",subResults:[{task:"Fix config loading",status:"done",result:"Modified config.js: changed loadConfig() to handle missing .env gracefully",toolsUsed:["edit_file"]},{task:"Add env validation",status:"done",result:"Modified config.js: added validateEnv() function that throws on missing required vars",toolsUsed:["edit_file"]}],expectedConflicts:1}];function N0(t,e){if(!Array.isArray(t))return 0;let n=0;n+=1.5;let s=Math.abs(t.length-e.expectedSubTasks);s===0?n+=3:s===1&&(n+=1.5),t.every(c=>c.task&&typeof c.task=="string"&&c.task.length>0)&&(n+=2);let r=t.flatMap(c=>Array.isArray(c.scope)?c.scope:[]),i=new Set(r);return r.length===i.size&&(n+=2),t.every(c=>typeof c.estimatedCalls=="number"||typeof c.estimatedSshCalls=="number")&&(n+=1.5),Math.min(10,Math.round(n*10)/10)}function P0(t,e){if(!t||typeof t!="object")return 0;let n=0;n+=1.5,t.summary&&t.summary.length>10&&(n+=2),t.commitMessage&&t.commitMessage.length>5&&(n+=2);let s=Array.isArray(t.conflicts)?t.conflicts:[];return e.expectedConflicts===0&&s.length===0||e.expectedConflicts>0&&s.length>0?n+=2.5:e.expectedConflicts>0&&s.length===0&&(n+=0),Array.isArray(t.filesChanged)&&t.filesChanged.length>0&&(n+=2),Math.min(10,Math.round(n*10)/10)}async function L0(t,e){let n={};if(e){let o=NA(e);o.provider&&(n.provider=o.provider),o.model&&(n.model=o.model)}let s=Date.now();try{if(t.type==="decompose"){let o=PA.replace("{maxSubTasks}",String(t.maxSubTasks)).replace("{prompt}",t.prompt),r=await C0([{role:"system",content:o},{role:"user",content:t.prompt}],[],n),i=A0(r.content||""),a=Date.now()-s;return{score:N0(i,t),latencyMs:a}}if(t.type==="synthesize"){let o=t.subResults.map((d,f)=>{let p=d.status==="done"?"SUCCESS":"FAILED";return`--- Agent ${f+1} [${p}] ---
|
|
1538
1538
|
Task: ${d.task}
|
|
1539
1539
|
Result: ${d.result}
|
|
1540
1540
|
Tools: ${d.toolsUsed.join(", ")}`}).join(`
|
|
1541
1541
|
|
|
1542
|
-
`),r=LA.replace("{prompt}",t.prompt).replace("{results}",o),i=await C0([{role:"system",content:r},{role:"user",content:"Synthesize the sub-agent results above."}],[],n),a=A0(i.content||""),c=Date.now()-s;return{score:P0(a,t),latencyMs:c}}return{score:0,latencyMs:0,error:`Unknown scenario type: ${t.type}`}}catch(o){return{score:0,latencyMs:Date.now()-s,error:o.message}}}async function IA(t={}){let e=t.models||["kimi-k2.5","qwen3.5:397b","minimax-m2.7:cloud"],n=t.onProgress||(()=>{}),s=[];for(let r of e){let i={model:r,scores:[],latencies:[]},a=[],c=[];for(let m of M0){n({model:r,scenario:m.id,done:!1});let h=await L0(m,r);i.scores.push(h.score),i.latencies.push(h.latencyMs),m.type==="decompose"&&a.push(h.score),m.type==="synthesize"&&c.push(h.score),n({model:r,scenario:m.id,done:!0,score:h.score,error:h.error})}let u=a.length>0?a.reduce((m,h)=>m+h,0)/a.length:0,d=c.length>0?c.reduce((m,h)=>m+h,0)/c.length:0,f=i.latencies.reduce((m,h)=>m+h,0)/i.latencies.length,p=u*.6+d*.4;s.push({model:r,decompose:Math.round(u*10)/10,synthesize:Math.round(d*10)/10,avgLatency:Math.round(f),overall:Math.round(p*10)/10})}s.sort((r,i)=>i.overall-r.overall);let o=O0.dirname(pc);return
|
|
1542
|
+
`),r=LA.replace("{prompt}",t.prompt).replace("{results}",o),i=await C0([{role:"system",content:r},{role:"user",content:"Synthesize the sub-agent results above."}],[],n),a=A0(i.content||""),c=Date.now()-s;return{score:P0(a,t),latencyMs:c}}return{score:0,latencyMs:0,error:`Unknown scenario type: ${t.type}`}}catch(o){return{score:0,latencyMs:Date.now()-s,error:o.message}}}async function IA(t={}){let e=t.models||["kimi-k2.5","qwen3.5:397b","minimax-m2.7:cloud"],n=t.onProgress||(()=>{}),s=[];for(let r of e){let i={model:r,scores:[],latencies:[]},a=[],c=[];for(let m of M0){n({model:r,scenario:m.id,done:!1});let h=await L0(m,r);i.scores.push(h.score),i.latencies.push(h.latencyMs),m.type==="decompose"&&a.push(h.score),m.type==="synthesize"&&c.push(h.score),n({model:r,scenario:m.id,done:!0,score:h.score,error:h.error})}let u=a.length>0?a.reduce((m,h)=>m+h,0)/a.length:0,d=c.length>0?c.reduce((m,h)=>m+h,0)/c.length:0,f=i.latencies.reduce((m,h)=>m+h,0)/i.latencies.length,p=u*.6+d*.4;s.push({model:r,decompose:Math.round(u*10)/10,synthesize:Math.round(d*10)/10,avgLatency:Math.round(f),overall:Math.round(p*10)/10})}s.sort((r,i)=>i.overall-r.overall);let o=O0.dirname(pc);return Ed.existsSync(o)||Ed.mkdirSync(o,{recursive:!0}),Ed.writeFileSync(pc,JSON.stringify({date:new Date().toISOString().slice(0,10),results:s},null,2)),s}function DA(t){console.log(`
|
|
1543
1543
|
${Vt.bold}${Vt.cyan}Orchestrator Model Benchmark${Vt.reset}
|
|
1544
1544
|
`);let e=` ${"Model".padEnd(25)} ${"Decompose".padEnd(10)} ${"Synthesize".padEnd(11)} ${"Speed".padEnd(8)} ${"Score".padEnd(8)}`;console.log(`${Vt.dim}${e}${Vt.reset}`),console.log(` ${Vt.dim}${"\u2500".repeat(65)}${Vt.reset}`);for(let n of t){let s=t.indexOf(n)===0?"\u{1F947}":t.indexOf(n)===1?"\u{1F948}":t.indexOf(n)===2?"\u{1F949}":" ",o=`${(n.avgLatency/1e3).toFixed(1)}s`;console.log(`${s} ${n.model.padEnd(25)} ${(n.decompose+"/10").padEnd(10)} ${(n.synthesize+"/10").padEnd(11)} ${o.padEnd(8)} ${Vt.bold}${n.overall}/10${Vt.reset}`)}t.length>0&&(console.log(`
|
|
1545
1545
|
${Vt.green}Best orchestrator: ${t[0].model} (${t[0].overall}/10)${Vt.reset}`),console.log(` ${Vt.dim}Saved to ${pc}${Vt.reset}
|
|
1546
|
-
`))}I0.exports={runOrchestratorBenchmark:IA,ORCHESTRATOR_SCENARIOS:M0,scoreDecompose:N0,scoreSynthesize:P0,runScenario:L0,printResults:DA,RESULTS_PATH:pc}});var F0=K((kN,q0)=>{var jA=require("axios"),di=require("fs"),j0=require("path"),qA="nex-code",
|
|
1546
|
+
`))}I0.exports={runOrchestratorBenchmark:IA,ORCHESTRATOR_SCENARIOS:M0,scoreDecompose:N0,scoreSynthesize:P0,runScenario:L0,printResults:DA,RESULTS_PATH:pc}});var F0=K((kN,q0)=>{var jA=require("axios"),di=require("fs"),j0=require("path"),qA="nex-code",Td=j0.join(process.cwd(),".nex"),Rd=j0.join(Td,"last-version-check");di.existsSync(Td)||di.mkdirSync(Td,{recursive:!0});async function FA(){try{let t=UA(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};WA(e);let n=BA(),o=(await jA.get(`https://registry.npmjs.org/${qA}/latest`,{timeout:5e3})).data.version,r=HA(o,n);return{hasNewVersion:r,latestVersion:r?o:void 0,currentVersion:r?n:void 0}}catch{return{hasNewVersion:!1}}}function BA(){return lo().version}function UA(){try{if(di.existsSync(Rd)){let t=di.readFileSync(Rd,"utf8");return parseInt(t,10)}}catch{}return null}function WA(t){try{di.writeFileSync(Rd,t.toString())}catch{}}function HA(t,e){try{let n=t.split(".").map(Number),s=e.split(".").map(Number);return n[0]>s[0]?!0:n[0]<s[0]?!1:n[1]>s[1]?!0:n[1]<s[1]?!1:n[2]>s[2]}catch{return!1}}q0.exports={checkForNewVersion:FA}});var Id=K((TN,J0)=>{var YA=require("readline"),yt=require("fs"),ut=require("path"),{C:l,banner:GA,cleanupTerminal:B0}=Ye(),{isDark:KA}=Rt(),{listProviders:Ad,getActiveProviderName:no,listAllModels:EN,setFallbackChain:zA,getFallbackChain:XA,getProvider:VA}=We(),{flushAutoSave:U0}=$n(),{writeDreamLog:JA,shouldConsolidate:ZA,consolidate:QA}=pd(),{isDebug:eO}=nr(),{getActiveModel:Qn,setActiveModel:Od}=bo(),{printContext:W0}=Ta(),{loadAllSkills:tO,getSkillCommands:gc,handleSkillCommand:nO}=Wn(),{setReadlineInterface:sO,setAutoConfirm:oO,getAutoConfirm:hc,setAllowAlwaysHandler:rO}=_t(),{StickyFooter:iO}=K$(),dn=process.cwd(),je=null,kn=null;function H0(){return kn?.signal??null}var mi=[{cmd:"/help",desc:"Show full help"},{cmd:"/model",desc:"Show/switch model"},{cmd:"/providers",desc:"List providers and models"},{cmd:"/fallback",desc:"Show/set fallback chain"},{cmd:"/tokens",desc:"Token usage and context budget"},{cmd:"/costs",desc:"Session token costs"},{cmd:"/budget",desc:"Show/set cost limits per provider"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/context",desc:"Show project context"},{cmd:"/tree [depth]",desc:"Show project file tree (default depth 3)"},{cmd:"/autoconfirm",desc:"Toggle auto-confirm"},{cmd:"/save",desc:"Save session"},{cmd:"/load",desc:"Load a saved session"},{cmd:"/sessions",desc:"List saved sessions"},{cmd:"/resume",desc:"Resume last session"},{cmd:"/branches",desc:"Show session tree (all branches)"},{cmd:"/timeline",desc:"Show message timeline of current branch"},{cmd:"/goto <index>",desc:"Jump to a message index (truncates after)"},{cmd:"/fork [index]",desc:"Create branch at index (default: current)"},{cmd:"/switch-branch <name>",desc:"Switch to a different conversation branch"},{cmd:"/delete-branch <name>",desc:"Delete a conversation branch"},{cmd:"/remember",desc:"Save a memory"},{cmd:"/forget",desc:"Delete a memory"},{cmd:"/memory",desc:"Show all memories"},{cmd:"/brain",desc:"Manage knowledge base"},{cmd:"/brain add",desc:"Add document: /brain add <name> [content]"},{cmd:"/brain list",desc:"List all brain documents"},{cmd:"/brain search",desc:"Search brain: /brain search <query>"},{cmd:"/brain show",desc:"Show document: /brain show <name>"},{cmd:"/brain remove",desc:"Remove document: /brain remove <name>"},{cmd:"/brain rebuild",desc:"Rebuild keyword index"},{cmd:"/brain embed",desc:"Build/rebuild embedding index"},{cmd:"/brain status",desc:"Show brain status (docs, index, embeddings)"},{cmd:"/brain review",desc:"Review pending brain changes (git diff)"},{cmd:"/brain undo",desc:"Undo last brain write"},{cmd:"/learn",desc:"Reflect on session and update memory"},{cmd:"/optimize",desc:"Show optimization opportunities"},{cmd:"/permissions",desc:"Show tool permissions"},{cmd:"/allow",desc:"Auto-allow a tool"},{cmd:"/deny",desc:"Block a tool"},{cmd:"/plan",desc:"Plan mode (analyze before executing)"},{cmd:"/plan edit",desc:"Open current plan in $EDITOR"},{cmd:"/plans",desc:"List saved plans"},{cmd:"/auto",desc:"Set autonomy level"},{cmd:"/commit",desc:"Smart commit (diff + message)"},{cmd:"/diff",desc:"Show current diff"},{cmd:"/review [--strict] [file]",desc:"Deep code review with score table and diff suggestions (--strict: force \u22653 critical findings)"},{cmd:"/branch",desc:"Create feature branch"},{cmd:"/mcp",desc:"MCP servers and tools"},{cmd:"/mcp list",desc:"List connected MCP servers and their tools"},{cmd:"/mcp status",desc:"Show which MCP servers are running"},{cmd:"/hooks",desc:"Show configured hooks"},{cmd:"/skills",desc:"List, enable, disable skills"},{cmd:"/install-skill <url>",desc:"Install a skill from git URL or user/repo"},{cmd:"/search-skill <query>",desc:"Search for skills on GitHub"},{cmd:"/remove-skill <name>",desc:"Remove an installed skill"},{cmd:"/tasks",desc:"Show task list"},{cmd:"/servers",desc:"List server profiles / ping"},{cmd:"/docker",desc:"List containers across all servers"},{cmd:"/deploy",desc:"List deploy configs / run named deploy"},{cmd:"/benchmark [--quick] [--models=a,b]",desc:"Rank Ollama Cloud models on nex-code tool-calling tasks (--history for nightly log)"},{cmd:"/bench [--dry-run] [--model=<spec>]",desc:"Run scenario benchmark (5 agentic tasks)"},{cmd:"/trend [n]",desc:"Show score history trend (default: last 10 sessions)"},{cmd:"/init",desc:"Interactive setup wizard (.nex/)"},{cmd:"/setup",desc:"Configure provider and API keys"},{cmd:"/retry [--model <id>]",desc:"Retry last user turn (optionally with a different model)"},{cmd:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/snapshot [name]",desc:"Create a named git snapshot of current changes"},{cmd:"/restore [name|last]",desc:"Restore a previously created snapshot"},{cmd:"/orchestrate <prompt>",desc:"Decompose prompt into parallel sub-tasks, run, synthesize"},{cmd:"/bench-orchestrator",desc:"Benchmark models for orchestrator role"},{cmd:"/audit",desc:"Show tool execution audit log"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function Y0(){let t=gc(),e=[...mi,...t],n=Math.max(...e.map(s=>s.cmd.length));console.log("");for(let{cmd:s,desc:o}of mi)console.log(` ${l.cyan}${s.padEnd(n+2)}${l.reset}${l.dim}${o}${l.reset}`);for(let{cmd:s,desc:o}of t)console.log(` ${l.cyan}${s.padEnd(n+2)}${l.reset}${l.dim}${o} ${l.yellow}[skill]${l.reset}`);console.log(`
|
|
1547
1547
|
${l.dim}Type /help for detailed usage${l.reset}
|
|
1548
|
-
`)}function G0(t){try{let e,n;t.endsWith("/")||t.endsWith(ut.sep)?(e=t,n=""):(e=ut.dirname(t),n=ut.basename(t)),e.startsWith("~")&&(e=ut.join(require("os").homedir(),e.slice(1)));let s=ut.isAbsolute(e)?e:ut.resolve(dn,e);if(!yt.existsSync(s)||!yt.statSync(s).isDirectory())return[];let o=yt.readdirSync(s,{withFileTypes:!0}),r=[];for(let i of o){if(i.name.startsWith(".")||i.name==="node_modules"||n&&!i.name.startsWith(n))continue;let a=t.endsWith("/")||t.endsWith(ut.sep)?t:ut.dirname(t)+"/",c=a==="./"&&!t.startsWith("./")?i.name:a+i.name;r.push(i.isDirectory()?c+"/":c)}return r}catch{return[]}}function K0(t){if(t.startsWith("/")){let s=[...mi,...
|
|
1548
|
+
`)}function G0(t){try{let e,n;t.endsWith("/")||t.endsWith(ut.sep)?(e=t,n=""):(e=ut.dirname(t),n=ut.basename(t)),e.startsWith("~")&&(e=ut.join(require("os").homedir(),e.slice(1)));let s=ut.isAbsolute(e)?e:ut.resolve(dn,e);if(!yt.existsSync(s)||!yt.statSync(s).isDirectory())return[];let o=yt.readdirSync(s,{withFileTypes:!0}),r=[];for(let i of o){if(i.name.startsWith(".")||i.name==="node_modules"||n&&!i.name.startsWith(n))continue;let a=t.endsWith("/")||t.endsWith(ut.sep)?t:ut.dirname(t)+"/",c=a==="./"&&!t.startsWith("./")?i.name:a+i.name;r.push(i.isDirectory()?c+"/":c)}return r}catch{return[]}}function K0(t){if(t.startsWith("/")){let s=[...mi,...gc()],o=s.map(r=>r.cmd).filter(r=>r.startsWith(t));return[o.length?o:s.map(r=>r.cmd),t]}let e=t.split(/\s+/),n=e[e.length-1]||"";return n&&(n.includes("/")||n.startsWith("./")||n.startsWith("../")||n.startsWith("~"))?[G0(n),n]:[[],t]}function z0(){console.log(`
|
|
1549
1549
|
${l.bold}${l.cyan}Commands:${l.reset}
|
|
1550
1550
|
${l.cyan}/help${l.reset} ${l.dim}Show this help${l.reset}
|
|
1551
1551
|
${l.cyan}/model [spec]${l.reset} ${l.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${l.reset}
|
|
@@ -1618,20 +1618,20 @@ ${l.bold}${l.cyan}Undo / Redo:${l.reset}
|
|
|
1618
1618
|
${l.cyan}/benchmark --all --parallel=N${l.reset}${l.dim} Override concurrency (default 3)${l.reset}
|
|
1619
1619
|
|
|
1620
1620
|
${l.cyan}/exit${l.reset} ${l.dim}Quit${l.reset}
|
|
1621
|
-
`)}function X0(t){let n=Math.round(t/100*30),s=30-n;return` ${t>80?l.red:t>50?l.yellow:l.green}${"\u2588".repeat(n)}${l.dim}${"\u2591".repeat(s)}${l.reset} ${t}%`}function
|
|
1622
|
-
${l.bold}${l.cyan}Providers:${l.reset}`);for(let s of t){let o=s.provider===e,r=s.configured?`${l.green}\u2713${l.reset}`:`${l.red}\u2717${l.reset}`,i=o?` ${l.cyan}(active)${l.reset}`:"";console.log(` ${r} ${l.bold}${s.provider}${l.reset}${i}`);for(let a of s.models){let c=a.id===n.id&&o?` ${l.yellow}\u25C4${l.reset}`:"";console.log(` ${l.dim}${a.id}${l.reset} \u2014 ${a.name}${c}`)}}console.log()}async function hi(t,e){let[n,...s]=t.split(/\s+/);switch(n){case"/help":return z0(),!0;case"/model":{let o=s.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=V$();await r(e)}else{let r=Qn(),i=no();console.log(`${l.bold}${l.cyan}Active model:${l.reset} ${l.dim}${i}:${r.id} (${r.name})${l.reset}`),console.log(`${l.gray}Use /model <provider:model> to switch. /providers to see all.${l.reset}`)}return!0}if(o==="list")return
|
|
1621
|
+
`)}function X0(t){let n=Math.round(t/100*30),s=30-n;return` ${t>80?l.red:t>50?l.yellow:l.green}${"\u2588".repeat(n)}${l.dim}${"\u2591".repeat(s)}${l.reset} ${t}%`}function Cd(){let t=Ad(),e=no(),n=Qn();console.log(`
|
|
1622
|
+
${l.bold}${l.cyan}Providers:${l.reset}`);for(let s of t){let o=s.provider===e,r=s.configured?`${l.green}\u2713${l.reset}`:`${l.red}\u2717${l.reset}`,i=o?` ${l.cyan}(active)${l.reset}`:"";console.log(` ${r} ${l.bold}${s.provider}${l.reset}${i}`);for(let a of s.models){let c=a.id===n.id&&o?` ${l.yellow}\u25C4${l.reset}`:"";console.log(` ${l.dim}${a.id}${l.reset} \u2014 ${a.name}${c}`)}}console.log()}async function hi(t,e){let[n,...s]=t.split(/\s+/);switch(n){case"/help":return z0(),!0;case"/model":{let o=s.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=V$();await r(e)}else{let r=Qn(),i=no();console.log(`${l.bold}${l.cyan}Active model:${l.reset} ${l.dim}${i}:${r.id} (${r.name})${l.reset}`),console.log(`${l.gray}Use /model <provider:model> to switch. /providers to see all.${l.reset}`)}return!0}if(o==="list")return Cd(),!0;if(Od(o)){let r=Qn(),i=no();console.log(`${l.green}Switched to ${i}:${r.id} (${r.name})${l.reset}`)}else console.log(`${l.red}Unknown model: ${o}${l.reset}`),console.log(`${l.gray}Use /providers to see available models${l.reset}`);return!0}case"/providers":return Cd(),!0;case"/fallback":{let o=s.join(" ").trim();if(!o){let i=XA();return i.length===0?(console.log(`${l.dim}No fallback chain configured${l.reset}`),console.log(`${l.dim}Use /fallback anthropic,openai,local to set${l.reset}`)):console.log(`${l.bold}${l.cyan}Fallback chain:${l.reset} ${i.join(" \u2192 ")}`),!0}let r=o.split(",").map(i=>i.trim()).filter(Boolean);return zA(r),console.log(`${l.green}Fallback chain: ${r.join(" \u2192 ")}${l.reset}`),!0}case"/tokens":{let{getConversationMessages:o}=Se(),{getUsage:r}=Ht(),{TOOL_DEFINITIONS:i}=fn(),a=o(),c=r(a,i),u=Qn(),d=no();console.log(`
|
|
1623
1623
|
${l.bold}${l.cyan}Token Usage:${l.reset}`),console.log(` ${l.dim}Model:${l.reset} ${d}:${u.id} (${(c.limit/1e3).toFixed(0)}k context)`),console.log(` ${l.dim}Used:${l.reset} ${c.used.toLocaleString()} / ${c.limit.toLocaleString()} (${c.percentage}%)`);let f=X0(c.percentage);return console.log(` ${f}`),console.log(`
|
|
1624
1624
|
${l.dim}Breakdown:${l.reset}`),console.log(` System prompt: ${c.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${c.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${c.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${c.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${c.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:r}=wo();return s.join(" ").trim()==="reset"?(r(),console.log(`${l.green}Cost tracking reset${l.reset}`),!0):(console.log(`
|
|
1625
1625
|
${o()}
|
|
1626
|
-
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:i,removeCostLimit:a,saveCostLimits:c,setCostLimit:u}=wo(),d=s[0];if(!d){let m=o(),h=
|
|
1627
|
-
${l.bold}${l.cyan}Cost Limits:${l.reset}`);let g=!1;for(let $ of h){let w=r($.provider),k=m[$.provider];if(k!==void 0){g=!0;let E=Math.min(100,Math.round(w/k*100)),S=10,x=Math.round(E/100*S),C=S-x,q=`${E>=100?l.red:E>=80?l.yellow:l.green}${"\u2588".repeat(x)}${l.dim}${"\u2591".repeat(C)}${l.reset}`;console.log(` ${l.bold}${$.provider}:${l.reset} $${w.toFixed(2)} / $${k.toFixed(2)} (${E}%) ${q}`)}else $.provider==="ollama"||$.provider==="local"?console.log(` ${l.bold}${$.provider}:${l.reset} ${l.dim}free (no limit)${l.reset}`):w>0&&console.log(` ${l.bold}${$.provider}:${l.reset} $${w.toFixed(2)} ${l.dim}(no limit)${l.reset}`)}return g||console.log(` ${l.dim}No limits set. Use /budget <provider> <amount> to set one.${l.reset}`),console.log(),!0}let f=s[1];if(!f){let m=i(d);return m.limit!==null?console.log(`${l.bold}${d}:${l.reset} $${m.spent.toFixed(2)} / $${m.limit.toFixed(2)} ($${m.remaining.toFixed(2)} remaining)`):console.log(`${l.bold}${d}:${l.reset} $${m.spent.toFixed(2)} ${l.dim}(no limit)${l.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return a(d),c(),console.log(`${l.green}Removed cost limit for ${d}${l.reset}`),!0;let p=parseFloat(f);return isNaN(p)||p<=0?(console.log(`${l.red}Invalid amount: ${f}. Use a positive number or 'off'.${l.reset}`),!0):(u(d,p),c(),console.log(`${l.green}Set ${d} budget limit: $${p.toFixed(2)}${l.reset}`),!0)}case"/clear":{let{clearConversation:o,getConversationMessages:r}=Se(),{clearHistory:i}=Un(),a=r();if(a.filter(d=>d.role==="user").length>=4){process.stdout.write(`${l.dim}Reflecting on session...${l.reset} `);let{learnFromSession:d}=
|
|
1626
|
+
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:i,removeCostLimit:a,saveCostLimits:c,setCostLimit:u}=wo(),d=s[0];if(!d){let m=o(),h=Ad();console.log(`
|
|
1627
|
+
${l.bold}${l.cyan}Cost Limits:${l.reset}`);let g=!1;for(let $ of h){let w=r($.provider),k=m[$.provider];if(k!==void 0){g=!0;let E=Math.min(100,Math.round(w/k*100)),S=10,x=Math.round(E/100*S),C=S-x,q=`${E>=100?l.red:E>=80?l.yellow:l.green}${"\u2588".repeat(x)}${l.dim}${"\u2591".repeat(C)}${l.reset}`;console.log(` ${l.bold}${$.provider}:${l.reset} $${w.toFixed(2)} / $${k.toFixed(2)} (${E}%) ${q}`)}else $.provider==="ollama"||$.provider==="local"?console.log(` ${l.bold}${$.provider}:${l.reset} ${l.dim}free (no limit)${l.reset}`):w>0&&console.log(` ${l.bold}${$.provider}:${l.reset} $${w.toFixed(2)} ${l.dim}(no limit)${l.reset}`)}return g||console.log(` ${l.dim}No limits set. Use /budget <provider> <amount> to set one.${l.reset}`),console.log(),!0}let f=s[1];if(!f){let m=i(d);return m.limit!==null?console.log(`${l.bold}${d}:${l.reset} $${m.spent.toFixed(2)} / $${m.limit.toFixed(2)} ($${m.remaining.toFixed(2)} remaining)`):console.log(`${l.bold}${d}:${l.reset} $${m.spent.toFixed(2)} ${l.dim}(no limit)${l.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return a(d),c(),console.log(`${l.green}Removed cost limit for ${d}${l.reset}`),!0;let p=parseFloat(f);return isNaN(p)||p<=0?(console.log(`${l.red}Invalid amount: ${f}. Use a positive number or 'off'.${l.reset}`),!0):(u(d,p),c(),console.log(`${l.green}Set ${d} budget limit: $${p.toFixed(2)}${l.reset}`),!0)}case"/clear":{let{clearConversation:o,getConversationMessages:r}=Se(),{clearHistory:i}=Un(),a=r();if(a.filter(d=>d.role==="user").length>=4){process.stdout.write(`${l.dim}Reflecting on session...${l.reset} `);let{learnFromSession:d}=gd();d(a).then(f=>{if(!f.skipped&&!f.error&&(f.applied.length>0||f.nexAdded.length>0)){let p=f.applied.length+f.nexAdded.length;process.stdout.write(`${l.green}${p} learning(s) saved${l.reset}
|
|
1628
1628
|
`)}else process.stdout.write(`${l.dim}nothing new${l.reset}
|
|
1629
1629
|
`)}).catch(()=>process.stdout.write(`
|
|
1630
1630
|
`))}o(),i(),je=null;let{deleteSession:u}=$n();return u("_autosave"),console.log(`${l.green}Conversation cleared${l.reset}`),!0}case"/retry":{let{getConversationMessages:o,setConversationMessages:r,processInput:i}=Se(),a=o(),c=a.map(g=>g.role).lastIndexOf("user");if(c===-1)return console.log(`${l.yellow}Nothing to retry \u2014 no user message found.${l.reset}`),!0;let u=s.indexOf("--model"),d=u!==-1&&s[u+1]?s[u+1]:null;if(d){let{setActiveModel:g}=We();if(!g(d))return console.log(`${l.red}Unknown model: ${d}. Use /providers to see available models.${l.reset}`),!0;console.log(`${l.cyan}Switched to model: ${d}${l.reset}`)}let f=a[c],p;typeof f.content=="string"?p=f.content:Array.isArray(f.content)?p=f.content.filter(g=>g&&g.type==="text").map(g=>g.text).join(`
|
|
1631
1631
|
`):p=String(f.content),r(a.slice(0,c));let{resetSessionTracking:m}=Se();m();let h=d||"current model";return console.log(`${l.cyan}Retrying with ${h}...${l.reset}`),await i(p),!0}case"/context":return await W0(dn),!0;case"/tree":{let{generateFileTree:o}=Ta(),r=parseInt(s.join(" ").trim(),10),i=!isNaN(r)&&r>0?Math.min(r,8):3,a=o(dn,{maxDepth:i,maxFiles:300});return console.log(`
|
|
1632
1632
|
${l.bold}${l.cyan}Project tree${l.reset}${l.dim} (depth ${i})${l.reset}
|
|
1633
1633
|
`),console.log(`${l.dim}${a}${l.reset}
|
|
1634
|
-
`),!0}case"/autoconfirm":{let o=!
|
|
1634
|
+
`),!0}case"/autoconfirm":{let o=!hc();return oO(o),console.log(`${l.green}Auto-confirm: ${o?"ON":"OFF"}${l.reset}`),o&&console.log(`${l.yellow} \u26A0 File changes will be applied without confirmation${l.reset}`),fi(),!0}case"/save":{let{saveSession:o}=$n(),{getConversationMessages:r}=Se(),i=s.join(" ").trim()||`session-${Date.now()}`,a=r();if(a.length===0)return console.log(`${l.yellow}No conversation to save${l.reset}`),!0;let c=Qn(),u=no();return o(i,a,{model:c.id,provider:u}),console.log(`${l.green}Session saved: ${i} (${a.length} messages)${l.reset}`),!0}case"/load":{let{loadSession:o}=$n(),{setConversationMessages:r}=Se(),i=s.join(" ").trim();if(!i)return console.log(`${l.red}Usage: /load <name>${l.reset}`),!0;let a=o(i);return a?(r(a.messages),console.log(`${l.green}Loaded session: ${a.name} (${a.messageCount} messages)${l.reset}`),!0):(console.log(`${l.red}Session not found: ${i}${l.reset}`),!0)}case"/sessions":{let{listSessions:o}=$n(),r=o();if(r.length===0)return console.log(`${l.dim}No saved sessions${l.reset}`),!0;console.log(`
|
|
1635
1635
|
${l.bold}${l.cyan}Sessions:${l.reset}`);for(let i of r){let a=i.updatedAt?new Date(i.updatedAt).toLocaleString():"?",c=i.name==="_autosave"?` ${l.dim}(auto)${l.reset}`:"",u=i.score!=null?` \xB7 score ${i.score}/10${i.scoreGrade?` (${i.scoreGrade})`:""}`:"";console.log(` ${l.cyan}${i.name}${l.reset}${c} \u2014 ${i.messageCount} msgs, ${a}${l.dim}${u}${l.reset}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=$n(),{setConversationMessages:r}=Se(),i=o();return i?(r(i.messages),console.log(`${l.green}Resumed: ${i.name} (${i.messageCount} messages)${l.reset}`),!0):(console.log(`${l.yellow}No session to resume${l.reset}`),!0)}case"/branches":{let{initTree:o,renderTree:r}=gs(),{getConversationMessages:i}=Se(),a=i();return a.length===0?(console.log(`${l.yellow}No conversation yet${l.reset}`),!0):(je||(je=o({messages:a})),console.log(r(je)),console.log(),!0)}case"/timeline":{let{initTree:o,renderTimeline:r}=gs(),{getConversationMessages:i}=Se(),a=i();if(a.length===0)return console.log(`${l.yellow}No conversation yet${l.reset}`),!0;je||(je=o({messages:a})),gs().setActiveMessages(je,a);let u=parseInt(s[0],10)||20;return console.log(r(je,u)),console.log(),!0}case"/goto":{let o=gs(),{getConversationMessages:r,setConversationMessages:i}=Se(),a=r();if(a.length===0)return console.log(`${l.yellow}No conversation yet${l.reset}`),!0;let c=parseInt(s[0],10);if(isNaN(c))return console.log(`${l.red}Usage: /goto <message-index>${l.reset}`),console.log(`${l.dim}Use /timeline to see message indices${l.reset}`),!0;je||(je=o.initTree({messages:a})),o.setActiveMessages(je,a);try{let{truncated:u}=o.gotoMessage(je,c),d=o.getActiveMessages(je);i(d),console.log(`${l.green}Jumped to message ${c}. Removed ${u} later messages.${l.reset}`),console.log(`${l.dim}Conversation now has ${d.length} messages. Continue chatting from here.${l.reset}`)}catch(u){console.log(`${l.red}${u.message}${l.reset}`)}return!0}case"/fork":{let o=gs(),{getConversationMessages:r,setConversationMessages:i}=Se(),a=r();if(a.length===0)return console.log(`${l.yellow}No conversation yet${l.reset}`),!0;je||(je=o.initTree({messages:a})),o.setActiveMessages(je,a);let c=s[0]?parseInt(s[0],10):a.length-1,u=s[1]||void 0;if(isNaN(c))return console.log(`${l.red}Usage: /fork [message-index] [branch-name]${l.reset}`),!0;try{let{branchName:d}=o.createBranch(je,c,u),f=o.getActiveMessages(je);i(f),console.log(`${l.green}Created branch "${d}" forking at message ${c}${l.reset}`),console.log(`${l.dim}Now on branch "${d}" with ${f.length} messages. Continue chatting.${l.reset}`)}catch(d){console.log(`${l.red}${d.message}${l.reset}`)}return!0}case"/switch-branch":{let o=gs(),{getConversationMessages:r,setConversationMessages:i}=Se();if(!je){let c=r();je=o.initTree({messages:c})}o.setActiveMessages(je,r());let a=s.join(" ").trim();if(!a)return console.log(`${l.red}Usage: /switch-branch <name>${l.reset}`),console.log(`${l.dim}Available: ${Object.keys(je.branches).join(", ")}${l.reset}`),!0;try{o.switchBranch(je,a);let c=o.getActiveMessages(je);i(c),console.log(`${l.green}Switched to branch "${a}" (${c.length} messages)${l.reset}`)}catch(c){console.log(`${l.red}${c.message}${l.reset}`)}return!0}case"/delete-branch":{let o=gs();if(!je){let{getConversationMessages:i}=Se();je=o.initTree({messages:i()})}let r=s.join(" ").trim();if(!r)return console.log(`${l.red}Usage: /delete-branch <name>${l.reset}`),!0;try{o.deleteBranch(je,r),console.log(`${l.green}Deleted branch "${r}"${l.reset}`)}catch(i){console.log(`${l.red}${i.message}${l.reset}`)}return!0}case"/remember":{let{remember:o}=mn(),r=s.join(" ").trim();if(!r)return console.log(`${l.red}Usage: /remember <key>=<value> or /remember <text>${l.reset}`),!0;let i=r.indexOf("="),a,c;return i>0?(a=r.substring(0,i).trim(),c=r.substring(i+1).trim()):(a=r.substring(0,40).replace(/\s+/g,"-"),c=r),o(a,c),console.log(`${l.green}Remembered: ${a}${l.reset}`),!0}case"/forget":{let{forget:o}=mn(),r=s.join(" ").trim();return r?(o(r)?console.log(`${l.green}Forgotten: ${r}${l.reset}`):console.log(`${l.red}Memory not found: ${r}${l.reset}`),!0):(console.log(`${l.red}Usage: /forget <key>${l.reset}`),!0)}case"/memory":{let{listMemories:o}=mn(),r=o();if(r.length===0)return console.log(`${l.dim}No memories saved${l.reset}`),!0;console.log(`
|
|
1636
1636
|
${l.bold}${l.cyan}Memory:${l.reset}`);for(let i of r)console.log(` ${l.cyan}${i.key}${l.reset} = ${i.value}`);return console.log(),!0}case"/brain":{let{listDocuments:o,readDocument:r,writeDocument:i,removeDocument:a,buildIndex:c,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=xr(),p=s[0],m=s.slice(1).join(" ").trim();switch(p){case"add":{if(!m)return console.log(`${l.red}Usage: /brain add <name> [content]${l.reset}`),console.log(`${l.dim} /brain add api-notes \u2014 creates empty file${l.reset}`),console.log(`${l.dim} /brain add api-notes This is content \u2014 writes directly${l.reset}`),!0;let h=m.indexOf(" ");if(h<0){i(m,`# ${m}
|
|
1637
1637
|
|
|
@@ -1649,7 +1649,7 @@ ${l.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \
|
|
|
1649
1649
|
`);else{console.log(`
|
|
1650
1650
|
${l.bold}${l.cyan}Brain: ${h.length} document(s)${l.reset}`);for(let g of h){let{frontmatter:$}=r(g.name),w=Array.isArray($.tags)?` [${$.tags.join(", ")}]`:"";console.log(` ${l.cyan}${g.name}${l.reset}${l.dim}${w}${l.reset}`)}console.log(`
|
|
1651
1651
|
${l.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${l.reset}
|
|
1652
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=
|
|
1652
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=gd(),{getConversationMessages:i}=Se(),a=i(),c=a.filter(u=>u.role==="user").length;if(c<4)return console.log(`${l.yellow}Session too short to learn from (need 4+ user messages, have ${c})${l.reset}`),!0;console.log(`${l.dim}Analyzing session for learnings...${l.reset}`);try{let[u,d]=await Promise.all([o(a),r(a)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${l.dim}Session too short${l.reset}`),!0;u.error&&console.log(`${l.red}Reflection error: ${u.error}${l.reset}`),console.log(""),u.summary&&(console.log(`${l.bold}Session:${l.reset} ${l.dim}${u.summary}${l.reset}`),console.log(""));let f=u.applied&&u.applied.length>0,p=u.nexAdded&&u.nexAdded.length>0,m=d.written&&d.written.length>0;if(!f&&!p&&!m)console.log(`${l.dim}No new learnings extracted from this session${l.reset}`);else{if(f){console.log(`${l.bold}${l.cyan}Memory updates:${l.reset}`);for(let{key:h,value:g,action:$}of u.applied){let w=$==="updated"?`${l.yellow}~${l.reset}`:`${l.green}+${l.reset}`;console.log(` ${w} ${l.bold}${h}${l.reset} = ${g}`)}}if(p){console.log(`${l.bold}${l.cyan}Added to NEX.md:${l.reset}`);for(let h of u.nexAdded)console.log(` ${l.green}+${l.reset} ${h}`)}if(m){console.log(`${l.bold}${l.cyan}Brain documents:${l.reset}`);for(let{name:h,reason:g,action:$}of d.written){let w=$==="updated"?`${l.yellow}~${l.reset}`:`${l.green}+${l.reset}`;console.log(` ${w} ${l.bold}${h}.md${l.reset}${g?l.dim+" \u2014 "+g+l.reset:""}`)}}}console.log("")}catch(u){console.log(`${l.red}Learn failed: ${u.message}${l.reset}`)}return!0}case"/optimize":{let{getConversationMessages:o}=Se(),{getUsage:r}=Ht(),{TOOL_DEFINITIONS:i}=fn(),{listMemories:a}=mn(),c=o(),u=r(c,i),d=Qn(),f=no(),p=a();console.log(`
|
|
1653
1653
|
${l.bold}${l.cyan}Optimization Report${l.reset}
|
|
1654
1654
|
`);let m=u.percentage>80?l.red:u.percentage>50?l.yellow:l.green;if(console.log(`${l.bold}Context Window:${l.reset} ${m}${u.percentage}%${l.reset} used (${u.used.toLocaleString()} / ${u.limit.toLocaleString()} tokens)`),u.percentage>75?console.log(` ${l.yellow}\u2192 Tip: Use /clear to free context (auto-learns first)${l.reset}`):u.percentage>50?console.log(` ${l.dim}\u2192 Context is filling up, consider /clear soon${l.reset}`):console.log(` ${l.green}\u2192 Context healthy${l.reset}`),console.log(`
|
|
1655
1655
|
${l.bold}Memory:${l.reset} ${p.length} entries`),p.length===0)console.log(` ${l.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${l.reset}`);else{let E=[...p].sort((C,H)=>new Date(H.updatedAt)-new Date(C.updatedAt))[0],S=E?Math.round((Date.now()-new Date(E.updatedAt))/6e4):null,x=S!==null?S<60?`${S}m ago`:`${Math.round(S/60)}h ago`:"?";console.log(` ${l.dim}Latest update: ${x}${l.reset}`),p.length>30&&console.log(` ${l.yellow}\u2192 Many memories (${p.length}) \u2014 consider pruning with /forget${l.reset}`)}console.log(`
|
|
@@ -1668,7 +1668,7 @@ ${l.cyan}${l.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u
|
|
|
1668
1668
|
${l.bold}${l.cyan}Plans:${l.reset}`);for(let i of r){let a=i.status==="completed"?`${l.green}\u2713`:i.status==="executing"?`${l.blue}\u2192`:`${l.dim}\u25CB`;console.log(` ${a} ${l.reset}${l.bold}${i.name}${l.reset} \u2014 ${i.task||"?"} (${i.steps} steps, ${i.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:o,setAutonomyLevel:r,AUTONOMY_LEVELS:i}=wn(),a=s.join(" ").trim();return a?(r(a)?(console.log(`${l.green}Autonomy: ${a}${l.reset}`),fi()):console.log(`${l.red}Unknown level: ${a}. Use: ${i.join(", ")}${l.reset}`),!0):(console.log(`${l.bold}${l.cyan}Autonomy:${l.reset} ${o()}`),console.log(`${l.dim}Levels: ${i.join(", ")}${l.reset}`),!0)}case"/permissions":{let{listPermissions:o}=qr(),r=o();console.log(`
|
|
1669
1669
|
${l.bold}${l.cyan}Tool Permissions:${l.reset}`);for(let i of r){let a=i.mode==="allow"?`${l.green}\u2713`:i.mode==="deny"?`${l.red}\u2717`:`${l.yellow}?`;console.log(` ${a} ${l.reset}${l.bold}${i.tool}${l.reset} ${l.dim}(${i.mode})${l.reset}`)}return console.log(`
|
|
1670
1670
|
${l.dim}Use /allow <tool> or /deny <tool> to change${l.reset}
|
|
1671
|
-
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=qr(),i=s.join(" ").trim();return i?(o(i,"allow"),r(),console.log(`${l.green}${i}: allow${l.reset}`),!0):(console.log(`${l.red}Usage: /allow <tool>${l.reset}`),!0)}case"/deny":{let{setPermission:o,savePermissions:r}=qr(),i=s.join(" ").trim();return i?(o(i,"deny"),r(),console.log(`${l.red}${i}: deny${l.reset}`),!0):(console.log(`${l.red}Usage: /deny <tool>${l.reset}`),!0)}case"/audit":{let{getAuditSummary:o,isAuditEnabled:r}=
|
|
1671
|
+
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=qr(),i=s.join(" ").trim();return i?(o(i,"allow"),r(),console.log(`${l.green}${i}: allow${l.reset}`),!0):(console.log(`${l.red}Usage: /allow <tool>${l.reset}`),!0)}case"/deny":{let{setPermission:o,savePermissions:r}=qr(),i=s.join(" ").trim();return i?(o(i,"deny"),r(),console.log(`${l.red}${i}: deny${l.reset}`),!0):(console.log(`${l.red}Usage: /deny <tool>${l.reset}`),!0)}case"/audit":{let{getAuditSummary:o,isAuditEnabled:r}=lu();if(!r())return console.log(`${l.yellow}Audit logging is disabled (set NEX_AUDIT=true to enable)${l.reset}`),!0;let i=parseInt(s.join(" ").trim())||1,a=o(i);if(console.log(`
|
|
1672
1672
|
${l.bold}${l.cyan}Audit Summary (${i} day${i>1?"s":""})${l.reset}
|
|
1673
1673
|
`),console.log(` Total tool calls: ${l.bold}${a.totalCalls}${l.reset}`),console.log(` Avg duration: ${l.dim}${a.avgDuration}ms${l.reset}`),console.log(` Success rate: ${a.successRate>=.95?l.green:l.yellow}${Math.round(a.successRate*100)}%${l.reset}`),Object.keys(a.byTool).length>0){console.log(`
|
|
1674
1674
|
${l.dim}Tool${" ".repeat(25)}Count${l.reset}`),console.log(` ${l.dim}${"\u2500".repeat(35)}${l.reset}`);let c=Object.entries(a.byTool).sort((u,d)=>d[1]-u[1]);for(let[u,d]of c.slice(0,15))console.log(` ${u.padEnd(30)}${d}`)}return console.log(),!0}case"/commit":{let{isGitRepo:o,commit:r,analyzeDiff:i,formatDiffSummary:a}=rs(),{confirm:c}=_t();if(!o())return console.log(`${l.red}Not a git repository${l.reset}`),!0;let u=s.join(" ").trim();if(u){let h=await r(u);return console.log(h?`${l.green}Committed: ${h} \u2014 ${u}${l.reset}`:`${l.red}Commit failed${l.reset}`),!0}if(!i())return console.log(`${l.yellow}No changes to commit${l.reset}`),!0;let f=await a();if(console.log(f),!await c(" Commit changes?"))return!0;let m=await r("nex-code update");return m&&console.log(`${l.green} \u2713 Committed: ${m}${l.reset}`),!0}case"/diff":{let{isGitRepo:o,formatDiffSummary:r}=rs();return o()?(console.log(r()),!0):(console.log(`${l.red}Not a git repository${l.reset}`),!0)}case"/review":{let{isGitRepo:o,getDiff:r}=rs(),{processInput:i}=Se(),a=s.join(" ").trim(),c=a.includes("--strict"),u=a.replace("--strict","").trim(),f=`## Review Protocol
|
|
@@ -1719,7 +1719,7 @@ ${l.bold}${l.cyan}Connected MCP Servers:${l.reset}`),f.length===0&&console.log(`
|
|
|
1719
1719
|
${l.bold}${l.cyan}MCP Server Status:${l.reset}`);for(let h of f){let g=h.connected?`${l.green}\u2713 connected${l.reset}`:`${l.dim}\u25CB disconnected${l.reset}`;console.log(` ${g} ${l.bold}${h.name}${l.reset} (${h.command}) \u2014 ${h.toolCount} tools`)}for(let h of p)f.find(g=>g.name===h.name)||console.log(` ${l.green}\u2713 connected${l.reset} ${l.bold}${h.name}${l.reset} \u2014 ${h.toolCount} tools`);return console.log(),!0}if(u==="connect")return console.log(`${l.dim}Connecting MCP servers...${l.reset}`),r().then(f=>{for(let p of f)p.error?console.log(` ${l.red}\u2717${l.reset} ${p.name}: ${p.error}`):console.log(` ${l.green}\u2713${l.reset} ${p.name}: ${p.tools} tools`);f.length===0&&console.log(`${l.dim}No MCP servers configured in .nex/config.json${l.reset}`)}).catch(f=>{console.log(`${l.red}MCP connection error: ${f.message}${l.reset}`)}),!0;if(u==="disconnect")return i(),console.log(`${l.green}All MCP servers disconnected${l.reset}`),!0;let d=o();if(d.length===0)return console.log(`${l.dim}No MCP servers configured${l.reset}`),console.log(`${l.dim}Add servers to .nex/config.json under "mcpServers"${l.reset}`),!0;console.log(`
|
|
1720
1720
|
${l.bold}${l.cyan}MCP Servers:${l.reset}`);for(let f of d){let p=f.connected?`${l.green}\u2713 connected${l.reset}`:`${l.dim}\u25CB disconnected${l.reset}`;console.log(` ${p} ${l.bold}${f.name}${l.reset} (${f.command}) \u2014 ${f.toolCount} tools`)}return console.log(`
|
|
1721
1721
|
${l.dim}Use /mcp connect to connect all servers${l.reset}
|
|
1722
|
-
`),!0}case"/hooks":{let{listHooks:o}=
|
|
1722
|
+
`),!0}case"/hooks":{let{listHooks:o}=Au(),r=o();if(r.length===0)return console.log(`${l.dim}No hooks configured${l.reset}`),console.log(`${l.dim}Add hooks to .nex/config.json or .nex/hooks/${l.reset}`),!0;console.log(`
|
|
1723
1723
|
${l.bold}${l.cyan}Hooks:${l.reset}`);for(let i of r){console.log(` ${l.cyan}${i.event}${l.reset}`);for(let a of i.commands)console.log(` ${l.dim}\u2192 ${a}${l.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:o,enableSkill:r,disableSkill:i}=Wn(),a=s.join(" ").trim();if(a.startsWith("enable ")){let u=a.substring(7).trim();return r(u)?console.log(`${l.green}Skill enabled: ${u}${l.reset}`):console.log(`${l.red}Skill not found: ${u}${l.reset}`),!0}if(a.startsWith("disable ")){let u=a.substring(8).trim();return i(u)?console.log(`${l.yellow}Skill disabled: ${u}${l.reset}`):console.log(`${l.red}Skill not found: ${u}${l.reset}`),!0}let c=o();if(c.length===0)return console.log(`${l.dim}No skills loaded${l.reset}`),console.log(`${l.dim}Add .md or .js files to .nex/skills/${l.reset}`),!0;console.log(`
|
|
1724
1724
|
${l.bold}${l.cyan}Skills:${l.reset}`);for(let u of c){let d=u.enabled?`${l.green}\u2713${l.reset}`:`${l.red}\u2717${l.reset}`,f=u.type==="prompt"?`${l.dim}(prompt)${l.reset}`:`${l.dim}(script)${l.reset}`,p=[];u.commands>0&&p.push(`${u.commands} cmd`),u.tools>0&&p.push(`${u.tools} tools`);let m=p.length>0?` \u2014 ${p.join(", ")}`:"";console.log(` ${d} ${l.bold}${u.name}${l.reset} ${f}${m}`)}return console.log(`
|
|
1725
1725
|
${l.dim}Use /skills enable <name> or /skills disable <name>${l.reset}
|
|
@@ -1752,13 +1752,13 @@ ${l.bold}${l.cyan}Configured servers (${c.length}):${l.reset}`);for(let f of c)c
|
|
|
1752
1752
|
${l.dim}/servers ping \u2014 check SSH connectivity for all servers${l.reset}`),console.log(`${l.dim}/servers ping <name> \u2014 check a specific server${l.reset}
|
|
1753
1753
|
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=ko(),{exec:i}=require("child_process"),{promisify:a}=require("util"),c=a(i),u=s[0]==="-a"||s[0]==="--all"?'docker ps -a --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"':'docker ps --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"',d=o(),f=[["local",null],...Object.entries(d)];console.log(`
|
|
1754
1754
|
${l.bold}${l.cyan}Docker Containers:${l.reset}`);for(let[p,m]of f){let h=p==="local"?`${l.dim}local${l.reset}`:`${l.cyan}${p}${l.reset}`;try{let g;if(p==="local"){let{stdout:$}=await c(u,{timeout:8e3});g=($||"").trim()}else{let $=await r(m,u,{timeout:1e4});if(g=[$.stdout,$.stderr].filter(Boolean).join("").trim(),$.exitCode!==0){console.log(` ${h}: ${l.red}SSH error (${$.exitCode})${l.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${h}: ${l.dim}(no containers)${l.reset}`):(console.log(` ${h}:`),g.split(`
|
|
1755
|
-
`).forEach($=>console.log(` ${l.dim}${$}${l.reset}`)))}catch(g){console.log(` ${h}: ${l.red}${g.message}${l.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=
|
|
1755
|
+
`).forEach($=>console.log(` ${l.dim}${$}${l.reset}`)))}catch(g){console.log(` ${h}: ${l.red}${g.message}${l.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=xl(),r=o(),i=Object.keys(r),a=s[0];if(a&&i.includes(a)){let c=s.includes("--dry-run")||s.includes("-n"),u=r[a],{executeTool:d}=fn();console.log(`
|
|
1756
1756
|
${l.bold}Running deploy: ${a}${c?" (dry run)":""}${l.reset}`);let f=await d("deploy",{...u,dry_run:c});return console.log(f),!0}if(i.length===0)return console.log(`
|
|
1757
1757
|
${l.dim}No deploy configs. Run /init to create .nex/deploy.json${l.reset}
|
|
1758
1758
|
`),!0;console.log(`
|
|
1759
1759
|
${l.bold}${l.cyan}Deploy configs (${i.length}):${l.reset}`);for(let[c,u]of Object.entries(r)){let d=u.method||"rsync",f=`[${d}]`,p=d==="git"?`${u.server}:${u.remote_path}${u.branch?` (${u.branch})`:""}`:`${u.local_path||""} \u2192 ${u.server}:${u.remote_path}`,m=[u.deploy_script?`script: ${u.deploy_script}`:null,u.health_check?`health: ${u.health_check}`:null].filter(Boolean).map(h=>` ${l.dim}\u2192 ${h}${l.reset}`).join("");console.log(` ${l.green}${c}${l.reset} ${l.dim}${f} ${p}${l.reset}${m}`)}return console.log(`
|
|
1760
1760
|
${l.dim}/deploy <name> \u2014 run a named deploy${l.reset}`),console.log(`${l.dim}/deploy <name> --dry-run \u2014 preview without syncing${l.reset}
|
|
1761
|
-
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:i}=m0();return i(e),s[0]==="deploy"?await r():await o(),!0}case"/setup":{let{runSetupWizard:o}=
|
|
1761
|
+
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:i}=m0();return i(e),s[0]==="deploy"?await r():await o(),!0}case"/setup":{let{runSetupWizard:o}=ld();return await o({rl:e,force:!0}),!0}case"/benchmark":{try{let $=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(yt.existsSync($)){let w=(Date.now()-yt.statSync($).mtimeMs)/864e5;w>30&&console.log(`${l.dim} \u2139 Benchmark results are ${Math.floor(w)} days old \u2014 run /benchmark --all to refresh${l.reset}
|
|
1762
1762
|
`)}}catch{}if(s.includes("--history")){let $=require("os"),w=ut.join($.homedir(),"Coding","nex-code-benchmarks","results");if(!yt.existsSync(w)){console.log(`${l.yellow}No nightly results at ${w}${l.reset}`),console.log(`${l.dim}Use /benchmark (no flags) to run a live model comparison.${l.reset}`);break}let k=yt.readdirSync(w).filter(S=>S.endsWith(".json")).sort().slice(-7);if(k.length===0){console.log(`${l.yellow}No result files found${l.reset}`);break}console.log(`
|
|
1763
1763
|
${l.bold}${l.cyan}OpenClaw Nightly Results (${k.length}-day trend)${l.reset}
|
|
1764
1764
|
`),console.log(` ${l.dim}${"Date".padEnd(12)} ${"Model".padEnd(25)} ${"Score".padEnd(8)} ${"Pass".padEnd(8)}${l.reset}`),console.log(` ${l.dim}${"\u2500".repeat(58)}${l.reset}`);let E=[];for(let S of k)try{let x=JSON.parse(yt.readFileSync(ut.join(w,S),"utf-8")),C=S.replace(".json",""),H=x.tasks?.length||x.total||0,q=x.tasks?.filter(T=>T.passed||T.score>=.7)?.length||x.passed||0,ie=x.score??x.overall_score??(H>0?Math.round(q/H*100):"N/A"),le=x.model||x.config?.model||"unknown";E.push({date:C,model:le,total:H,passed:q,score:ie});let te=typeof ie=="number"?ie>=80?l.green:ie>=60?l.yellow:l.red:l.dim;console.log(` ${C.padEnd(12)} ${le.substring(0,24).padEnd(25)} ${te}${String(ie).padEnd(8)}${l.reset} ${q}/${H}`)}catch{}if(E.length>=2){let S=E[0].score,x=E[E.length-1].score;if(typeof S=="number"&&typeof x=="number"){let C=x-S,H=C>0?`${l.green}\u25B2 +${C}`:C<0?`${l.red}\u25BC ${C}`:`${l.dim}\u2192 stable`;console.log(`
|
|
@@ -1782,12 +1782,12 @@ ${l.bold}Scenario Benchmark${l.reset} ${l.dim}5 agentic scenarios \xB7 each run
|
|
|
1782
1782
|
`),await o({dryRun:r,model:a,cwd:dn,onProgress:({id:c,name:u,done:d,score:f,grade:p})=>{if(!d)process.stdout.write(`${l.dim} \u2192 ${u}...${l.reset}`);else{let m=f>=8?l.green:f>=6?l.yellow:l.red;process.stdout.write(` ${m}${f}/10 (${p})${l.reset}
|
|
1783
1783
|
`)}}}),!0}case"/trend":{let{showScoreTrend:o}=$s(),r=parseInt(s[0],10)||10;return o(r),!0}case"/orchestrate":{let o=s.join(" ").trim();if(!o)return console.log(`${l.yellow}Usage: /orchestrate <prompt>${l.reset}`),console.log(`${l.dim}Example: /orchestrate fix login bug, update docs, add dark mode${l.reset}`),!0;let{runOrchestrated:r}=Br();return await r(o),!0}case"/bench-orchestrator":{let{runOrchestratorBenchmark:o,printResults:r}=D0(),i=s.find(u=>u.startsWith("--models=")),a=i?i.replace("--models=","").split(",").map(u=>u.trim()):void 0,c=await o({models:a,onProgress:({model:u,scenario:d,done:f,score:p,error:m})=>{f?m?process.stdout.write(` ${l.red}ERR${l.reset}
|
|
1784
1784
|
`):process.stdout.write(` ${l.green}${p}/10${l.reset}
|
|
1785
|
-
`):process.stdout.write(`${l.dim} \u2192 ${u}: ${d}...${l.reset}`)}});return r(c),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:{let o=nO(t);if(o)return o.agentPrompt&&(hi._pendingAgentPrompt=o.agentPrompt),!0;{let r=[...mi,...
|
|
1786
|
-
`).filter(Boolean).slice(-
|
|
1787
|
-
`)}catch{}}function Jt(){return`${l.bold}${l.cyan}\u203A${l.reset} `}function fi(){if(!global._nexFooter)return;let{isPlanMode:t,getAutonomyLevel:e}=wn(),{getAutoConfirm:n}=_t(),s=[];t()&&s.push("plan");let o=e();o==="semi-auto"&&s.push("semi"),o==="autonomous"&&s.push("auto"),n()&&s.push("always"),global._nexFooter.setStatusInfo({mode:s.join(" \xB7 ")})}var
|
|
1785
|
+
`):process.stdout.write(`${l.dim} \u2192 ${u}: ${d}...${l.reset}`)}});return r(c),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:{let o=nO(t);if(o)return o.agentPrompt&&(hi._pendingAgentPrompt=o.agentPrompt),!0;{let r=[...mi,...gc()].map(u=>u.cmd.split(" ")[0]),i=(u,d)=>{let f=u.length,p=d.length,m=Array.from({length:f+1},(h,g)=>Array.from({length:p+1},($,w)=>g===0?w:w===0?g:0));for(let h=1;h<=f;h++)for(let g=1;g<=p;g++)m[h][g]=u[h-1]===d[g-1]?m[h-1][g-1]:1+Math.min(m[h-1][g],m[h][g-1],m[h-1][g-1]);return m[f][p]},a=null,c=3;for(let u of r){let d=i(n,u);d<c&&(c=d,a=u)}console.log(a?`${l.red}Unknown command: ${n}.${l.reset} ${l.dim}Did you mean ${l.reset}${l.cyan}${a}${l.reset}${l.dim}? Type /help for all commands.${l.reset}`:`${l.red}Unknown command: ${n}. Type /help${l.reset}`)}return!0}}}var Md=1e3;function Nd(){return ut.join(process.cwd(),".nex","repl_history")}function V0(){try{let t=Nd();if(yt.existsSync(t))return yt.readFileSync(t,"utf-8").split(`
|
|
1786
|
+
`).filter(Boolean).slice(-Md)}catch{}return[]}function mc(t){try{let e=Nd(),n=ut.dirname(e);yt.existsSync(n)||yt.mkdirSync(n,{recursive:!0}),yt.appendFileSync(e,t+`
|
|
1787
|
+
`)}catch{}}function Jt(){return`${l.bold}${l.cyan}\u203A${l.reset} `}function fi(){if(!global._nexFooter)return;let{isPlanMode:t,getAutonomyLevel:e}=wn(),{getAutoConfirm:n}=_t(),s=[];t()&&s.push("plan");let o=e();o==="semi-auto"&&s.push("semi"),o==="autonomous"&&s.push("auto"),n()&&s.push("always"),global._nexFooter.setStatusInfo({mode:s.join(" \xB7 ")})}var Pd="\x1B[200~",Ld="\x1B[201~";function aO(t){return typeof t=="string"&&t.includes(Pd)}function cO(t){return typeof t=="string"&&t.includes(Ld)}function pi(t){return typeof t!="string"?t:t.split(Pd).join("").split(Ld).join("")}async function lO(){if(!VA("local"))return!1;try{let{exec:e}=require("child_process"),{promisify:n}=require("util");return await n(e)("curl -s --max-time 1 http://localhost:11434/api/tags"),Od("local:llama3"),!0}catch{return!1}}async function uO(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:n}=Se();t(H0);let o=Ad().some(N=>N.configured),r=(async()=>{tO();let N=Qn(),Z=no();return{model:N,providerName:Z}})(),i=(async()=>o?!0:await lO()?(console.log(`${l.green}\u2713 Local Ollama detected \u2014 using local models${l.reset}`),console.log(`${l.dim}Tip: Set API keys for cloud providers for more model options (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${l.reset}
|
|
1788
1788
|
`),!0):!1)(),a=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:N}=F0();return await N()}catch{return{hasNewVersion:!1}}})(),[c,u,d]=await Promise.all([r,i,a]);!u&&!o&&(console.error(`
|
|
1789
1789
|
${l.red}\u2717 No provider configured and no local Ollama detected.${l.reset}
|
|
1790
|
-
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:p}=Un();f().then(N=>{}),p().catch(()=>{});let m=V0(),h=YA.createInterface({input:process.stdin,output:process.stdout,prompt:Jt(),completer:K0,history:m,historySize:
|
|
1790
|
+
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:p}=Un();f().then(N=>{}),p().catch(()=>{});let m=V0(),h=YA.createInterface({input:process.stdin,output:process.stdout,prompt:Jt(),completer:K0,history:m,historySize:Md});sO(h);let{setAskUserHandler:g}=fn();g(async(N,Z)=>{let{T:ne}=Rt(),Q=ne.reset,ge=ne.bold,ke=ne.dim,pe=ne.cyan,qe=ne.yellow;return process.stdout.write(`
|
|
1791
1791
|
${ge}${qe}\u2753${Q} ${ge}${N}${Q}
|
|
1792
1792
|
|
|
1793
1793
|
`),Z.forEach((Pe,$t)=>{process.stdout.write(` ${pe}${$t+1}${Q} ${Pe}
|
|
@@ -1796,34 +1796,34 @@ ${l.red}\u2717 No provider configured and no local Ollama detected.${l.reset}
|
|
|
1796
1796
|
${pe}[1-${Z.length+1}]${Q} \u203A `),new Promise(Pe=>{h.resume(),h.once("line",$t=>{let Ue=$t.trim(),kt=parseInt(Ue);kt>=1&&kt<=Z.length?(process.stdout.write(`
|
|
1797
1797
|
`),Pe(Z[kt-1])):kt===Z.length+1||Ue===""?(process.stdout.write(` ${pe}\u203A${Q} `),h.once("line",ws=>{process.stdout.write(`
|
|
1798
1798
|
`),Pe(ws.trim()||"")})):(process.stdout.write(`
|
|
1799
|
-
`),Pe(Ue))})})});let $=new iO;$.activate(h),global._nexFooter=$,global._nexRawWrite=N=>$.rawWrite(N),rO(()=>fi()),process.stdout.isTTY&&process.stdout.write("\x1B[H\x1B[2J\x1B[3J");let w=c.providerName==="ollama"?c.model.id:`${c.providerName}:${c.model.id}`;GA(w,dn,{yolo:
|
|
1799
|
+
`),Pe(Ue))})})});let $=new iO;$.activate(h),global._nexFooter=$,global._nexRawWrite=N=>$.rawWrite(N),rO(()=>fi()),process.stdout.isTTY&&process.stdout.write("\x1B[H\x1B[2J\x1B[3J");let w=c.providerName==="ollama"?c.model.id:`${c.providerName}:${c.model.id}`;GA(w,dn,{yolo:hc()});{$.setStatusInfo({model:w,branch:"",project:ut.basename(dn)});let{execFile:N}=require("child_process");N("git",["rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"},(Z,ne)=>{!Z&&ne&&$.setStatusInfo({model:w,branch:ne.trim(),project:ut.basename(dn)})})}d.hasNewVersion&&console.log(`${l.yellow}\u{1F4A1} New version available!${l.reset} Run ${l.cyan}npm update -g nex-code${l.reset} to upgrade from ${l.dim}${d.currentVersion}${l.reset} to ${l.green}${d.latestVersion}${l.reset}
|
|
1800
1800
|
`),await W0(dn),setTimeout(()=>{try{if(ZA()){let{insights:N}=QA();N.length>0&&eO()&&process.stdout.write(`${l.dim}\u{1F4AD} Dream consolidated ${N.length} insight(s) from recent sessions${l.reset}
|
|
1801
1801
|
`)}}catch{}},2e3);let k=!1,E=0,S=!1,x=null;function C(){U0();try{let{getConversationMessages:N}=Se();JA(N())}catch{}$.deactivate(),B0(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)}process.on("SIGTERM",C),process.on("exit",()=>{U0()}),h.on("SIGINT",()=>{if(B0(),E++,E>=2){C();return}if(k){kn&&kn.abort();let{cancelPendingAskUser:N}=fn();N(),console.log(`
|
|
1802
1802
|
${l.yellow} Task cancelled. Press Ctrl+C again to exit.${l.reset}`),k=!1,h.setPrompt(Jt()),h.prompt()}else console.log(`${l.dim} (Press Ctrl+C again to exit)${l.reset}`),h.setPrompt(Jt()),h.prompt(),x&&clearTimeout(x),x=setTimeout(()=>{E=0,x=null},2e3)}),process.on("SIGINT",()=>{process.stdin.isTTY?(E++,E>=2&&C()):C()});let H=!1,q=[],ie=0,le={},te=!1;function T(){let N=q.join(`
|
|
1803
1803
|
`).replace(/\r/g,"").trim();if(q=[],H=!1,!N)return!0;ie++,te=!0;let Z=ie;le[Z]=N;let ne=N.split(`
|
|
1804
|
-
`).length,Q=ne>1?`[Pasted content #${Z} \u2014 ${ne} lines]`:`[Pasted content #${Z}]`,ge=h.line||"",ke=ge&&!ge.endsWith(" ")?" ":"",pe=ge+ke+Q;return h.setPrompt(Jt()),h.prompt(),h.line=pe,h.cursor=pe.length,h._refreshLine(),!0}function Te(N){return N.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(Z,ne)=>le[Number(ne)]||"")}function G(){ie=0,le={},te=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let N=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(Z,...ne){if(Z!=="data")return N.call(process.stdin,Z,...ne);let Q=ne[0];if(Buffer.isBuffer(Q)&&(Q=Q.toString("utf8")),typeof Q!="string")return N.call(process.stdin,Z,...ne);let ge=Q.includes(
|
|
1804
|
+
`).length,Q=ne>1?`[Pasted content #${Z} \u2014 ${ne} lines]`:`[Pasted content #${Z}]`,ge=h.line||"",ke=ge&&!ge.endsWith(" ")?" ":"",pe=ge+ke+Q;return h.setPrompt(Jt()),h.prompt(),h.line=pe,h.cursor=pe.length,h._refreshLine(),!0}function Te(N){return N.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(Z,ne)=>le[Number(ne)]||"")}function G(){ie=0,le={},te=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let N=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(Z,...ne){if(Z!=="data")return N.call(process.stdin,Z,...ne);let Q=ne[0];if(Buffer.isBuffer(Q)&&(Q=Q.toString("utf8")),typeof Q!="string")return N.call(process.stdin,Z,...ne);let ge=Q.includes(Pd),ke=Q.includes(Ld);if(ge&&ke){let pe=pi(Q);return pe&&q.push(...pe.split(`
|
|
1805
1805
|
`)),T()}if(ge){H=!0,q=[];let pe=pi(Q);return pe&&q.push(...pe.split(`
|
|
1806
1806
|
`)),!0}if(ke){let pe=pi(Q);return pe&&q.push(...pe.split(`
|
|
1807
1807
|
`)),T()}if(H){let pe=pi(Q);return pe&&q.push(...pe.split(`
|
|
1808
1808
|
`)),!0}return Q.includes(`
|
|
1809
1809
|
`)&&Q.length>40&&!H?(q.push(...Q.replace(/\r/g,"").split(`
|
|
1810
|
-
`)),T()):N.call(process.stdin,Z,...ne)}}let z=0,fe=-1,Ee=[],Ae="";function ve(){if(z>0){let N=$._scrollEnd,Z="\x1B7";for(let ne=0;ne<z;ne++)Z+=`\x1B[${N-z+1+ne};1H\x1B[2K`;Z+="\x1B8",$.rawWrite(Z),z=0}}function be(){ve(),fe=-1,Ee=[],Ae=""}function v(N,Z=-1){let ne=[...mi,...
|
|
1811
|
-
${ge}. `).trim()}let{loadSession:M}=$n(),{setConversationMessages:R}=Se();if(e()===0){let N=M("_autosave");if(N&&N.messages&&N.messages.length>0&&Date.now()-new Date(N.updatedAt).getTime()<1440*60*1e3){let{confirm:ne}=_t();if(await ne("Previous session found. Resume?")){let ke=N.messages,pe=ke.length>20?ke.slice(-20):ke;R(pe);let{getUsage:qe,forceCompress:Pe}=Ht();if(qe(pe,[]).percentage>=30){let{messages:Ue}=Pe(pe,[]);R(Ue)}}}}h.setPrompt(Jt()),h.prompt(),h.on("line",async N=>{if(be(),Object.keys(le).length>0&&(N=Te(N),G(),h.setPrompt(Jt())),k){let ge=N.trim();if(ge){let{injectMidRunNote:ke}=Se();ke(ge),process.stdout.write(`${l.cyan} \u270E Queued \u2014 will be applied in the next step${l.reset}
|
|
1810
|
+
`)),T()):N.call(process.stdin,Z,...ne)}}let z=0,fe=-1,Ee=[],Ae="";function ve(){if(z>0){let N=$._scrollEnd,Z="\x1B7";for(let ne=0;ne<z;ne++)Z+=`\x1B[${N-z+1+ne};1H\x1B[2K`;Z+="\x1B8",$.rawWrite(Z),z=0}}function be(){ve(),fe=-1,Ee=[],Ae=""}function v(N,Z=-1){let ne=[...mi,...gc()].filter(Ue=>Ue.cmd.startsWith(N));if(!ne.length||ne.length===1&&ne[0].cmd===N&&Z<0)return;let Q=$._scrollEnd,ge=Math.min(10,Q-2);if(ge<1)return;let ke=ne.slice(0,ge),pe=Math.max(...ke.map(Ue=>Ue.cmd.length));z=ke.length,Ee=ne,Ae=N,ne.length>ge&&z++;let qe=Q-z+1,Pe="\x1B7",$t=($._cols||80)-1;for(let Ue=0;Ue<ke.length;Ue++){let{cmd:kt,desc:ws}=ke[Ue],Zo=Math.max(0,pe-kt.length+2),gi=2+kt.length+Zo,es=ws;if(gi+ws.length>$t){let Dn=Math.max(0,$t-gi-3);Dn>0?es=ws.substring(0,Dn)+"...":(es="",Zo=1)}let yi=" ".repeat(Zo);if(Ue===Z)Pe+=`\x1B[${qe+Ue};1H\x1B[2K \x1B[7m ${l.bold}${kt}${l.reset}\x1B[7m${yi}${es}\x1B[27m${l.reset}`;else{let Dn=kt.substring(0,N.length),wc=kt.substring(N.length);Pe+=`\x1B[${qe+Ue};1H\x1B[2K ${l.cyan}${Dn}${l.reset}${l.dim}${wc}${yi}${es}${l.reset}`}}ne.length>ge&&(Pe+=`\x1B[${qe+ke.length};1H\x1B[2K ${l.dim}\u2026 +${ne.length-ge} more${l.reset}`),Pe+="\x1B8",$.rawWrite(Pe)}if(process.stdin.isTTY){let N=h._ttyWrite.bind(h),Z=!1;h._ttyWrite=function(ne,Q){if(Z)return N(ne,Q);if(z>0&&Q&&!Q.ctrl&&!Q.meta){let ge=Math.min(Ee.length,10)-1;if(Q.name==="down"){fe=Math.min(fe+1,ge),Z=!0,h.write(null,{ctrl:!0,name:"u"}),h.write(fe>=0?Ee[fe].cmd:Ae),Z=!1,ve(),v(Ae,fe);return}if(Q.name==="up"){if(fe===-1)fe=Math.min(Ee.length,10)-1;else if(fe>0)fe--;else{fe=-1,Z=!0,h.write(null,{ctrl:!0,name:"u"}),h.write(Ae),Z=!1,ve(),v(Ae,-1);return}Z=!0,h.write(null,{ctrl:!0,name:"u"}),h.write(Ee[fe].cmd),Z=!1,ve(),v(Ae,fe);return}}return N(ne,Q)},process.stdin.on("keypress",(ne,Q)=>{z>0&&Q&&(Q.name==="down"||Q.name==="up")||(be(),!(Q&&(Q.name==="tab"||Q.name==="return"))&&setImmediate(()=>{h.line&&h.line.startsWith("/")&&v(h.line,-1)}))})}let L=null,O=`${l.dim}...${l.reset} `;function D(N){return(N.match(/[^\s\d](\d{1,2})\.\s+\S/g)||[]).length<2?N:N.replace(/([^\s\d])(\d{1,2})\.\s+/g,(ne,Q,ge)=>`${Q}
|
|
1811
|
+
${ge}. `).trim()}let{loadSession:M}=$n(),{setConversationMessages:R}=Se();if(e()===0&&!hc()){let N=M("_autosave");if(N&&N.messages&&N.messages.length>0&&Date.now()-new Date(N.updatedAt).getTime()<1440*60*1e3){let{confirm:ne}=_t();if(await ne("Previous session found. Resume?")){let ke=N.messages,pe=ke.length>20?ke.slice(-20):ke;R(pe);let{getUsage:qe,forceCompress:Pe}=Ht();if(qe(pe,[]).percentage>=30){let{messages:Ue}=Pe(pe,[]);R(Ue)}}}}h.setPrompt(Jt()),h.prompt(),h.on("line",async N=>{if(be(),Object.keys(le).length>0&&(N=Te(N),G(),h.setPrompt(Jt())),k){let ge=N.trim();if(ge){let{injectMidRunNote:ke}=Se();ke(ge),process.stdout.write(`${l.cyan} \u270E Queued \u2014 will be applied in the next step${l.reset}
|
|
1812
1812
|
`),h.prompt()}return}if(L!==null){if(L._mode==="triple"){if(N.trim()==='"""'){let ge=L.join(`
|
|
1813
|
-
`).trim();if(L=null,ge){
|
|
1813
|
+
`).trim();if(L=null,ge){mc(ge.replace(/\n/g,"\\n")),k=!0,h.prompt(),E=0,S=!1,x&&(clearTimeout(x),x=null),kn=new AbortController;try{await n(ge)}catch(pe){if(!kn?.signal?.aborted){let qe=pe.message?.split(`
|
|
1814
1814
|
`)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${qe}${l.reset}`)}}k=!1;let ke=ne();ke>0&&process.stdout.write(`${l.gray}[${ke} messages] ${l.reset}`)}h.setPrompt(Jt()),h.prompt();return}L.push(N),h.setPrompt(O),h.prompt();return}if(N.endsWith("\\"))L.push(N.slice(0,-1));else{L.push(N);let ge=L.join(`
|
|
1815
|
-
`).trim();if(L=null,ge){
|
|
1816
|
-
`)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${Pe}${l.reset}`)}}let{getConversationLength:ke}=Se();k=!1;let pe=ke();pe>0&&process.stdout.write(`${l.gray}[${pe} messages] ${l.reset}`)}h.setPrompt(Jt()),h.prompt();return}h.setPrompt(O),h.prompt();return}if(N.trim()==='"""'||N.trim().startsWith('"""')){let ge=N.trim().substring(3);L=ge?[ge]:[],L._mode="triple",h.setPrompt(O),h.prompt();return}if(N.endsWith("\\")){L=[N.slice(0,-1)],L._mode="backslash",h.setPrompt(O),h.prompt();return}let Z=D(N.trim());if(!Z){h.setPrompt(Jt()),h.prompt();return}if(
|
|
1815
|
+
`).trim();if(L=null,ge){mc(ge.replace(/\n/g,"\\n")),k=!0,h.prompt(),E=0,S=!1,x&&(clearTimeout(x),x=null),kn=new AbortController;try{await n(ge)}catch(qe){if(!kn?.signal?.aborted){let Pe=qe.message?.split(`
|
|
1816
|
+
`)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${Pe}${l.reset}`)}}let{getConversationLength:ke}=Se();k=!1;let pe=ke();pe>0&&process.stdout.write(`${l.gray}[${pe} messages] ${l.reset}`)}h.setPrompt(Jt()),h.prompt();return}h.setPrompt(O),h.prompt();return}if(N.trim()==='"""'||N.trim().startsWith('"""')){let ge=N.trim().substring(3);L=ge?[ge]:[],L._mode="triple",h.setPrompt(O),h.prompt();return}if(N.endsWith("\\")){L=[N.slice(0,-1)],L._mode="backslash",h.setPrompt(O),h.prompt();return}let Z=D(N.trim());if(!Z){h.setPrompt(Jt()),h.prompt();return}if(mc(Z),Z==="/"){Y0(),h.setPrompt(Jt()),h.prompt();return}if(Z.startsWith("/")){await hi(Z,h);let ge=hi._pendingAgentPrompt;if(ge){hi._pendingAgentPrompt=null;try{let{isPlanMode:ke,setPlanMode:pe}=wn(),{invalidateSystemPromptCache:qe}=Se();ke()&&(pe(!1),qe())}catch{}k=!0,h.prompt(),E=0,S=!1,x&&(clearTimeout(x),x=null),kn=new AbortController;try{await n(ge,null,{autoOrchestrate:!1,skipPhaseRouting:!0,skillLoop:!0,maxIterations:200})}catch(ke){if(!kn?.signal?.aborted){let pe=ke.message?.split(`
|
|
1817
1817
|
`)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${pe}${l.reset}`)}}k=!1}h.setPrompt(Jt()),h.prompt();return}{let ge=KA?"\x1B[48;5;237m":"\x1B[48;2;220;225;235m",ke=process.stdout.columns||80,pe=Z.split(`
|
|
1818
|
-
`);process.stdout.isTTY&&process.stdout.write(`\x1B[${pe.length}A`),pe.forEach((qe,Pe)=>{let $t=Pe===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",Ue=2+qe.length,kt=" ".repeat(Math.max(0,ke-Ue));console.log(`\x1B[2K${ge}${$t} ${qe}${kt}\x1B[0m`)}),console.log()}if(process.env.NEX_AUTO_PLAN!=="0"&&!
|
|
1819
|
-
`)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${ke}${l.reset}`)}}k=!1;let{getConversationLength:ne}=Se(),Q=ne();Q>0&&process.stdout.write(`${l.gray}[${Q} messages] ${l.reset}`),h.setPrompt(Jt()),h.prompt()}),h.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}J0.exports={startREPL:uO,getPrompt:Jt,loadHistory:V0,appendHistory:
|
|
1818
|
+
`);process.stdout.isTTY&&process.stdout.write(`\x1B[${pe.length}A`),pe.forEach((qe,Pe)=>{let $t=Pe===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",Ue=2+qe.length,kt=" ".repeat(Math.max(0,ke-Ue));console.log(`\x1B[2K${ge}${$t} ${qe}${kt}\x1B[0m`)}),console.log()}if(process.env.NEX_AUTO_PLAN!=="0"&&!hc()){let{isPlanMode:ge,setPlanMode:ke}=wn(),{invalidateSystemPromptCache:pe}=Se(),qe=/\b(implement|refactor|migrate|redesign)\b/i,Pe=/\b(create|build|add|write|introduce|develop|set\s+up)\b/i,$t=/^(how|what|why|when|where|which|explain|show|list|tell|describe|can\s+you|could\s+you|do\s+you)\b/i,Ue=/\b(spawn[_\s]?agents?|swarm)\b/i;!$t.test(Z)&&!Ue.test(Z)&&(qe.test(Z)||Pe.test(Z)&&Z.split(/\s+/).length>=5)&&!ge()&&(ke(!0),pe(),console.log(`${l.cyan}${l.bold}\u2387 Auto Plan Mode${l.reset}${l.dim} \u2014 implementation task detected \xB7 read-only until /plan approve${l.reset}`))}{let{getConversationLength:ge}=Se();if(ge()===0)try{let{detectCategory:ke,getModelForCategory:pe}=us(),qe=ke(Z);if(qe&&qe.id!=="coding"){let Pe=pe(qe.id),$t=Qn();if(Pe&&Pe!==$t?.id&&Od(Pe)){let Ue=Qn();console.log(`${l.dim}\u21B3 ${qe.icon} ${qe.label} task \u2014 routing to ${Ue?.name||Pe}${l.reset}`),global._nexFooter&&global._nexFooter.setStatusInfo({model:Ue?.name||Pe})}}}catch{}}k=!0,h.prompt(),E=0,S=!1,x&&(clearTimeout(x),x=null),kn=new AbortController;try{await n(Z)}catch(ge){if(!kn?.signal?.aborted){let ke=ge.message?.split(`
|
|
1819
|
+
`)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${ke}${l.reset}`)}}k=!1;let{getConversationLength:ne}=Se(),Q=ne();Q>0&&process.stdout.write(`${l.gray}[${Q} messages] ${l.reset}`),h.setPrompt(Jt()),h.prompt()}),h.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}J0.exports={startREPL:uO,getPrompt:Jt,loadHistory:V0,appendHistory:mc,getHistoryPath:Nd,HISTORY_MAX:Md,showCommandList:Y0,completer:K0,completeFilePath:G0,handleSlashCommand:hi,showProviders:Cd,showHelp:z0,renderBar:X0,hasPasteStart:aO,hasPasteEnd:cO,stripPasteSequences:pi,getAbortSignal:H0}});var Q0=K((RN,Z0)=>{"use strict";var dO=require("readline");function so(t){process.stdout.write(JSON.stringify(t)+`
|
|
1820
1820
|
`)}function fO(){process.env.NEX_SERVER="1";let t=(...a)=>process.stderr.write(a.map(String).join(" ")+`
|
|
1821
|
-
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=_t(),n=new Map,s=0;e((a,c)=>{let u="cfm-"+ ++s,d=c?.toolName||"",f=!1;try{let{isCritical:p}=_t();f=p(a)}catch{}return so({type:"confirm_request",id:u,question:a,tool:d,critical:f}),new Promise(p=>{n.set(u,p)})});let o=null,r={onToken(a){o&&so({type:"token",id:o,text:a})},onThinkingToken(){},onToolStart(a,c){o&&so({type:"tool_start",id:o,tool:a,args:c||{}})},onToolEnd(a,c,u){o&&so({type:"tool_end",id:o,tool:a,summary:c||"",ok:!!u})}},i=dO.createInterface({input:process.stdin,output:null,terminal:!1});so({type:"ready"}),i.on("line",async a=>{let c=a.trim();if(!c)return;let u;try{u=JSON.parse(c)}catch{return}switch(u.type){case"chat":{let d=u.id||"msg-"+Date.now();o=d;let{processInput:f}=Se();try{await f(u.text,r),so({type:"done",id:d})}catch(p){so({type:"error",id:d,message:p?.message||String(p)})}finally{o=null}break}case"confirm":{let d=n.get(u.id);d&&(n.delete(u.id),d(!!u.answer));break}case"cancel":{for(let[d,f]of n)n.delete(d),f(!1);break}case"clear":{let{clearConversation:d}=Se();d();for(let[f,p]of n)n.delete(f),p(!1);break}default:break}}),i.on("close",()=>{process.exit(0)})}Z0.exports={startServerMode:fO}});var ow=K((CN,sw)=>{"use strict";var oo=require("fs"),
|
|
1821
|
+
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=_t(),n=new Map,s=0;e((a,c)=>{let u="cfm-"+ ++s,d=c?.toolName||"",f=!1;try{let{isCritical:p}=_t();f=p(a)}catch{}return so({type:"confirm_request",id:u,question:a,tool:d,critical:f}),new Promise(p=>{n.set(u,p)})});let o=null,r={onToken(a){o&&so({type:"token",id:o,text:a})},onThinkingToken(){},onToolStart(a,c){o&&so({type:"tool_start",id:o,tool:a,args:c||{}})},onToolEnd(a,c,u){o&&so({type:"tool_end",id:o,tool:a,summary:c||"",ok:!!u})}},i=dO.createInterface({input:process.stdin,output:null,terminal:!1});so({type:"ready"}),i.on("line",async a=>{let c=a.trim();if(!c)return;let u;try{u=JSON.parse(c)}catch{return}switch(u.type){case"chat":{let d=u.id||"msg-"+Date.now();o=d;let{processInput:f}=Se();try{await f(u.text,r),so({type:"done",id:d})}catch(p){so({type:"error",id:d,message:p?.message||String(p)})}finally{o=null}break}case"confirm":{let d=n.get(u.id);d&&(n.delete(u.id),d(!!u.answer));break}case"cancel":{for(let[d,f]of n)n.delete(d),f(!1);break}case"clear":{let{clearConversation:d}=Se();d();for(let[f,p]of n)n.delete(f),p(!1);break}default:break}}),i.on("close",()=>{process.exit(0)})}Z0.exports={startServerMode:fO}});var ow=K((CN,sw)=>{"use strict";var oo=require("fs"),Dd=require("path"),pO=require("https"),{execSync:jd}=require("child_process"),hO=5*1024*1024;function ew(t){let e=t.match(/^\*\/(\d+) \* \* \* \*$/);if(e){let s=parseInt(e[1],10);if(s>0)return{intervalMs:s*60*1e3,initialDelayMs:0}}let n=t.match(/^0 (\d+) \* \* \*$/);if(n){let s=parseInt(n[1],10),o=new Date,r=new Date;return r.setHours(s,0,0,0),r<=o&&r.setDate(r.getDate()+1),{intervalMs:1440*60*1e3,initialDelayMs:r.getTime()-o.getTime()}}return null}function qd(t,e){return t.replace(/\{(\w+)\}/g,(n,s)=>e[s]!==void 0?e[s]:n)}function tw(t,e){if(t)try{let n=Dd.resolve(t),s=Dd.dirname(n);oo.existsSync(s)||oo.mkdirSync(s,{recursive:!0});try{oo.statSync(n).size>hO&&oo.truncateSync(n,0)}catch{}oo.appendFileSync(n,JSON.stringify(e)+`
|
|
1822
1822
|
`,"utf-8")}catch(n){process.stderr.write(`[daemon] log write error: ${n.message}
|
|
1823
|
-
`)}}function mO(t,e){if(process.platform==="darwin")try{let n=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),s=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');
|
|
1824
|
-
`)}finally{i()}let d=Date.now()-a;tw(n,{ts:new Date().toISOString(),trigger:o,task:t.slice(0,200),status:c,error:u,durationMs:d});let f=c==="ok"?`Task completed in ${d}ms`:`Task failed: ${u}`;gO(s,`nex daemon (${o})`,f)}function yO(t,e){let n=t.replace(/\\/g,"/");return e.some(s=>{let o=s.replace(/^\.\//,"");if(o.endsWith("/**")){let r=o.slice(0,-3);return n===r||n.startsWith(r+"/")}if(o.startsWith("**/")){let r=o.slice(3);return n===r||n.endsWith("/"+r)}return n===o})}function $O(t,e,n){let{ignore:s=[],task:o,debounceMs:r=2e3,auto:i=!0}=t,a=new Set,c=null,u=async()=>{let f=[...a];a.clear();let p=
|
|
1825
|
-
`),null}}function wO(t,e,n){let{task:s,debounceMs:o=0,auto:r=!0}=t,i=()=>{try{return
|
|
1826
|
-
`),null;let{intervalMs:i,initialDelayMs:a}=r,c=async()=>{await
|
|
1823
|
+
`)}}function mO(t,e){if(process.platform==="darwin")try{let n=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),s=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');jd(`osascript -e 'display notification "${n}" with title "${s}"'`,{stdio:"ignore"})}catch{}}function nw(t){let e=process.env.NEX_MATRIX_URL,n=process.env.NEX_MATRIX_TOKEN,s=process.env.NEX_MATRIX_ROOM;if(!(!e||!n||!s))try{let o=JSON.stringify({msgtype:"m.text",body:t}),r=Date.now(),i=`${e}/_matrix/client/r0/rooms/${encodeURIComponent(s)}/send/m.room.message/${r}`,a=new URL(i),c={hostname:a.hostname,port:a.port||(a.protocol==="https:"?443:80),path:a.pathname+a.search,method:"PUT",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","Content-Length":Buffer.byteLength(o)}},u=pO.request(c);u.on("error",()=>{}),u.write(o),u.end()}catch{}}function gO(t,e,n){Array.isArray(t)&&(t.includes("desktop")&&mO(e,n),t.includes("matrix")&&nw(`[nex daemon] ${e}: ${n}`))}async function Fd(t,e,n,s,o){let{processInput:r,clearConversation:i}=Se(),a=Date.now(),c="ok",u=null;try{await r(t,null,{autoConfirm:e})}catch(p){c="error",u=p.message,process.stderr.write(`[daemon] task error (${o}): ${p.message}
|
|
1824
|
+
`)}finally{i()}let d=Date.now()-a;tw(n,{ts:new Date().toISOString(),trigger:o,task:t.slice(0,200),status:c,error:u,durationMs:d});let f=c==="ok"?`Task completed in ${d}ms`:`Task failed: ${u}`;gO(s,`nex daemon (${o})`,f)}function yO(t,e){let n=t.replace(/\\/g,"/");return e.some(s=>{let o=s.replace(/^\.\//,"");if(o.endsWith("/**")){let r=o.slice(0,-3);return n===r||n.startsWith(r+"/")}if(o.startsWith("**/")){let r=o.slice(3);return n===r||n.endsWith("/"+r)}return n===o})}function $O(t,e,n){let{ignore:s=[],task:o,debounceMs:r=2e3,auto:i=!0}=t,a=new Set,c=null,u=async()=>{let f=[...a];a.clear();let p=qd(o,{changedFile:f[0]||"",changedFiles:f.join(", ")});await Fd(p,i,e.logFile,e.notify,"file-change")},d=(f,p)=>{if(!p)return;let m=p.replace(/\\/g,"/");yO(m,s)||(a.add(m),clearTimeout(c),c=setTimeout(u,r))};try{return oo.watch(n,{recursive:!0},d)}catch(f){return process.stderr.write(`[daemon] file-change watcher error: ${f.message}
|
|
1825
|
+
`),null}}function wO(t,e,n){let{task:s,debounceMs:o=0,auto:r=!0}=t,i=()=>{try{return jd("git log --format=%H -1",{cwd:n,encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}},a=()=>{try{return jd("git log --format=%s -1",{cwd:n,encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return""}},c=i();return setInterval(async()=>{let d=i();if(!d||d===c)return;let f=a();c=d;let p=async()=>{let m=qd(s,{commitHash:d,commitMessage:f});await Fd(m,r,e.logFile,e.notify,"git-commit")};o>0?setTimeout(p,o):await p()},1e4)}function bO(t,e){let{cron:n,task:s,auto:o=!0}=t,r=ew(n);if(!r)return process.stderr.write(`[daemon] unsupported cron syntax: "${n}" \u2014 skipping
|
|
1826
|
+
`),null;let{intervalMs:i,initialDelayMs:a}=r,c=async()=>{await Fd(s,o,e.logFile,e.notify,"schedule")};return a>0?setTimeout(()=>{c(),setInterval(c,i)},a):setInterval(c,i)}async function _O(t,e={}){let n=e.cwd||process.cwd(),s=Dd.resolve(n,t),o;try{let u=oo.readFileSync(s,"utf-8");o=JSON.parse(u)}catch(u){if(u.code==="ENOENT"){let d=JSON.stringify({triggers:[{on:"file-change",glob:"**/*.{js,ts}",ignore:["dist/**","node_modules/**"],task:"run npm test -- --testPathPattern={changedFile} and report results",debounceMs:2e3,auto:!0}],notify:["desktop"],logFile:".nex/daemon.log"},null,2);throw process.stderr.write(`[daemon] config file not found: ${s}
|
|
1827
1827
|
|
|
1828
1828
|
Create .nex/daemon.json with this example:
|
|
1829
1829
|
${d}
|
|
@@ -1833,7 +1833,7 @@ press Ctrl+C to stop
|
|
|
1833
1833
|
`);let a=[];for(let u of o.triggers){let d=null;switch(u.on){case"file-change":d=$O(u,o,n);break;case"git-commit":d=wO(u,o,n);break;case"schedule":d=bO(u,o);break;default:process.stderr.write(`[daemon] unknown trigger type: ${u.on}
|
|
1834
1834
|
`)}d&&a.push(d)}let c=()=>{process.stdout.write(`
|
|
1835
1835
|
[daemon] shutting down...
|
|
1836
|
-
`);for(let u of a)try{u&&typeof u.close=="function"?u.close():u&&clearInterval(u)}catch{}process.exit(0)};return process.on("SIGINT",c),process.on("SIGTERM",c),new Promise(()=>{})}sw.exports={startDaemon:_O,parseCronToMs:ew,expandTemplate:
|
|
1836
|
+
`);for(let u of a)try{u&&typeof u.close=="function"?u.close():u&&clearInterval(u)}catch{}process.exit(0)};return process.on("SIGINT",c),process.on("SIGTERM",c),new Promise(()=>{})}sw.exports={startDaemon:_O,parseCronToMs:ew,expandTemplate:qd,appendLog:tw,notifyMatrix:nw}});var iw=K((AN,rw)=>{rw.exports=Id()});var $c=require("path"),xO=require("os");require("dotenv").config({path:$c.join(__dirname,"..",".env")});require("dotenv").config({path:$c.join(xO.homedir(),".nex-code",".env")});require("dotenv").config();var _e=process.argv.slice(2);(_e.includes("--help")||_e.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
1837
1837
|
|
|
1838
1838
|
Options:
|
|
1839
1839
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -1856,7 +1856,7 @@ Options:
|
|
|
1856
1856
|
--mcp-config <path> Path to MCP server config (default: .nex/mcp.json)
|
|
1857
1857
|
-h, --help Show this help
|
|
1858
1858
|
-v, --version Show version
|
|
1859
|
-
`),process.exit(0));if(_e.includes("-v")||_e.includes("--version")){let t=lo();console.log(t.version),process.exit(0)}var lw=_e.includes("--yolo")||_e.includes("-yolo");if(lw){let{setAutoConfirm:t}=_t();t(!0)}if(!lw)try{let t=require("fs"),e
|
|
1860
|
-
`));var
|
|
1859
|
+
`),process.exit(0));if(_e.includes("-v")||_e.includes("--version")){let t=lo();console.log(t.version),process.exit(0)}var lw=_e.includes("--yolo")||_e.includes("-yolo");if(lw){let{setAutoConfirm:t}=_t();t(!0)}if(!lw)try{let t=require("fs"),e=$c.join(process.cwd(),".nex","config.json");if(t.existsSync(e)&&JSON.parse(t.readFileSync(e,"utf-8")).yolo===!0){let{setAutoConfirm:s}=_t();s(!0)}}catch{}var Hd=_e.includes("--flatrate")||!!process.env.OLLAMA_API_KEY&&!process.env.NEX_NO_FLATRATE;Hd&&(process.env.NEX_MAX_PARALLEL||(process.env.NEX_MAX_PARALLEL="6"),process.env.NEX_MAX_SUBTASKS||(process.env.NEX_MAX_SUBTASKS="10"),process.env.NEX_MAX_CHAT_RETRIES||(process.env.NEX_MAX_CHAT_RETRIES="5"),process.env.OLLAMA_FALLBACK_CHAIN||(process.env.OLLAMA_FALLBACK_CHAIN="ministral-3:8b,qwen3-vl:235b-instruct,devstral-small-2:24b"),process.stderr.write(`\x1B[38;2;80;210;120m\u25C6\x1B[0m \x1B[1mFlatrate mode\x1B[0m\x1B[2m \u2014 100 turns \xB7 6 parallel agents \xB7 5 retries \xB7 verify-on\x1B[0m
|
|
1860
|
+
`));var Bd=_e.indexOf("--model");if(Bd!==-1&&_e[Bd+1]){let{setActiveModel:t}=We();t(_e[Bd+1])}var yc=_e.indexOf("--max-turns");if(yc!==-1&&_e[yc+1]){let t=parseInt(_e[yc+1],10);if(t>0){let{setMaxIterations:e}=Se();e(t)}}else try{let t=require("fs"),e=$c.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let n=JSON.parse(t.readFileSync(e,"utf-8")),s=parseInt(n.maxIterations,10);if(s>0){let{setMaxIterations:o}=Se();o(s)}}}catch{}var Ud=_e.indexOf("--mcp-config");Ud!==-1&&_e[Ud+1]&&(process.env.NEX_MCP_CONFIG=_e[Ud+1]);function Wd(){if(process.platform==="darwin")try{let{spawn:t}=require("child_process"),e=t("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});e.unref();let n=()=>{try{e.kill()}catch{}};process.on("exit",n),process.on("SIGINT",n),process.on("SIGTERM",n)}catch{}}async function SO(){let{runSetupWizard:t}=ld();await t()}function aw(t){if(_e.includes("--auto")){let{setAutoConfirm:a}=_t();a(!0)}if(Hd&&yc===-1){let{setMaxIterations:a}=Se();a(100)}if(!_e.includes("--model")){let{setActiveModel:a}=We(),c=process.env.HEADLESS_MODEL||"devstral-small-2:24b";a(c)}let n=!_e.includes("--no-auto-orchestrate")&&process.env.NEX_AUTO_ORCHESTRATE!=="false",s=_e.indexOf("--orchestrator-model"),o=s!==-1?_e[s+1]:void 0;if(t.startsWith("/")){let{loadAllSkills:a,handleSkillCommand:c}=Wn();a();let u=c(t);if(u&&u.agentPrompt){let{processInput:f,getConversationMessages:p}=Se();f(u.agentPrompt,null,{autoOrchestrate:n,orchestratorModel:o}).then(()=>process.exit(0)).catch(m=>{console.error(m.message),process.exit(1)});return}let{handleSlashCommand:d}=Id();d(t,null).then(()=>process.exit(0)).catch(f=>{console.error(f.message),process.exit(1)});return}let{processInput:r,getConversationMessages:i}=Se();r(t,null,{autoOrchestrate:n,orchestratorModel:o}).then(()=>{try{let{writeDreamLog:a}=pd();a(i())}catch{}if(_e.includes("--json")){let c=i().filter(u=>u.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:c?.content||""}))}process.exit(0)}).catch(a=>{_e.includes("--json")?console.log(JSON.stringify({success:!1,error:a.message})):console.error(a.message),process.exit(1)})}if(_e.includes("--server")){let{setAutoConfirm:t}=_t();t(!0),Q0().startServerMode();return}if(_e.includes("--daemon")||_e.includes("--watch")){let t=_e.includes("--daemon")?_e.indexOf("--daemon"):_e.indexOf("--watch"),e=_e[t+1],n=e&&!e.startsWith("--")?e:".nex/daemon.json",{startDaemon:s}=ow();s(n).catch(o=>{console.error("Daemon error:",o.message),process.exit(1)});return}var cw=_e.indexOf("--prompt-file");if(cw!==-1){let t=_e[cw+1];(!t||t.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let e=require("fs"),n;try{n=e.readFileSync(t,"utf-8").trim()}catch(s){console.error(`--prompt-file: cannot read file: ${s.message}`),process.exit(1)}if(n||(console.error("--prompt-file: file is empty"),process.exit(1)),_e.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}Wd(),aw(n)}else{let t=_e.indexOf("--task")!==-1?_e.indexOf("--task"):_e.indexOf("--prompt");if(t!==-1){let e=_e[t+1];if((!e||e.startsWith("--"))&&(console.error("--task/--prompt requires a prompt"),process.exit(1)),Wd(),_e.includes("--orchestrate")){let n=_e.indexOf("--orchestrator-model"),s=n!==-1?_e[n+1]:void 0,{runOrchestrated:o}=Br();o(e,{orchestratorModel:s}).then(()=>{process.exit(0)}).catch(r=>{console.error(`Orchestrator error: ${r.message}`),process.exit(1)})}else aw(e)}else SO().then(()=>{if(Wd(),Hd){let{setMaxIterations:n}=Se();n(100)}let{startREPL:e}=iw();e(),setTimeout(async()=>{try{let{loadKnownModels:n,findNewModels:s}=Vo(),o=n(),r=o.lastChecked?new Date(o.lastChecked):null;if((r?(Date.now()-r.getTime())/864e5:999)<7||!process.env.OLLAMA_API_KEY)return;let{newModels:a}=await s();if(a.length>0){let{C:c}=Ye();process.stdout.write(`
|
|
1861
1861
|
${c.dim}\u{1F4A1} ${a.length} new Ollama Cloud model(s) available \u2014 /benchmark --discover to test them${c.reset}
|
|
1862
1862
|
`)}}catch{}},3e3)})}
|