nex-code 0.5.14 → 0.5.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/background-worker.js +171 -168
- package/dist/benchmark.js +176 -173
- package/dist/nex-code.js +273 -270
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,35 +1,35 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Cl=Object.defineProperty;var mx=Object.getOwnPropertyDescriptor;var gx=Object.getOwnPropertyNames;var yx=Object.prototype.hasOwnProperty;var $x=(t,e)=>()=>(t&&(e=t(t=0)),e);var X=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),wx=(t,e)=>{for(var n in e)Cl(t,n,{get:e[n],enumerable:!0})},bx=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of gx(e))!yx.call(t,s)&&s!==n&&Cl(t,s,{get:()=>e[s],enumerable:!(o=mx(e,s))||o.enumerable});return t};var _x=t=>bx(Cl({},"__esModule",{value:!0}),t);var Po=X((
|
|
3
|
-
`),s=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(s){let r=parseInt(s[1].slice(0,2),16),i=parseInt(s[2].slice(0,2),16),a=parseInt(s[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function
|
|
2
|
+
var Cl=Object.defineProperty;var mx=Object.getOwnPropertyDescriptor;var gx=Object.getOwnPropertyNames;var yx=Object.prototype.hasOwnProperty;var $x=(t,e)=>()=>(t&&(e=t(t=0)),e);var X=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),wx=(t,e)=>{for(var n in e)Cl(t,n,{get:e[n],enumerable:!0})},bx=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of gx(e))!yx.call(t,s)&&s!==n&&Cl(t,s,{get:()=>e[s],enumerable:!(o=mx(e,s))||o.enumerable});return t};var _x=t=>bx(Cl({},"__esModule",{value:!0}),t);var Po=X((dI,xx)=>{xx.exports={name:"nex-code",version:"0.5.15",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 .","scan:secrets":"node scripts/secret-scan.js --staged","install-hooks":"ln -sf ../../hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit && ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-commit, pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js","benchmark:reallife":"node scripts/benchmark-reallife.js","benchmark:report":"node scripts/benchmark-reallife-report.js","improve:reallife":"node scripts/improve-reallife.js","benchmark:gate":"node scripts/benchmark-gate.js",release:"bash scripts/release.sh"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","gemini","llm","gpt","agentic","terminal","coding-assistant","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.15.0",dotenv:"^16.4.0",pixelmatch:"^7.1.0",pngjs:"^7.0.0"},devDependencies:{esbuild:"^0.27.3",jest:"^29.7.0",prettier:"^3.8.1",typescript:"^5.9.3"},overrides:{"brace-expansion":">=5.0.5",picomatch:">=4.0.4"},jest:{coverageThreshold:{global:{lines:45,functions:30,branches:35},"./cli/sub-agent.js":{lines:70,functions:60,branches:55}}}}});var Lt=X((fI,Pp)=>{"use strict";var Rp="\x1B[0m",Cp="\x1B[1m",Lo="\x1B[2m";function ie(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function vx(){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
|
+
`),s=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(s){let r=parseInt(s[1].slice(0,2),16),i=parseInt(s[2].slice(0,2),16),a=parseInt(s[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function Ap(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function kx(t){try{let n=require("fs").readFileSync(Ap(),"utf8"),o=JSON.parse(n);if(o&&typeof o[t]=="boolean")return o[t]}catch(e){console.error("readThemeCache failed:",e.message)}return null}function Sx(t,e){try{let n=require("fs"),o=require("path"),s=Ap(),r=o.dirname(s),i={};try{i=JSON.parse(n.readFileSync(s,"utf8"))}catch(c){console.error("theme cache failed:",c.message)}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(c=>delete i[c]),n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(s,JSON.stringify(i),"utf8")}catch{}}function Ex(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let i=e.split(";"),a=parseInt(i[i.length-1],10);if(!isNaN(a))return a<8}let n=process.env.TERM_SESSION_ID||"default",o=kx(n);if(o!==null)return o;let s=vx(),r=s!==null?s:!0;return Sx(n,r),r}var Op=Ex(),Mp={reset:Rp,bold:Cp,dim:Lo,primary:ie(80,190,255),secondary:ie(60,170,190),success:ie(80,210,120),warning:ie(245,175,50),error:ie(230,80,80),muted:Lo,subtle:ie(130,130,145),tool_read:ie(80,190,255),tool_write:ie(245,165,55),tool_exec:ie(185,100,235),tool_search:ie(70,185,190),tool_git:ie(90,210,100),tool_web:ie(100,215,250),tool_sysadmin:ie(225,150,75),tool_default:ie(100,205,115),syn_keyword:ie(185,100,235),syn_string:ie(90,210,120),syn_number:ie(245,175,50),syn_comment:Lo,syn_key:ie(80,190,255),diff_add:ie(80,210,120),diff_rem:ie(230,80,80),banner_logo:ie(80,200,255),banner_name:ie(80,200,255),banner_version:Lo,banner_model:Lo,banner_yolo:ie(245,175,50),banner_gemini:ie(138,180,248),footer_sep:Lo,footer_model:ie(80,175,235),footer_branch:ie(80,210,100),footer_project:ie(130,130,145),footer_divider:ie(80,80,95),footer_mode:ie(210,150,50),white:ie(210,210,220),red:ie(220,85,85),green:ie(80,200,110),yellow:ie(230,185,60),blue:ie(70,140,230),magenta:ie(200,120,190),cyan:ie(90,200,215),gray:ie(120,120,135),bgRed:"\x1B[48;2;140;40;40m",bgGreen:"\x1B[48;2;30;100;50m",diff_add_bg:"\x1B[48;2;10;46;20m",diff_rem_bg:"\x1B[48;2;58;16;16m",brightCyan:ie(110,215,230),brightMagenta:ie(220,140,210),brightBlue:ie(100,160,240)},Np={reset:Rp,bold:Cp,dim:ie(110,110,120),primary:ie(0,110,190),secondary:ie(0,125,148),success:ie(0,148,62),warning:ie(168,92,0),error:ie(188,32,32),muted:ie(110,110,120),subtle:ie(155,155,165),tool_read:ie(0,110,190),tool_write:ie(168,92,0),tool_exec:ie(128,42,188),tool_search:ie(0,122,148),tool_git:ie(0,138,62),tool_web:ie(0,112,178),tool_sysadmin:ie(168,82,0),tool_default:ie(0,138,62),syn_keyword:ie(128,42,188),syn_string:ie(0,138,62),syn_number:ie(168,92,0),syn_comment:ie(135,135,148),syn_key:ie(0,110,190),diff_add:ie(0,148,62),diff_rem:ie(188,32,32),banner_logo:ie(0,122,205),banner_name:ie(0,122,205),banner_version:ie(100,100,118),banner_model:ie(100,100,118),banner_yolo:ie(168,62,0),banner_gemini:ie(26,115,232),footer_sep:ie(168,168,178),footer_model:ie(0,102,175),footer_branch:ie(0,138,62),footer_project:ie(135,135,148),footer_divider:ie(168,168,178),footer_mode:ie(148,88,0),white:ie(40,40,52),red:ie(188,32,32),green:ie(0,148,62),yellow:ie(168,92,0),blue:ie(0,110,190),magenta:ie(128,42,188),cyan:ie(0,125,148),gray:ie(132,132,142),bgRed:"\x1B[48;2;180;50;50m",bgGreen:"\x1B[48;2;30;130;60m",diff_add_bg:"\x1B[48;2;215;245;220m",diff_rem_bg:"\x1B[48;2;255;215;215m",brightCyan:ie(0,158,182),brightMagenta:ie(158,52,208),brightBlue:ie(0,112,208)},Tx=Op?Mp:Np;Pp.exports={T:Tx,isDark:Op,DARK:Mp,LIGHT:Np}});var qs=X((pI,Fp)=>{var{T:ae}=Lt(),Al=5,Io=(()=>{let t=[];for(let e=0;e<Al;e++)t.push(e);for(let e=Al-2;e>=1;e--)t.push(e);return t})(),Lp=["\u273D","\u2726","\u2727","\u2726"],Ip=["\xB7 ","\xB7\xB7 ","\xB7\xB7\xB7"," \xB7\xB7"];function jp(t=""){let e=String(t).toLowerCase();return e.includes("search")||e.includes("read")||e.includes("list")||e.includes("inspect")?{glyph:"\u25CC",color:ae.cyan,accent:"scan"}:e.includes("write")||e.includes("edit")||e.includes("patch")||e.includes("build")?{glyph:"\u2726",color:ae.yellow,accent:"shape"}:e.includes("test")||e.includes("diff")||e.includes("check")||e.includes("verify")?{glyph:"\u25A3",color:ae.green,accent:"verify"}:e.includes("wait")||e.includes("github")||e.includes("fetch")||e.includes("browser")?{glyph:"\u25CD",color:ae.blue,accent:"wait"}:{glyph:"\u25CF",color:ae.cyan,accent:"think"}}function Dp(t,e,n){let o="";for(let s=0;s<Al;s++)s===t?o+=`${n}${e}${ae.reset}`:s===t-1||s===t+1?o+=`${ae.dim}\xB7${ae.reset}`:o+=`${ae.dim}\xB7${ae.reset}`;return o}function qp(t){return`${ae.dim}${Ip[t%Ip.length]}${ae.reset}`}var Ol=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Io[this.frame%Io.length],n=jp(this.text),o=Dp(e,n.glyph,n.color),s=qp(this.frame),r="";if(this.startTime){let i=Math.floor((Date.now()-this.startTime)/1e3);if(i>=60){let a=Math.floor(i/60),c=i%60;r=` ${ae.dim}${a}m ${String(c).padStart(2,"0")}s${ae.reset}`}else i>=1&&(r=` ${ae.dim}${i}s${ae.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${ae.reset}${s} ${o} ${ae.dim}${this.text}${ae.reset}${r}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(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}},Ml=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_render(){if(this._stopped)return;let e=Io[this.frame%Io.length],n=`${ae.cyan}\u25CC${ae.reset}`,o=this._formatElapsed(),s=o?` ${ae.dim}${o}${ae.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let c,u;switch(this.statuses[a]){case"done":c=`${ae.green}\u2713${ae.reset}`,u=ae.dim;break;case"error":c=`${ae.red}\u2717${ae.reset}`,u=ae.dim;break;case"retry":c=`${ae.yellow}\u21BB${ae.reset}`,u=ae.yellow;break;default:c=a===e?n:`${ae.dim}\xB7${ae.reset}`,u=""}let d=a===this.labels.length-1?s:"",f=r-4-(d?o.length+1:0),p=this.labels[a].length>f?this.labels[a].substring(0,Math.max(10,f-3))+"...":this.labels[a];i+=`\x1B[2K ${c} ${u}${p}${ae.reset}${d}
|
|
4
4
|
`}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let 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 o=0;o<this.lineCount;o++)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?` ${ae.dim}${e}${ae.reset}`:"",o=process.stderr.columns||80,s="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${ae.green}\u2713${ae.reset}`;break;case"error":i=`${ae.red}\u2717${ae.reset}`;break;case"retry":i=`${ae.yellow}\u21BB${ae.reset}`;break;default:i=`${ae.yellow}\u25CB${ae.reset}`}let a=r===this.labels.length-1?n:"",c=o-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];s+=`\x1B[2K ${i} ${ae.dim}${u}${ae.reset}${a}
|
|
7
|
-
`}process.stderr.write(s)}},aa={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},ca={done:ae.green,in_progress:ae.cyan,pending:ae.dim,failed:ae.red},ws=null,Nl=class{constructor(e,n){this.name=e,this.tasks=n.map(o=>({id:o.id,description:o.description,status:o.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=
|
|
7
|
+
`}process.stderr.write(s)}},aa={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},ca={done:ae.green,in_progress:ae.cyan,pending:ae.dim,failed:ae.red},ws=null,Nl=class{constructor(e,n){this.name=e,this.tasks=n.map(o=>({id:o.id,description:o.description,status:o.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=Lp[this.frame%Lp.length],n=this._formatElapsed(),o=this._formatTokens(),s=[n,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=s?` ${ae.dim}(${s})${ae.reset}`:"",i=`\x1B[2K${ae.cyan}${ae.bold}${e}${ae.reset} ${ae.bold}${this.name}${ae.reset}${ae.dim}\u2026${ae.reset}${r}
|
|
8
8
|
`;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],u=a===0?"\u23BF":"\u2502",d=aa[c.status]||aa.pending,f=ca[c.status]||ca.pending,p=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${ae.dim}${u}${ae.reset} ${f}${d}${ae.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),ws=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,ws===this&&(ws=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 o=this.tasks.find(s=>s.id===e);o&&(o.status=n)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),n=this.tasks.filter(a=>a.status==="done").length,o=this.tasks.filter(a=>a.status==="failed").length,s=this.tasks.length,r=o>0?`${n}/${s} done, ${o} failed`:`${n}/${s} done`,i=`\x1B[2K${ae.green}${ae.bold}\u2714${ae.reset} ${ae.bold}${this.name}${ae.reset} ${ae.dim}(${e} \xB7 ${r})${ae.reset}
|
|
13
13
|
`;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],u=a===0?"\u23BF":"\u2502",d=aa[c.status]||aa.pending,f=ca[c.status]||ca.pending,p=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${ae.dim}${u}${ae.reset} ${f}${d}${ae.reset} ${ae.dim}${p}${ae.reset}
|
|
14
|
-
`}process.stderr.write(i)}},Pl=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=Io[this.frame%Io.length],n=
|
|
14
|
+
`}process.stderr.write(i)}},Pl=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=Io[this.frame%Io.length],n=jp(this.message),o=Dp(e,n.glyph,n.color),s=qp(this.frame),r=this.message;this.count>0&&(r+=` ${ae.cyan}${this.count}${ae.reset}`,this.total&&(r+=`/${this.total}`)),this.detail&&(r+=` ${ae.dim}${this.detail}${ae.reset}`);let i="";if(this.startTime){let a=Math.floor((Date.now()-this.startTime)/1e3);a>=1&&(i=` ${ae.dim}${a}s${ae.reset}`)}process.stderr.write(`\x1B[2K\r${n.color}${n.accent.toUpperCase()}${ae.reset}${s} ${o} ${ae.dim}${r}${ae.reset}${i}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){e.count!==void 0&&(this.count=e.count),e.total!==void 0&&(this.total=e.total),e.detail!==void 0&&(this.detail=e.detail),e.message!==void 0&&(this.message=e.message)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h")}};function Rx(t){ws=t}function Cx(){return ws}function Ax(){ws&&(ws.stop(),ws=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Fp.exports={C:ae,Spinner:Ol,MultiProgress:Ml,TaskProgress:Nl,ToolProgress:Pl,setActiveTaskProgress:Rx,getActiveTaskProgress:Cx,cleanupTerminal:Ax}});var la=X((hI,Gp)=>{"use strict";var{T:Fs}=Lt(),be={kw:Fs.syn_keyword,str:Fs.syn_string,cmt:Fs.syn_comment,num:Fs.syn_number,type:Fs.cyan,punct:Fs.magenta,reset:Fs.reset},Bp={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"])},Ox={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 Wp(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return Ox[e]||null}var Up=/\x1b\[[0-9;]*m/g;function ss(t,e,n){let o=t.split(Up),s=t.match(Up)||[],r="";for(let i=0;i<o.length;i++)r+=o[i].replace(e,n),i<s.length&&(r+=s[i]);return r}function Mx(t){let e=t;return e=e.replace(/"([^"\\]|\\.)*"\s*:/g,n=>be.type+n+be.reset),e=ss(e,/"([^"\\]|\\.)*"/g,n=>be.str+n+be.reset),e=ss(e,/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,n=>be.num+n+be.reset),e=ss(e,/\b(true|false|null)\b/g,n=>be.kw+n+be.reset),e}function Nx(t){if(/<!--/.test(t))return t.replace(/<!--[\s\S]*?(?:-->|$)/g,n=>be.cmt+n+be.reset);let e=t;return e=e.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(n,o,s)=>o+be.type+s+be.reset),e=ss(e,/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(n,o)=>" "+be.kw+o+be.reset+"="),e=ss(e,/"([^"]*)"/g,n=>be.str+n+be.reset),e}function Px(t){let e=t;return e=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,n=>be.cmt+n+be.reset),e=ss(e,/#[0-9a-fA-F]{3,8}\b/g,n=>be.num+n+be.reset),e=ss(e,/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(n,o,s)=>be.num+o+be.reset+s),e=ss(e,/([a-z][a-z-]*)(\s*:)/g,(n,o,s)=>be.type+o+be.reset+s),e=ss(e,/"[^"]*"|'[^']*'/g,n=>be.str+n+be.reset),e}function Hp(t,e,n){if(e==="json")return Mx(t);if(e==="html"||e==="xml")return Nx(t);if(e==="css")return Px(t);if(e==="md")return t;let o=Bp[e]||Bp.js,s="",r=0;if(n.inBlockComment){let i=t.indexOf("*/");if(i===-1)return be.cmt+t+be.reset;if(s+=be.cmt+t.slice(0,i+2)+be.reset,n.inBlockComment=!1,r=i+2,r>=t.length)return s}if(n.inString==="`"){let i=t.indexOf("`");if(i===-1)return be.str+t+be.reset;if(s+=be.str+t.slice(0,i+1)+be.reset,n.inString=null,r=i+1,r>=t.length)return s}for(;r<t.length;){let i=t[r];if(!n.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return s+=be.cmt+t.slice(r)+be.reset,n.inBlockComment=!0,s;s+=be.cmt+t.slice(r,a+2)+be.reset,r=a+2;continue}if(!n.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return s+=be.cmt+t.slice(r)+be.reset,s;if(!n.inString&&(i==='"'||i==="'"||i==="`")){n.inString=i,s+=be.str+i,r++;continue}if(n.inString){if(i==="\\"&&r+1<t.length){s+=i+t[r+1],r+=2;continue}if(i===n.inString){s+=i+be.reset,n.inString=null,r++;continue}s+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let a="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(a.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)a+=t[r++];s+=be.num+a+be.reset;continue}if(i==="@"&&(e==="js"||e==="java"||e==="py")){let a="@";for(r++;r<t.length&&/[a-zA-Z0-9_$.]/.test(t[r]);)a+=t[r++];s+=be.punct+a+be.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];o.has(a)?s+=be.kw+a+be.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?s+=be.type+a+be.reset:s+=a;continue}s+=i,r++}return n.inString&&n.inString!=="`"&&(s+=be.reset,n.inString=null),s}function Lx(t,e){let n=Wp(e);if(!n)return t.split(`
|
|
15
15
|
`);let o=t.split(`
|
|
16
|
-
`),s={inString:null,inBlockComment:!1};return o.map(r=>
|
|
16
|
+
`),s={inString:null,inBlockComment:!1};return o.map(r=>Hp(r,n,s))}function Ix(t,e){return e?Hp(t,e,{inString:null,inBlockComment:!1}):t}Gp.exports={detectLang:Wp,highlightLine:Ix,highlightLines:Lx}});var th=X((mI,eh)=>{var{T}=Lt(),Ke=T,Yp=require("path"),zp=["\u23FA","\u25C9","\u25CE","\u25C9"];function da(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var jx={read_file:T.tool_read,list_directory:T.tool_read,write_file:T.tool_write,edit_file:T.tool_write,patch_file:T.tool_write,bash:T.tool_exec,grep:T.tool_search,search_files:T.tool_search,glob:T.tool_search,git_commit:T.tool_git,git_push:T.tool_git,git_pull:T.tool_git,git_status:T.tool_git,git_diff:T.tool_git,git_log:T.tool_git,git_branch:T.tool_git,git_stash:T.tool_git,web_fetch:T.tool_web,web_search:T.tool_web,sysadmin:T.tool_sysadmin,ssh_exec:T.tool_sysadmin,ssh_upload:T.tool_sysadmin,ssh_download:T.tool_sysadmin,deploy:T.tool_sysadmin},Jp={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"},Dx={read_file:{label:"Inspect",accent:T.tool_read,icon:"\u25CC"},list_directory:{label:"Inspect",accent:T.tool_read,icon:"\u25CC"},grep:{label:"Inspect",accent:T.tool_search,icon:"\u25CC"},search_files:{label:"Inspect",accent:T.tool_search,icon:"\u25CC"},glob:{label:"Inspect",accent:T.tool_search,icon:"\u25CC"},web_fetch:{label:"Explore",accent:T.tool_web,icon:"\u25CC"},web_search:{label:"Explore",accent:T.tool_web,icon:"\u25CC"},browser_open:{label:"Explore",accent:T.tool_web,icon:"\u25CC"},browser_screenshot:{label:"Capture",accent:T.tool_web,icon:"\u25CC"},browser_click:{label:"Interact",accent:T.tool_web,icon:"\u25CC"},browser_fill:{label:"Interact",accent:T.tool_web,icon:"\u25CC"},write_file:{label:"Shape",accent:T.tool_write,icon:"\u2726"},edit_file:{label:"Shape",accent:T.tool_write,icon:"\u2726"},patch_file:{label:"Shape",accent:T.tool_write,icon:"\u2726"},bash:{label:"Execute",accent:T.tool_exec,icon:"\u25A3"},sysadmin:{label:"Operate",accent:T.tool_sysadmin,icon:"\u25A3"},ssh_exec:{label:"Operate",accent:T.tool_sysadmin,icon:"\u25A3"},ssh_upload:{label:"Ship",accent:T.tool_sysadmin,icon:"\u25A3"},ssh_download:{label:"Collect",accent:T.tool_sysadmin,icon:"\u25A3"},deploy:{label:"Ship",accent:T.tool_sysadmin,icon:"\u25A3"},git_status:{label:"Verify",accent:T.tool_git,icon:"\u2713"},git_diff:{label:"Verify",accent:T.tool_git,icon:"\u2713"},git_log:{label:"Verify",accent:T.tool_git,icon:"\u2713"},git_commit:{label:"Commit",accent:T.tool_git,icon:"\u2713"},git_push:{label:"Ship",accent:T.tool_git,icon:"\u2713"},git_pull:{label:"Sync",accent:T.tool_git,icon:"\u2713"},git_branch:{label:"Sync",accent:T.tool_git,icon:"\u2713"},git_stash:{label:"Sync",accent:T.tool_git,icon:"\u2713"}};function Il(t){return Dx[t]||{label:"Run",accent:T.tool_default,icon:"\u2022"}}function Kp(t){let e=Il(t);return`${e.accent}${Ke.bold}${e.icon} ${e.label.toUpperCase()}${T.reset}`}function qx(t){return t.replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function Xp(t,e={}){return e.path?da(e.path):e.file?da(e.file):e.query?String(e.query).substring(0,44):e.pattern?String(e.pattern).substring(0,44):e.url?String(e.url).substring(0,44):e.command?String(e.command).substring(0,44):Jp[t]||qx(t)}function Fx(t){return String(t||"").split(`
|
|
17
17
|
`).map(e=>{let n=e.match(/^(\d+):\s?(.*)$/s);return n?{lineNumber:n[1],content:n[2]||""}:null}).filter(Boolean)}function Bx(t,e,n={}){let{maxLines:o=4,indent:s=" ",maxContent:r=110,includeOverflow:i=!0}=n;if(!Array.isArray(e)||e.length===0)return"";let{highlightLine:a,detectLang:c}=la(),u=c(t||null),d=e.slice(0,o),f=d.map(({lineNumber:p,content:m})=>{let h=m.length>r?m.substring(0,r-1)+"\u2026":m;return`${s}${T.subtle}${p}:${T.reset} ${a(h,u)}${T.reset}`});return i&&e.length>d.length&&f.push(`${s}${T.subtle}\u2026 +${e.length-d.length} more line${e.length-d.length!==1?"s":""}${T.reset}`),f.join(`
|
|
18
18
|
`)}function Ux(t,e=96){let n=String(t||"").replace(/\t/g," ").trimEnd();return n.length>e?n.substring(0,Math.max(1,e-1))+"\u2026":n}function Ll(t,e={}){let{maxLines:n=3,maxContent:o=96}=e,r=String(t||"").split(`
|
|
19
|
-
`).filter((a,c,u)=>a.trim()||u.length===1||c===0),i=r.slice(0,n).map(a=>Ux(a,o));return{shown:i,more:Math.max(0,r.length-i.length)}}function
|
|
19
|
+
`).filter((a,c,u)=>a.trim()||u.length===1||c===0),i=r.slice(0,n).map(a=>Ux(a,o));return{shown:i,more:Math.max(0,r.length-i.length)}}function Zp(t,e={}){let{indent:n=" ",maxLines:o=2,maxContent:s=100}=e;if(!t)return"";let{shown:r,more:i}=Ll(t,{maxLines:o,maxContent:s});if(r.length===0)return"";let a=r.map((c,u)=>`${n}${T.subtle}${u===0?"$":">"}${T.reset} ${T.muted}${c}${T.reset}`);return i>0&&a.push(`${n}${T.subtle}\u2026 +${i} more command line${i!==1?"s":""}${T.reset}`),a.join(`
|
|
20
20
|
`)}function jl(t,e,n,o={}){let{indent:s=" ",maxLines:r=3,maxContent:i=96,includeLabels:a=!0}=o,{highlightLine:c,detectLang:u}=la(),d=u(t||null),{shown:f,more:p}=Ll(e,{maxLines:r,maxContent:i}),{shown:m,more:h}=Ll(n,{maxLines:r,maxContent:i}),g=[];return f.length>0&&a&&g.push(`${s}${T.subtle}before${T.reset}`),f.forEach(y=>{g.push(`${s}${T.diff_rem}- ${T.reset}${c(y,d)}${T.reset}`)}),p>0&&g.push(`${s}${T.subtle}\u2026 ${p} more removed line${p!==1?"s":""}${T.reset}`),m.length>0&&a&&g.push(`${s}${T.subtle}after${T.reset}`),m.forEach(y=>{g.push(`${s}${T.diff_add}+ ${T.reset}${c(y,d)}${T.reset}`)}),h>0&&g.push(`${s}${T.subtle}\u2026 ${h} more added line${h!==1?"s":""}${T.reset}`),g.join(`
|
|
21
|
-
`)}function
|
|
22
|
-
`)}function Wx(t){let e=new Set,n=[];for(let o of t){let s=Il(o.fnName).label;e.has(s)||(e.add(s),n.push(s))}return n.length===0?"":n.length<=3?n.join(`${Ke.dim} \u2192 ${Ke.reset}`):`${n.slice(0,3).join(`${Ke.dim} \u2192 ${Ke.reset}`)}${Ke.dim} \u2192 +${n.length-3}${Ke.reset}`}function ua(t,e=!1,n=null){if(e)return`${T.error}\u23FA${T.reset}`;let o=jx[t]||T.tool_default;if(n==="blink")return`${o}\x1B[5m\u23FA\x1B[25m${T.reset}`;let s=typeof n=="number"?
|
|
21
|
+
`)}function Qp(t,e,n={}){let{indent:o=" ",maxPatches:s=2,maxLinesPerSide:r=2,maxContent:i=92}=n;if(!Array.isArray(e)||e.length===0)return"";let a=[];return e.slice(0,s).forEach((c,u)=>{a.push(`${o}${T.subtle}patch ${u+1}${T.reset}`);let d=jl(t,c.old_text,c.new_text,{indent:o+" ",maxLines:r,maxContent:i,includeLabels:!1});d&&a.push(d)}),e.length>s&&a.push(`${o}${T.subtle}\u2026 +${e.length-s} more patches${T.reset}`),a.join(`
|
|
22
|
+
`)}function Wx(t){let e=new Set,n=[];for(let o of t){let s=Il(o.fnName).label;e.has(s)||(e.add(s),n.push(s))}return n.length===0?"":n.length<=3?n.join(`${Ke.dim} \u2192 ${Ke.reset}`):`${n.slice(0,3).join(`${Ke.dim} \u2192 ${Ke.reset}`)}${Ke.dim} \u2192 +${n.length-3}${Ke.reset}`}function ua(t,e=!1,n=null){if(e)return`${T.error}\u23FA${T.reset}`;let o=jx[t]||T.tool_default;if(n==="blink")return`${o}\x1B[5m\u23FA\x1B[25m${T.reset}`;let s=typeof n=="number"?zp[n%zp.length]:n!==null?n:"\u23FA";return`${o}${s}${T.reset}`}function Hx(t,e,n=!1,o=null){let s=(t||[]).filter(u=>u&&u.canExecute!==!1);if(s.length===0)return`${ua("",n,o)} Step ${e}`;if(s.length===1){let u=s[0],d=u.args||{},f=Xp(u.fnName,{...d,path:d._originalPath||d.path});return`${ua(u.fnName,n,o)} ${Kp(u.fnName)} ${Ke.bold}${f}${Ke.reset}`}let r=s[0].fnName,i=Wx(s)||`${s.length} tools`,a=s.slice(0,2).map(u=>Xp(u.fnName,u.args||{})).filter(Boolean).join(`${Ke.dim} \xB7 ${Ke.reset}`),c=a?` ${T.subtle}\xB7${T.reset} ${Ke.dim}${a}${Ke.reset}`:"";return`${ua(r,n,o)} ${Kp(r)} ${Ke.bold}${i}${Ke.reset}${c}`}function Gx(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,44);break;case"grep":case"search_files":n=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":n=e.pattern||"";break;case"web_fetch":n=(e.url||"").substring(0,60);break;case"web_search":n=(e.query||"").substring(0,50);break;default:n=JSON.stringify(e).substring(0,80)}let o=Jp[t]||t.replace(/_/g," "),s=n?`(${Ke.dim}${n}${Ke.reset})`:"",r=`${ua(t)} ${Ke.bold}${o}${Ke.reset}${s}`;if(t==="bash"||t==="ssh_exec"){let i=Zp(e.command,{indent:" ",maxLines:2,maxContent:108});return i?`${r}
|
|
23
23
|
${i}`:r}if(t==="edit_file"){let i=jl(e.path,e.old_text,e.new_text,{indent:" ",maxLines:2,maxContent:92});return i?`${r}
|
|
24
|
-
${i}`:r}if(t==="patch_file"){let i=
|
|
24
|
+
${i}`:r}if(t==="patch_file"){let i=Qp(e.path,e.patches,{indent:" ",maxPatches:2,maxLinesPerSide:1,maxContent:90});return i?`${r}
|
|
25
25
|
${i}`:r}return r}function Yx(t,e=8){let n=t.split(`
|
|
26
26
|
`),o=n.slice(0,e),s=n.length-e,r=`${T.muted} \u23BF ${T.reset}`,i=" ",a=o.map((c,u)=>`${u===0?r:i}${T.success}${c}${T.reset}`).join(`
|
|
27
27
|
`);return s>0&&(a+=`
|
|
28
|
-
${T.subtle} \u2026 +${s} lines${T.reset}`),a}var fa=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],
|
|
28
|
+
${T.subtle} \u2026 +${s} lines${T.reset}`),a}var fa=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],Vp=Math.floor(Math.random()*fa.length),zx=null;function Kx(t){zx=t}function Xx(){let t=fa[Vp%fa.length];return Vp++,t}function Vx(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading ${e.path||"file"}`;case"list_directory":return`Listing ${e.path||"."}`;case"search_files":return`Searching ${e.pattern||"..."}`;case"glob":return`Searching ${e.pattern||"..."}`;case"grep":return`Searching ${e.pattern||"..."}`;case"web_fetch":return`Fetching ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Analyzing repository status";case"git_diff":return`Diffing${e.file?` ${e.file}`:""}`;case"git_log":return`Reading git log${e.file?` (${e.file})`:""}`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;case"sysadmin":{let n=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${n}: full audit...`;case"disk_usage":return`Sysadmin${n}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${n}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${n}: network status...`;case"ssl_check":return`Sysadmin${n}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${n}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${n}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${n}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${n}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${n}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${n}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${n}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${n}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${n}: cron ${e.cron_action||""}...`;default:return`Sysadmin${n}: ${e.action}...`}}case"visual_diff":return"Comparing screenshots (pixel diff)...";case"responsive_sweep":return`Responsive sweep: ${(e.url||"").substring(0,50)}...`;case"visual_annotate":return`Annotating screenshot (${(e.annotations||[]).length} markers)...`;case"visual_watch":return`Visual watch: ${(e.url||"").substring(0,50)}...`;case"design_tokens":return"Extracting design tokens...";case"design_compare":return"Comparing against reference design...";default:return`Running: ${t}`}}function Jx(t,e,n,o){let s=String(n||""),r=Il(t),i=` ${T.subtle}\u2502${T.reset} ${r.accent}${Ke.bold}${r.label}${T.reset} ${T.subtle}\xB7${T.reset} `;if(o){let u=s.split(`
|
|
29
29
|
`)[0];if(u.startsWith("BLOCKED:")){let m=u.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return`${i}${T.muted}blocked: ${m}${T.reset}`}let d=u.replace(/^ERROR:\s*/i,"").substring(0,80),f=s.match(/\nHINT: (.+)/),p=f?`
|
|
30
|
-
${T.muted}${f[1].substring(0,100)}${T.reset}`:"";return`${i}${T.error}${d}${T.reset}${p}`}let a;switch(t){case"read_file":{let u=Fx(s),d=u.length,f=u[u.length-1],p=f?parseInt(f.lineNumber||"0"):0,m=e.line_start||e.line_end,h=e.path?
|
|
30
|
+
${T.muted}${f[1].substring(0,100)}${T.reset}`:"";return`${i}${T.error}${d}${T.reset}${p}`}let a;switch(t){case"read_file":{let u=Fx(s),d=u.length,f=u[u.length-1],p=f?parseInt(f.lineNumber||"0"):0,m=e.line_start||e.line_end,h=e.path?Yp.basename(e.path):null,g=h?` ${T.muted}from ${h}${T.reset}`:"";m&&p>d?a=`Read lines ${e.line_start||1}\u2013${p}${g}`:a=`Read ${d} line${d!==1?"s":""}${g}`;let y=Bx(e.path,u,{maxLines:4,maxContent:120});y&&(a+=`
|
|
31
31
|
${y}`);break}case"write_file":{let d=(e.content||"").split(`
|
|
32
|
-
`).length,f=e.path?
|
|
32
|
+
`).length,f=e.path?Yp.basename(e.path):null,p=f?`Wrote ${f} \xB7 ${d} line${d!==1?"s":""}`:`Wrote ${d} line${d!==1?"s":""}`,{highlightLines:m}=la(),h=m(e.content||"",e.path||null),g=40,y=8;if(d<=g){let w=h.map(x=>` ${x}`).join(`
|
|
33
33
|
`);a=`${p}
|
|
34
34
|
${w}`}else{let w=h.slice(0,y).map(x=>` ${x}`).join(`
|
|
35
35
|
`);a=`${p}
|
|
@@ -39,10 +39,10 @@ ${w}
|
|
|
39
39
|
`),f=u.length,p=d.length,m=e.path?da(e.path):null,h=m?` ${T.muted}${m}${T.reset}`:"",g=jl(e.path,e.old_text,e.new_text,{indent:" ",maxLines:4,maxContent:96});a=`${T.diff_rem}\u2212${f}${T.reset} ${T.diff_add}+${p}${T.reset}${h}`+(g?`
|
|
40
40
|
`+g:"");break}case"patch_file":{let u=e.patches||[],d=u.reduce((g,y)=>g+(y.old_text||"").split(`
|
|
41
41
|
`).length,0),f=u.reduce((g,y)=>g+(y.new_text||"").split(`
|
|
42
|
-
`).length,0),p=e.path?da(e.path):null,m=p?` ${T.muted}${p}${T.reset}`:"";a=`${u.length} patch${u.length!==1?"es":""} ${T.diff_rem}\u2212${d}${T.reset} ${T.diff_add}+${f}${T.reset}${m}`;let h=
|
|
42
|
+
`).length,0),p=e.path?da(e.path):null,m=p?` ${T.muted}${p}${T.reset}`:"";a=`${u.length} patch${u.length!==1?"es":""} ${T.diff_rem}\u2212${d}${T.reset} ${T.diff_add}+${f}${T.reset}${m}`;let h=Qp(e.path,u,{indent:" ",maxPatches:3,maxLinesPerSide:2,maxContent:92});h&&(a+=`
|
|
43
43
|
${h}`);break}case"bash":{let d=s.match(/^EXIT (\d+)/),f=s.split(`
|
|
44
44
|
`).filter(g=>g&&!g.startsWith("EXIT ")&&!g.startsWith("HINT:")&&g.trim()),p=d?d[1]==="0"?`${T.success}\u2713${T.reset}`:`${T.error}\u2717 Exit ${d[1]}${T.reset}`:`${T.success}\u2713${T.reset}`,m=s.match(/\nHINT: (.+)/);if(m)a=`${p} ${T.muted}\u2014 ${m[1].substring(0,100)}${T.reset}`;else if(f.length===0)a=p;else{let g=d&&d[1]!=="0",y=g?f.slice(-3):f.slice(0,3),w=f.length-3,x=y.map((S,k)=>k===0?`${p} ${T.muted}${S.substring(0,120)}${T.reset}`:` ${T.muted}${S.substring(0,120)}${T.reset}`);if(w>0){let S=g?` ${T.subtle}${w} lines above\u2026${T.reset}`:` ${T.subtle}\u2026 +${w} lines${T.reset}`;g?x.unshift(S):x.push(S)}a=x.join(`
|
|
45
|
-
`)}let h=
|
|
45
|
+
`)}let h=Zp(e.command,{indent:" ",maxLines:2,maxContent:108});h&&(a=`${h}
|
|
46
46
|
${a}`);break}case"grep":case"search_files":{if(s.includes("(no matches)")||s==="no matches")a=`No matches${e.pattern?` ${T.muted}"${String(e.pattern).substring(0,40)}"${T.reset}`:""}`;else{let y=function(k){let v=k.indexOf(":");if(v===-1)return`${T.muted}${k.substring(0,90)}${T.reset}`;let C=k.substring(0,v),q=k.substring(v+1),D=q.match(/^(\d+)[:-](.*)/s),ee=D?`:${D[1]}`:"",ue=(D?D[2]:q).trim(),le=`${T.subtle}${u.basename(C)}${ee}${T.reset}`,de=`${T.muted}${ue.substring(0,80)}${ue.length>80?"\u2026":""}${T.reset}`;return`${le} ${de}`};var c=y;let u=require("path"),d=s.split(`
|
|
47
47
|
`).filter(Boolean),f=d.length,m=new Set(d.map(k=>k.split(":")[0]).filter(Boolean)).size,h=e.pattern?` ${T.muted}"${String(e.pattern).substring(0,40)}"${T.reset}`:"",g=m>1?`${f} match${f!==1?"es":""} in ${m} files${h}`:`${f} match${f!==1?"es":""}${h}`,w=e.path?`
|
|
48
48
|
${T.subtle}path:${T.reset} ${T.muted}${String(e.path).substring(0,70)}${T.reset}`:"",x=d.slice(0,5).map((k,v)=>v===0?`${g}${w}
|
|
@@ -62,22 +62,22 @@ ${g.join(`
|
|
|
62
62
|
`).filter(m=>m.trim()&&!m.startsWith("EXIT ")),p=d?`${T.error}\u2717${T.reset}`:`${T.success}\u2713${T.reset}`;if(f.length===0)a=p;else{if(f.length>2&&f.every(w=>/^\[/.test(w.trim()))){a=`${p} ${f.length} log lines`;break}let h=d?f.slice(-3):f.slice(0,3),g=f.length-3,y=h.map((w,x)=>x===0?`${p} ${T.muted}${w.substring(0,120)}${T.reset}`:` ${T.muted}${w.substring(0,120)}${T.reset}`);if(g>0){let w=d?` ${T.subtle}${g} lines above\u2026${T.reset}`:` ${T.subtle}\u2026 +${g} lines${T.reset}`;d?y.unshift(w):y.push(w)}a=y.join(`
|
|
63
63
|
`)}break}default:{let u=s.split(`
|
|
64
64
|
`).filter(d=>d.trim()&&!d.startsWith("EXIT ")&&!d.startsWith("HINT:"));if(u.length>0){let d=u[0].trim().substring(0,90),f=u.length>1?` ${T.subtle}\u2026 +${u.length-1} lines${T.reset}`:"";a=`${T.muted}${d}${T.reset}${f}`}else a=`${r.label} complete`}}return`${i}${a}${T.reset}`}function Zx(t,e,n,o,s,r){let i=Math.round(o/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,c=`
|
|
65
|
-
${T.success}\u25C6${Ke.reset} ${Ke.bold}${t}${Ke.reset}`;return c+=` ${T.subtle}\u2501\u2501${T.reset} ${Ke.dim}${a}`,r.size>0&&(c+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),s.size>0&&(c+=` \xB7 ${s.size} scanned`),c+=Ke.reset,c}
|
|
65
|
+
${T.success}\u25C6${Ke.reset} ${Ke.bold}${t}${Ke.reset}`;return c+=` ${T.subtle}\u2501\u2501${T.reset} ${Ke.dim}${a}`,r.size>0&&(c+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),s.size>0&&(c+=` \xB7 ${s.size} scanned`),c+=Ke.reset,c}eh.exports={C:Ke,formatToolCall:Gx,formatResult:Yx,getToolSpinnerText:Vx,formatToolSummary:Jx,formatSectionHeader:Hx,formatMilestone:Zx,getThinkingVerb:Xx,setActiveModelForSpinner:Kx,THINKING_VERBS:fa}});var He=X((gI,sh)=>{var{T:Un}=Lt(),Dl=Un,Qx=require("path"),nh=["01100110","01111110","01111110","01011010","01111110","00111100"];function ev(t,e){let n=[];for(let o=0;o<t.length;o+=2){let s="";for(let r=0;r<t[0].length;r++){let i=t[o][r]==="1",a=o+1<t.length&&t[o+1][r]==="1";i&&a?s+=`${e}\u2588\x1B[0m`:i&&!a?s+=`${e}\u2580\x1B[0m`:!i&&a?s+=`${e}\u2584\x1B[0m`:s+=" "}n.push(s)}return n}function tv(t,e,n={}){let o=Dl.bold,s=Dl.reset,r=ev(nh,Un.banner_logo),i=n.yolo?` ${o}${Un.banner_yolo}\u26A1 YOLO${s}`:"",a=n.gemini?` ${o}${Un.banner_gemini}\u2726 GEMINI${s}`:"",c=Po().version,u=e?Qx.basename(e):null,d=`${Un.banner_model}[${t||"model"}]${s}`,f=`${Un.banner_version}[${u||"workspace"}]${s}`,p=[` ${Un.banner_name}${o}nex-code${s} ${Un.banner_version}v${c}${s}`,` ${d} ${f}`,` ${Un.banner_logo}${o}terminal workbench${s} ${Un.muted}\xB7 /help${s}${a}${i}`,""],m=Math.max(r.length,p.length),h=Math.floor((m-r.length)/2),g=Math.floor((m-p.length)/2),y=nh[0].length,w=[];for(let x=0;x<m;x++){let S=r[x-h]??" ".repeat(y),k=p[x-g]??"";w.push(S+k)}console.log(`
|
|
66
66
|
`+w.join(`
|
|
67
67
|
`)+`
|
|
68
|
-
`)}var{Spinner:nv,MultiProgress:sv,TaskProgress:ov,ToolProgress:rv,setActiveTaskProgress:iv,getActiveTaskProgress:av,cleanupTerminal:cv}=qs(),{formatToolCall:lv,formatResult:uv,getToolSpinnerText:dv,formatToolSummary:fv,formatSectionHeader:pv,formatMilestone:hv,getThinkingVerb:mv,setActiveModelForSpinner:gv}=
|
|
69
|
-
`){u(s);return}if(p==="\x1B[A"){s=(s-1+n.length)%n.length,a();return}if(p==="\x1B[B"){s=(s+1)%n.length,a();return}let m=p.toLowerCase().trim();if(m==="y"){c(!0);return}if(m==="n"){c(!1);return}if(m==="a"&&e.toolName){pa(e.toolName),c(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",d)})}function Ov(t,e){let n=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(o=>{let s=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(pa(e.toolName),o(!0)):o(i!=="n")};if(Bs)Bs.question(`${Wn.yellow}${t} ${n}${Wn.reset}`,s);else{let r=yv.createInterface({input:process.stdin,output:process.stdout});r.question(`${Wn.yellow}${t} ${n}${Wn.reset}`,i=>{r.close(),s(i)})}})}var pa=()=>{};function Mv(t){pa=t}
|
|
70
|
-
`);this.buffer=n.pop()||"";for(let o of n){let s=this.parseLine(o);if(s?.done)return s}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},ha=class extends qo{constructor(e,n={}){super(e,n),this.toolCallsMap={}}parseLine(e){let n=e.trim();if(!n||!n.startsWith("data: "))return{done:!1};let o=n.slice(6);if(o==="[DONE]")return{done:!0,result:this.getResult()};let s;try{s=JSON.parse(o)}catch{return{done:!1}}let r=s.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a;i.index!==void 0&&i.index!==null?a=i.index:i.id?a=`id:${i.id}`:a=0,this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},ma=class extends Do{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i}){let a={model:e,messages:n,max_tokens:s,temperature:r};return i&&(a.stream=!0),o&&o.length>0&&(a.tools=o),a}normalizeResponse(e){let n=e.choices?.[0]?.message||{},o=(n.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:n.content||"",tool_calls:o}}createStreamParser(e,n={}){return new ha(e,n)}},ga=class extends qo{constructor(e,n={}){super(e,n),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let n=e.trim();if(!n.startsWith("data: "))return{done:!1};let o=n.slice(6),s;try{s=JSON.parse(o)}catch{return{done:!1}}switch(s.type){case"content_block_start":{let r=s.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=s.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let n={};if(e.inputJson)try{n=JSON.parse(e.inputJson)}catch{n=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:n}}})}}},Gl="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",ya=class extends Do{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let c={model:e,messages:n,max_tokens:s,temperature:r};if(i&&(c.stream=!0),a?.system){let u=a.system,d=u.indexOf(Gl);if(d!==-1){let f=u.slice(0,d).trimEnd(),p=u.slice(d+Gl.length).trimStart();c.system=[{type:"text",text:f},{type:"text",text:p,cache_control:{type:"ephemeral"}}]}else c.system=u}return o&&o.length>0&&(c.tools=o),c}formatTools(e){return!e||e.length===0?[]:e.map(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let n="",o=[];for(let s of e.content||[])s.type==="text"?n+=s.text:s.type==="tool_use"&&o.push({id:s.id,function:{name:s.name,arguments:s.input}});return{content:n,tool_calls:o}}createStreamParser(e,n={}){return new ga(e,n)}};function uh(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 $a=class extends qo{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:uh(e.function?.arguments??e.arguments)}}))}}},wa=class extends Do{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let c={model:e,messages:n,stream:i,options:{temperature:r,num_predict:s,repeat_penalty:a?.repeat_penalty??1.05}};return o&&o.length>0&&(c.tools=o),c}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:(n.tool_calls||[]).map((o,s)=>({id:o.id||`ollama-${Date.now()}-${s}`,function:{name:o.function?.name||o.name||"unknown",arguments:uh(o.function?.arguments??o.arguments)}}))}}createStreamParser(e,n={}){return new $a(e,n)}},Pv=new ma,Lv=new ya,Iv=new wa;dh.exports={ANTHROPIC_CACHE_BOUNDARY:Gl,WireProtocol:Do,StreamParser:qo,OpenAICompatibleProtocol:ma,AnthropicProtocol:ya,OllamaChatProtocol:wa,OpenAIStreamParser:ha,AnthropicStreamParser:ga,OllamaStreamParser:$a,openaiProtocol:Pv,anthropicProtocol:Lv,ollamaProtocol:Iv}});var hh=X((wI,ph)=>{var ba=require("axios"),jv=require("http"),Dv=require("https"),{BaseProvider:qv,readStreamErrorBody:Fv}=jo(),{ollamaProtocol:Us}=Fo(),_a=new jv.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),xa=new Dv.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),fh={"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}},Yl=class extends qv{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||fh,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){ba.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:_a,httpsAgent:xa}).then(e=>{let n=e.data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await ba.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:_a,httpsAgent:xa})).data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(n=>{if(Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:n.role,content:o.join(`
|
|
71
|
-
`)};return s.length>0&&(r.images=s),n.tool_call_id&&(r.tool_call_id=n.tool_call_id),r}return n})}async chat(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=Us.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1,extra:{repeat_penalty:o.repeat_penalty}}),c;try{c=await ba.post(`${this.baseUrl}${Us.getEndpoint()}`,a,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:_a,httpsAgent:xa})}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 Us.normalizeResponse(c.data)}async stream(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),c=o.onThinkingToken||(()=>{}),u=Us.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0,extra:{repeat_penalty:o.repeat_penalty}}),d;try{d=await ba.post(`${this.baseUrl}${Us.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:_a,httpsAgent:xa})}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 Fv(p,y=>y?.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=Us.createStreamParser(a,{onThinkingToken:c});return new Promise((p,m)=>{o.signal&&o.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:y}=f.feed(h.toString());g&&p(y)}),d.data.on("error",h=>{if(o.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 Us.normalizeResponse(e)}};
|
|
72
|
-
`)||JSON.stringify(e.content):n=typeof e.content=="string"?e.content:JSON.stringify(e.content),{role:"tool",content:n,tool_call_id:e.tool_call_id}}if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),c=Ws.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await
|
|
73
|
-
|
|
74
|
-
`:"")+s.content;continue}if(s.role!=="system"&&s.role!=="tool"&&this._messageFormatCache.has(s)){o.push(this._messageFormatCache.get(s));continue}let r=this._formatSingleMessage(s,o);if(r){if(s.role!=="system"&&s.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(s);this._messageStringCache.set(i,r),this._messageFormatCache.set(s,r)}o.push(r)}}for(let s=o.length-1;s>0;s--)o[s].role==="user"&&o[s-1].role==="user"&&o.splice(s,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:o,system:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let s of e.tool_calls)o.push({type:"tool_use",id:s.id||`toolu-${Date.now()}`,name:s.function.name,input:typeof s.function.arguments=="string"?JSON.parse(s.function.arguments||"{}"):s.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=n[n.length-1],s;if(Array.isArray(e.content)){let i=[];for(let a of e.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});s=i}else s=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:s};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let o=[];for(let s of e.content)s.type==="text"?o.push({type:"text",text:s.text??""}):s.type==="image"&&s.data&&o.push({type:"image",source:{type:"base64",media_type:s.media_type||"image/png",data:s.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return bs.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,{messages:c,system:u}=this.formatMessages(e),d=this.formatTools(n),f=bs.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:u}}),p;try{p=await wh.post(`${this.baseUrl}${bs.getEndpoint()}`,f,{timeout:o.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 bs.normalizeResponse(p.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,c=o.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f=this.formatTools(n),p=bs.buildRequestBody({model:r,messages:u,tools:f,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:d}}),m;try{m=await wh.post(`${this.baseUrl}${bs.getEndpoint()}`,p,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let y=g.response?.status?` [HTTP ${g.response.status}]`:"",w=await Hv(g,x=>x?.error?.message||x?.error);throw new Error(`API Error${y}: ${w}`)}let h=bs.createStreamParser(c);return new Promise((g,y)=>{o.signal&&o.signal.addEventListener("abort",()=>{m.data.destroy(),y(new DOMException("The operation was aborted","AbortError"))},{once:!0}),m.data.on("data",w=>{let{done:x,result:S}=h.feed(w.toString());x&&g(S)}),m.data.on("error",w=>{o.signal?.aborted||y(new Error(`Stream error: ${w.message}`))}),m.data.on("end",()=>{g(h.flush())})})}normalizeResponse(e){return bs.normalizeResponse(e)}};_h.exports={AnthropicProvider:Kl,ANTHROPIC_MODELS:bh}});var Eh=X((xI,Sh)=>{var vh=require("axios"),{BaseProvider:Yv,readStreamErrorBody:zv}=jo(),{openaiProtocol:Hs}=Fo(),kh={"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}},Xl=class extends Yv{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||kh,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),c=Hs.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await vh.post(`${this.baseUrl}${Hs.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return Hs.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,a=o.onToken||(()=>{}),{messages:c}=this.formatMessages(e),u=Hs.buildRequestBody({model:s,messages:c,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),d;try{d=await vh.post(`${this.baseUrl}${Hs.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",h=await zv(p,g=>g?.error?.message||g?.error);throw new Error(`API Error${m}: ${h}`)}let f=Hs.createStreamParser(a);return new Promise((p,m)=>{o.signal&&o.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:y}=f.feed(h.toString());g&&p(y)}),d.data.on("error",h=>{o.signal?.aborted||m(new Error(`Stream error: ${h.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return Hs.normalizeResponse(e)}};Sh.exports={GeminiProvider:Xl,GEMINI_MODELS:kh}});var Ch=X((vI,Rh)=>{var va=require("axios"),{BaseProvider:Kv,readStreamErrorBody:Xv}=jo(),{ollamaProtocol:Gs}=Fo(),Th="http://localhost:11434",Vl=class extends Kv{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Th,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 va.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of n){let s=o.name||o.model;if(!s)continue;let r=s.replace(/:latest$/,""),i=32768;try{let a=await va.post(`${this.baseUrl}/api/show`,{name:s},{timeout:5e3}),c=a.data?.model_info||a.data?.details||{};i=c["general.context_length"]||c["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:o.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:"user",content:o.join(`
|
|
75
|
-
`)};return s.length>0&&(r.images=s),r}return n})}async chat(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=Gs.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await va.post(`${this.baseUrl}${Gs.getEndpoint()}`,r,{timeout:o.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let c=a.response?.status?` [HTTP ${a.response.status}]`:"",u=a.response?.data?.error||a.message;throw new Error(`API Error${c}: ${u}`)}return Gs.normalizeResponse(i.data)}async stream(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),i=Gs.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),a;try{a=await va.post(`${this.baseUrl}${Gs.getEndpoint()}`,i,{timeout:o.timeout||this.timeout,responseType:"stream",signal:o.signal})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=await Xv(u,p=>p?.error);throw new Error(`API Error${d}: ${f}`)}let c=Gs.createStreamParser(r);return new Promise((u,d)=>{o.signal&&o.signal.addEventListener("abort",()=>{a.data.destroy(),d(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",f=>{let{done:p,result:m}=c.feed(f.toString());p&&u(m)}),a.data.on("error",f=>{o.signal?.aborted||d(new Error(`Stream error: ${f.message}`))}),a.data.on("end",()=>{u(c.flush())})})}normalizeResponse(e){return Gs.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}};
|
|
76
|
-
`)}}function Zl(t,e){let n=
|
|
77
|
-
`)}function ok(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function rk(t,e,n,o){let s=Zl(t,e),r=(n*s.input+o*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function ik(){ka=[]}function ak(t,e){_s[t]=e}function ck(t){delete _s[t]}function lk(){return{..._s}}function
|
|
78
|
-
`),a}catch(a){throw s.stop(),a}}async function Sk(t,e){return Mr.callChat(t,e)}
|
|
68
|
+
`)}var{Spinner:nv,MultiProgress:sv,TaskProgress:ov,ToolProgress:rv,setActiveTaskProgress:iv,getActiveTaskProgress:av,cleanupTerminal:cv}=qs(),{formatToolCall:lv,formatResult:uv,getToolSpinnerText:dv,formatToolSummary:fv,formatSectionHeader:pv,formatMilestone:hv,getThinkingVerb:mv,setActiveModelForSpinner:gv}=th();sh.exports={C:Dl,banner:tv,Spinner:nv,MultiProgress:sv,TaskProgress:ov,ToolProgress:rv,setActiveTaskProgress:iv,getActiveTaskProgress:av,cleanupTerminal:cv,formatToolCall:lv,formatResult:uv,getToolSpinnerText:dv,formatToolSummary:fv,formatSectionHeader:pv,formatMilestone:hv,getThinkingVerb:mv,setActiveModelForSpinner:gv}});var It=X((yI,lh)=>{var yv=require("readline"),{C:Wn}=He(),$v=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,wv=/^=([\w-]+)/;function Or(t){return typeof t!="string"?t:t.replace($v,"").replace(wv,"$1")}var Bl=[/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/],oh=[...Bl,/\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 bv(t){for(let e of oh)if(e.test(t))return e;return null}var rh=[/\.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)/],_v=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,ql=[/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 ih(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let o=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(o.length===0)return!1;let s=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>s(u)):ql.some(c=>c.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:ql.some(a=>a.test(i))};return o.every(s)}var Ul=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/,/--no-verify\b/,/git\s+reset\s+--hard\b/,/git\s+clean\s+-[a-z]*f/,/git\s+checkout\s+--\s/,/git\s+push\s+(?:--force\b|-f\b)/,/\b(?:curl|wget|fetch)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|ksh|dash|python|python3|perl|ruby|node)\b/,/\b(?:curl|wget)\b[^;&`$()]*\$\([^)]*\)/,/\bbase64\s+(?:-d|--decode|-D)\b[^|;&`$()]*\|\s*(?:sh|bash|zsh|python|python3|perl|ruby|node)\b/,/\beval\s+["'`]?\$\(\s*(?:curl|wget|fetch)\b/,/\bbash\s+-i\s*>&?\s*\/dev\/tcp\//,/\bnc\s+(?:-[a-z]*e|-[a-z]*c)\b/,/\bmkfifo\b[^;&`]*;\s*(?:nc|ncat|telnet)\b/],ah=[/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/],ch=[...Ul,...ah],Wl=!1,Bs=null,Fl=null;function xv(t){Wl=t}function vv(t){Fl=t}function kv(){return Wl}function Sv(t){Bs=t}function Ev(t){let e=Or(t);for(let n of Bl)if(n.test(e))return n;return null}function Tv(t){let e=Or(t);if(/ssh\s/.test(e)&&ih(e))return!1;for(let n of ch)if(n.test(e))return!0;return!1}function Rv(t){let e=Or(t);for(let n of Ul)if(n.test(e))return!0;return!1}function Cv(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=Or(t);if(!_v.test(e))return null;for(let n of rh)if(n.test(e))return n;return null}function Av(t,e={}){if(Wl)return Promise.resolve(!0);if(Fl)return Fl(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return Ov(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;Bs&&Bs.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${Wn.yellow}${t}${Wn.reset}`;for(let m=0;m<n.length;m++){let h=m===s,g=h?`${Wn.yellow}\u276F${Wn.reset}`:" ",y=h?`${Wn.yellow}${n[m]}${Wn.reset}`:n[m];p+=`\x1B[${f+1+m};1H\x1B[2K ${g} ${y}`}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(),Bs&&Bs.resume(),o(f)},u=f=>{if(f===1){c(!1);return}f===2&&e.toolName&&pa(e.toolName),c(!0)},d=f=>{if(f[0]===3){c(!1);return}let p=f.toString();if(p==="\r"||p===`
|
|
69
|
+
`){u(s);return}if(p==="\x1B[A"){s=(s-1+n.length)%n.length,a();return}if(p==="\x1B[B"){s=(s+1)%n.length,a();return}let m=p.toLowerCase().trim();if(m==="y"){c(!0);return}if(m==="n"){c(!1);return}if(m==="a"&&e.toolName){pa(e.toolName),c(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",d)})}function Ov(t,e){let n=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(o=>{let s=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(pa(e.toolName),o(!0)):o(i!=="n")};if(Bs)Bs.question(`${Wn.yellow}${t} ${n}${Wn.reset}`,s);else{let r=yv.createInterface({input:process.stdin,output:process.stdout});r.question(`${Wn.yellow}${t} ${n}${Wn.reset}`,i=>{r.close(),s(i)})}})}var pa=()=>{};function Mv(t){pa=t}lh.exports={sanitizeBashCommand:Or,FORBIDDEN_PATTERNS:Bl,SSH_FORBIDDEN_PATTERNS:oh,BASH_PROTECTED_PATHS:rh,SSH_SAFE_PATTERNS:ql,isSSHReadOnly:ih,DANGEROUS_BASH:ch,CRITICAL_BASH:Ul,NOTABLE_BASH:ah,isForbidden:Ev,isSSHForbidden:bv,isDangerous:Tv,isCritical:Rv,isBashPathForbidden:Cv,confirm:Av,setAutoConfirm:xv,getAutoConfirm:kv,setConfirmHook:vv,setReadlineInterface:Sv,setAllowAlwaysHandler:Mv}});var jo=X(($I,uh)=>{async function Nv(t,e){if(!t.response?.data)return t.message;let n=t.response.data;if(typeof n=="object"&&n!==null&&typeof n.pipe!="function")return e(n)||t.message;try{let o=await new Promise((r,i)=>{let a=[];n.on("data",c=>a.push(c)),n.on("end",()=>r(Buffer.concat(a).toString("utf8"))),n.on("error",i)}),s=JSON.parse(o);return e(s)||o||t.message}catch{return t.message}}var Hl=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,n,o={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,n,o={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};uh.exports={BaseProvider:Hl,readStreamErrorBody:Nv}});var Fo=X((wI,fh)=>{var Do=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")}},qo=class{constructor(e,n={}){this.onToken=e,this.callbacks=n,this.content="",this.buffer=""}feed(e){this.buffer+=e;let n=this.buffer.split(`
|
|
70
|
+
`);this.buffer=n.pop()||"";for(let o of n){let s=this.parseLine(o);if(s?.done)return s}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},ha=class extends qo{constructor(e,n={}){super(e,n),this.toolCallsMap={}}parseLine(e){let n=e.trim();if(!n||!n.startsWith("data: "))return{done:!1};let o=n.slice(6);if(o==="[DONE]")return{done:!0,result:this.getResult()};let s;try{s=JSON.parse(o)}catch{return{done:!1}}let r=s.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a;i.index!==void 0&&i.index!==null?a=i.index:i.id?a=`id:${i.id}`:a=0,this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},ma=class extends Do{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i}){let a={model:e,messages:n,max_tokens:s,temperature:r};return i&&(a.stream=!0),o&&o.length>0&&(a.tools=o),a}normalizeResponse(e){let n=e.choices?.[0]?.message||{},o=(n.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:n.content||"",tool_calls:o}}createStreamParser(e,n={}){return new ha(e,n)}},ga=class extends qo{constructor(e,n={}){super(e,n),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let n=e.trim();if(!n.startsWith("data: "))return{done:!1};let o=n.slice(6),s;try{s=JSON.parse(o)}catch{return{done:!1}}switch(s.type){case"content_block_start":{let r=s.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=s.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let n={};if(e.inputJson)try{n=JSON.parse(e.inputJson)}catch{n=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:n}}})}}},Gl="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",ya=class extends Do{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let c={model:e,messages:n,max_tokens:s,temperature:r};if(i&&(c.stream=!0),a?.system){let u=a.system,d=u.indexOf(Gl);if(d!==-1){let f=u.slice(0,d).trimEnd(),p=u.slice(d+Gl.length).trimStart();c.system=[{type:"text",text:f},{type:"text",text:p,cache_control:{type:"ephemeral"}}]}else c.system=u}return o&&o.length>0&&(c.tools=o),c}formatTools(e){return!e||e.length===0?[]:e.map(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let n="",o=[];for(let s of e.content||[])s.type==="text"?n+=s.text:s.type==="tool_use"&&o.push({id:s.id,function:{name:s.name,arguments:s.input}});return{content:n,tool_calls:o}}createStreamParser(e,n={}){return new ga(e,n)}};function dh(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 $a=class extends qo{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:dh(e.function?.arguments??e.arguments)}}))}}},wa=class extends Do{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:a}){let c={model:e,messages:n,stream:i,options:{temperature:r,num_predict:s,repeat_penalty:a?.repeat_penalty??1.05}};return o&&o.length>0&&(c.tools=o),c}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:(n.tool_calls||[]).map((o,s)=>({id:o.id||`ollama-${Date.now()}-${s}`,function:{name:o.function?.name||o.name||"unknown",arguments:dh(o.function?.arguments??o.arguments)}}))}}createStreamParser(e,n={}){return new $a(e,n)}},Pv=new ma,Lv=new ya,Iv=new wa;fh.exports={ANTHROPIC_CACHE_BOUNDARY:Gl,WireProtocol:Do,StreamParser:qo,OpenAICompatibleProtocol:ma,AnthropicProtocol:ya,OllamaChatProtocol:wa,OpenAIStreamParser:ha,AnthropicStreamParser:ga,OllamaStreamParser:$a,openaiProtocol:Pv,anthropicProtocol:Lv,ollamaProtocol:Iv}});var mh=X((bI,hh)=>{var ba=require("axios"),jv=require("http"),Dv=require("https"),{BaseProvider:qv,readStreamErrorBody:Fv}=jo(),{ollamaProtocol:Us}=Fo(),_a=new jv.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),xa=new Dv.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),ph={"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}},Yl=class extends qv{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||ph,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){ba.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:_a,httpsAgent:xa}).then(e=>{let n=e.data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await ba.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:_a,httpsAgent:xa})).data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(n=>{if(Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:n.role,content:o.join(`
|
|
71
|
+
`)};return s.length>0&&(r.images=s),n.tool_call_id&&(r.tool_call_id=n.tool_call_id),r}return n})}async chat(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=Us.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1,extra:{repeat_penalty:o.repeat_penalty}}),c;try{c=await ba.post(`${this.baseUrl}${Us.getEndpoint()}`,a,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:_a,httpsAgent:xa})}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 Us.normalizeResponse(c.data)}async stream(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),c=o.onThinkingToken||(()=>{}),u=Us.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0,extra:{repeat_penalty:o.repeat_penalty}}),d;try{d=await ba.post(`${this.baseUrl}${Us.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:_a,httpsAgent:xa})}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 Fv(p,y=>y?.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=Us.createStreamParser(a,{onThinkingToken:c});return new Promise((p,m)=>{o.signal&&o.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:y}=f.feed(h.toString());g&&p(y)}),d.data.on("error",h=>{if(o.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 Us.normalizeResponse(e)}};hh.exports={OllamaProvider:Yl,OLLAMA_MODELS:ph}});var wh=X((_I,$h)=>{var gh=require("axios"),{BaseProvider:Bv,readStreamErrorBody:Uv}=jo(),{openaiProtocol:Ws}=Fo(),yh={"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}},zl=class extends Bv{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||yh,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool"){let n;return Array.isArray(e.content)?n=e.content.filter(s=>s.type==="text").map(s=>s.text).join(`
|
|
72
|
+
`)||JSON.stringify(e.content):n=typeof e.content=="string"?e.content:JSON.stringify(e.content),{role:"tool",content:n,tool_call_id:e.tool_call_id}}if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),c=Ws.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await gh.post(`${this.baseUrl}${Ws.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return Ws.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),{messages:c}=this.formatMessages(e),u=Ws.buildRequestBody({model:s,messages:c,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),d;try{d=await gh.post(`${this.baseUrl}${Ws.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",h=await Uv(p,g=>g?.error?.message||g?.error);throw new Error(`API Error${m}: ${h}`)}let f=Ws.createStreamParser(a);return new Promise((p,m)=>{o.signal&&o.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:y}=f.feed(h.toString());g&&p(y)}),d.data.on("error",h=>{o.signal?.aborted||m(new Error(`Stream error: ${h.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return Ws.normalizeResponse(e)}};$h.exports={OpenAIProvider:zl,OPENAI_MODELS:yh}});var vh=X((xI,xh)=>{var bh=require("axios"),{BaseProvider:Wv,readStreamErrorBody:Hv}=jo(),{anthropicProtocol:bs}=Fo(),_h={"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}},Gv="2023-06-01",Kl=class extends Wv{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||_h,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Gv}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n="",o=[];for(let s of e){if(s.role==="system"){n+=(n?`
|
|
73
|
+
|
|
74
|
+
`:"")+s.content;continue}if(s.role!=="system"&&s.role!=="tool"&&this._messageFormatCache.has(s)){o.push(this._messageFormatCache.get(s));continue}let r=this._formatSingleMessage(s,o);if(r){if(s.role!=="system"&&s.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(s);this._messageStringCache.set(i,r),this._messageFormatCache.set(s,r)}o.push(r)}}for(let s=o.length-1;s>0;s--)o[s].role==="user"&&o[s-1].role==="user"&&o.splice(s,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:o,system:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let s of e.tool_calls)o.push({type:"tool_use",id:s.id||`toolu-${Date.now()}`,name:s.function.name,input:typeof s.function.arguments=="string"?JSON.parse(s.function.arguments||"{}"):s.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=n[n.length-1],s;if(Array.isArray(e.content)){let i=[];for(let a of e.content)a.type==="text"?i.push({type:"text",text:a.text??""}):a.type==="image"&&a.data&&i.push({type:"image",source:{type:"base64",media_type:a.media_type||"image/png",data:a.data}});s=i}else s=typeof e.content=="string"?e.content:JSON.stringify(e.content);let r={type:"tool_result",tool_use_id:e.tool_call_id,content:s};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(r),null):{role:"user",content:[r]}}if(Array.isArray(e.content)){let o=[];for(let s of e.content)s.type==="text"?o.push({type:"text",text:s.text??""}):s.type==="image"&&s.data&&o.push({type:"image",source:{type:"base64",media_type:s.media_type||"image/png",data:s.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return bs.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,{messages:c,system:u}=this.formatMessages(e),d=this.formatTools(n),f=bs.buildRequestBody({model:r,messages:c,tools:d,maxTokens:a,temperature:o.temperature??this.temperature,stream:!1,extra:{system:u}}),p;try{p=await bh.post(`${this.baseUrl}${bs.getEndpoint()}`,f,{timeout:o.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 bs.normalizeResponse(p.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,c=o.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f=this.formatTools(n),p=bs.buildRequestBody({model:r,messages:u,tools:f,maxTokens:a,temperature:o.temperature??this.temperature,stream:!0,extra:{system:d}}),m;try{m=await bh.post(`${this.baseUrl}${bs.getEndpoint()}`,p,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let y=g.response?.status?` [HTTP ${g.response.status}]`:"",w=await Hv(g,x=>x?.error?.message||x?.error);throw new Error(`API Error${y}: ${w}`)}let h=bs.createStreamParser(c);return new Promise((g,y)=>{o.signal&&o.signal.addEventListener("abort",()=>{m.data.destroy(),y(new DOMException("The operation was aborted","AbortError"))},{once:!0}),m.data.on("data",w=>{let{done:x,result:S}=h.feed(w.toString());x&&g(S)}),m.data.on("error",w=>{o.signal?.aborted||y(new Error(`Stream error: ${w.message}`))}),m.data.on("end",()=>{g(h.flush())})})}normalizeResponse(e){return bs.normalizeResponse(e)}};xh.exports={AnthropicProvider:Kl,ANTHROPIC_MODELS:_h}});var Th=X((vI,Eh)=>{var kh=require("axios"),{BaseProvider:Yv,readStreamErrorBody:zv}=jo(),{openaiProtocol:Hs}=Fo(),Sh={"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}},Xl=class extends Yv{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Sh,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),c=Hs.buildRequestBody({model:s,messages:a,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await kh.post(`${this.baseUrl}${Hs.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return Hs.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,a=o.onToken||(()=>{}),{messages:c}=this.formatMessages(e),u=Hs.buildRequestBody({model:s,messages:c,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),d;try{d=await kh.post(`${this.baseUrl}${Hs.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let m=p.response?.status?` [HTTP ${p.response.status}]`:"",h=await zv(p,g=>g?.error?.message||g?.error);throw new Error(`API Error${m}: ${h}`)}let f=Hs.createStreamParser(a);return new Promise((p,m)=>{o.signal&&o.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:y}=f.feed(h.toString());g&&p(y)}),d.data.on("error",h=>{o.signal?.aborted||m(new Error(`Stream error: ${h.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return Hs.normalizeResponse(e)}};Eh.exports={GeminiProvider:Xl,GEMINI_MODELS:Sh}});var Ah=X((kI,Ch)=>{var va=require("axios"),{BaseProvider:Kv,readStreamErrorBody:Xv}=jo(),{ollamaProtocol:Gs}=Fo(),Rh="http://localhost:11434",Vl=class extends Kv{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Rh,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 va.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of n){let s=o.name||o.model;if(!s)continue;let r=s.replace(/:latest$/,""),i=32768;try{let a=await va.post(`${this.baseUrl}/api/show`,{name:s},{timeout:5e3}),c=a.data?.model_info||a.data?.details||{};i=c["general.context_length"]||c["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:o.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:"user",content:o.join(`
|
|
75
|
+
`)};return s.length>0&&(r.images=s),r}return n})}async chat(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=Gs.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await va.post(`${this.baseUrl}${Gs.getEndpoint()}`,r,{timeout:o.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let c=a.response?.status?` [HTTP ${a.response.status}]`:"",u=a.response?.data?.error||a.message;throw new Error(`API Error${c}: ${u}`)}return Gs.normalizeResponse(i.data)}async stream(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),i=Gs.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),a;try{a=await va.post(`${this.baseUrl}${Gs.getEndpoint()}`,i,{timeout:o.timeout||this.timeout,responseType:"stream",signal:o.signal})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=await Xv(u,p=>p?.error);throw new Error(`API Error${d}: ${f}`)}let c=Gs.createStreamParser(r);return new Promise((u,d)=>{o.signal&&o.signal.addEventListener("abort",()=>{a.data.destroy(),d(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",f=>{let{done:p,result:m}=c.feed(f.toString());p&&u(m)}),a.data.on("error",f=>{o.signal?.aborted||d(new Error(`Stream error: ${f.message}`))}),a.data.on("end",()=>{u(c.flush())})})}normalizeResponse(e){return Gs.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}};Ch.exports={LocalProvider:Vl,DEFAULT_LOCAL_URL:Rh}});var os=X((SI,Mh)=>{"use strict";var Qt=require("fs"),Oh=require("path");function Vv(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Jv(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function Zv(t,e){let n=Oh.dirname(t),o=Oh.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{Qt.existsSync(n)||Qt.mkdirSync(n,{recursive:!0,mode:448}),Qt.writeFileSync(o,e,{encoding:"utf-8",mode:384}),Qt.renameSync(o,t)}catch(s){try{Qt.unlinkSync(o)}catch{}throw s}}function Qv(t,e,{timeout:n=5e3,retryMs:o=50}={}){let s=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=Qt.openSync(s,"wx"),Qt.writeSync(i,Buffer.from(String(process.pid))),Qt.closeSync(i),i=-1;try{return e()}finally{try{Qt.unlinkSync(s)}catch{}}}catch(a){if(i!==-1)try{Qt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let c=Qt.readFileSync(s,"utf-8").trim(),u=parseInt(c,10);if(!Vv(u)){try{Qt.unlinkSync(s)}catch{}continue}}catch(c){if(c.code&&c.code!=="ENOENT")throw c;continue}if(Date.now()>=r){try{Qt.unlinkSync(s)}catch{}return e()}Jv(o)}}}Mh.exports={atomicWrite:Zv,withFileLockSync:Qv}});var xs=X((EI,Fh)=>{var Bo=require("fs"),Jl=require("path"),{T:Nh}=Lt(),{atomicWrite:ek,withFileLockSync:tk}=os(),Ph={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:{}},ka=[],_s={};function nk(t,e,n,o,s=0){if(ka.push({provider:t,model:e,input:n,output:o,cacheRead:s}),_s[t]!==void 0){let r=Dh(t);r.allowed||process.stderr.write(`${Nh.yellow}\u26A0 Budget limit reached for ${t}: $${r.spent.toFixed(2)} / $${r.limit.toFixed(2)}${Nh.reset}
|
|
76
|
+
`)}}function Zl(t,e){let n=Ph[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function Lh(t){let e=Zl(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Ih(){let t={};for(let i of ka){let a=`${i.provider}:${i.model}`;t[a]||(t[a]={provider:i.provider,model:i.model,requests:0,input:0,output:0,cacheRead:0}),t[a].requests++,t[a].input+=i.input,t[a].output+=i.output,t[a].cacheRead+=i.cacheRead||0}let e=Object.values(t).map(i=>({...i,cost:Lh(i)})),n=e.reduce((i,a)=>i+a.cost,0),o=e.reduce((i,a)=>i+a.input,0),s=e.reduce((i,a)=>i+a.output,0),r=e.reduce((i,a)=>i+(a.cacheRead||0),0);return{totalCost:n,totalInput:o,totalOutput:s,totalCacheRead:r,breakdown:e}}function sk(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:o}=Ih();if(o.length===0)return"No token usage recorded this session.";let s=[];s.push("Session Token Usage:"),s.push("");for(let r of o){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";s.push(` ${r.provider}:${r.model}`),s.push(` Input: ${r.input.toLocaleString()} tokens`),s.push(` Output: ${r.output.toLocaleString()} tokens`),s.push(` Cost: ${i}`)}return s.push(""),s.push(` Total: ${e.toLocaleString()} in + ${n.toLocaleString()} out = $${t.toFixed(4)}`),s.join(`
|
|
77
|
+
`)}function ok(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function rk(t,e,n,o){let s=Zl(t,e),r=(n*s.input+o*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function ik(){ka=[]}function ak(t,e){_s[t]=e}function ck(t){delete _s[t]}function lk(){return{..._s}}function jh(t){let e=0;for(let n of ka)n.provider===t&&(e+=Lh(n));return e}function Dh(t){let e=jh(t),n=_s[t];if(n===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let o=Math.max(0,n-e);return{allowed:e<n,spent:e,limit:n,remaining:o}}function qh(){let t=Jl.join(process.cwd(),".nex","config.json");if(Bo.existsSync(t))try{let e=JSON.parse(Bo.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(_s={...e.costLimits})}catch{}}function uk(){let t=Jl.join(process.cwd(),".nex"),e=Jl.join(t,"config.json");Bo.existsSync(t)||Bo.mkdirSync(t,{recursive:!0}),tk(e,()=>{let n={};if(Bo.existsSync(e))try{n=JSON.parse(Bo.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=_s,ek(e,JSON.stringify(n,null,2))})}function dk(){_s={}}qh();Fh.exports={PRICING:Ph,trackUsage:nk,getSessionCosts:Ih,formatCosts:sk,formatCostHint:rk,resetCosts:ik,getPricing:Zl,setCostLimit:ak,removeCostLimit:ck,getCostLimits:lk,getProviderSpend:jh,checkBudget:Dh,loadCostLimits:qh,saveCostLimits:uk,resetCostLimits:dk,estimateTokens:ok}});var Sa=X((TI,Bh)=>{function Ql(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var fk=Ql();function pk(...t){Ql()&&console.log(...t)}function hk(...t){Ql()&&console.warn(...t)}Bh.exports={DEBUG:fk,debugLog:pk,warnLog:hk}});var Hh=X((RI,Wh)=>{"use strict";var mk=new Set(["read_file","grep","glob","search_files","list_directory"]),gk=new Set(["write_file","edit_file","patch_file"]),yk=new Set(["bash"]),$k=new Set(["web_search","web_fetch","perplexity_search"]);function Uh(t,e){let n=0,o=0,s=0,r=0,i=0;for(let[a,c]of t)i+=c,mk.has(a)&&(n+=c),gk.has(a)&&(o+=c),yk.has(a)&&(s+=c),$k.has(a)&&(r+=c);return i===0?`Phase ${e}`:r/i>.5?"Research":n/i>.5?"Exploration":o/i>.3?"Implementation":s/i>.3&&o/i<.15?"Verification":`Phase ${e}`}var eu=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,n,o,s){if(this._disabled)return null;this._stepsThisPhase++;for(let i of n)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:Uh(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(o),filesModified:new Set(s)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};Wh.exports={MilestoneTracker:eu,_phaseName:Uh}});var Uo=X((CI,Gh)=>{var Mr=Xe(),wk={"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 bk(){return Mr.getActiveModel()}function _k(t){return Mr.setActiveModel(t)}function xk(){return Mr.getModelNames()}function vk(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let o=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(o)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let o=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(o)}catch{}let n=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)try{return JSON.parse(n[1].trim())}catch{}return null}async function kk(t,e){let{C:n}=He(),{Spinner:o}=He(),s=new o("Thinking...");s.start();let r=!0,i="";try{let a=await Mr.callStream(t,e,{onToken:c=>{r&&(s.stop(),process.stdout.write(`${n.blue}`),r=!1),process.stdout.write(c),i+=c}});return r?s.stop():process.stdout.write(`${n.reset}
|
|
78
|
+
`),a}catch(a){throw s.stop(),a}}async function Sk(t,e){return Mr.callChat(t,e)}Gh.exports={MODELS:wk,getActiveModel:bk,setActiveModel:_k,getModelNames:xk,callOllamaStream:kk,callOllama:Sk,parseToolArgs:vk}});var Kh=X((OI,zh)=>{var Ea=require("path"),{C:K}=He(),{T:tu,isDark:AI}=Lt(),{confirm:Ek,getAutoConfirm:Tk}=It(),Yh=2e3;function Nr(t,e){let n=t.split(`
|
|
79
79
|
`),o=e.split(`
|
|
80
|
-
`),s=[],r=n.length,i=o.length;if(r>
|
|
80
|
+
`),s=[],r=n.length,i=o.length;if(r>Yh||i>Yh){for(let f of n)s.push({type:"remove",line:f});for(let f of o)s.push({type:"add",line:f});return s}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]===o[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]===o[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:o[u-1]}),u--):(d.unshift({type:"remove",line:n[c-1]}),c--);return d}function Rk(t,e,n,o=3){console.log(`
|
|
81
81
|
${K.bold}${K.cyan} Diff: ${t}${K.reset}`);let s=Nr(e,n),r=[];if(s.forEach((c,u)=>{c.type!=="same"&&r.push(u)}),r.length===0){console.log(`${K.gray} (no changes)${K.reset}`);return}let i=Math.max(0,r[0]-o),a=Math.min(s.length,r[r.length-1]+o+1);i>0&&console.log(`${K.gray} ...${K.reset}`);for(let c=i;c<a;c++){let u=s[c];switch(u.type){case"remove":console.log(`${K.red} - ${u.line}${K.reset}`);break;case"add":console.log(`${K.green} + ${u.line}${K.reset}`);break;default:console.log(`${K.gray} ${u.line}${K.reset}`)}}a<s.length&&console.log(`${K.gray} ...${K.reset}`),console.log()}function Ck(t,e,n){console.log(`
|
|
82
82
|
${K.bold}${K.cyan} File exists \u2014 showing changes: ${t}${K.reset}`);let o=Nr(e,n),s=0;for(let i of o)i.type!=="same"&&s++;if(s===0){console.log(`${K.gray} (identical content)${K.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${K.gray} ...(${s-r} more changes)${K.reset}`);break}switch(i.type){case"remove":console.log(`${K.red} - ${i.line}${K.reset}`),r++;break;case"add":console.log(`${K.green} + ${i.line}${K.reset}`),r++;break;default:r>0&&console.log(`${K.gray} ${i.line}${K.reset}`)}}console.log()}function Ak(t,e){console.log(`
|
|
83
83
|
${K.bold}${K.cyan} New file: ${t}${K.reset}`);let n=e.split(`
|
|
@@ -87,36 +87,36 @@ ${K.bold}${K.cyan} Side-by-side: ${t}${K.reset}`),console.log(` ${K.dim}${"\u2
|
|
|
87
87
|
${K.green}\u23FA${K.reset} ${K.bold}${s}(${a})${K.reset}`),f===0&&p===0){console.log(` ${K.dim}\u23BF (no changes)${K.reset}
|
|
88
88
|
`);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(ue=>ue.severity==="error").length,q=i.filter(ue=>ue.severity==="warn").length,D=i.filter(ue=>ue.severity==="info").length,ee=[];C>0&&ee.push(`${K.red}${C} error${C!==1?"s":""}${K.dim}`),q>0&&ee.push(`${K.yellow}${q} warning${q!==1?"s":""}${K.dim}`),D>0&&ee.push(`${K.cyan}${D} info${D!==1?"s":""}${K.dim}`),m.push(`found ${ee.join(", ")}`)}console.log(` ${K.dim}\u23BF ${m.join(", ")}${K.reset}`);let g=[];c.forEach((C,q)=>{C.type!=="same"&&g.push(q)});let y=[],w=null,x=null;for(let C of g){let q=Math.max(0,C-r),D=Math.min(c.length-1,C+r);w===null?(w=q,x=D):(q<=x+1||(y.push([w,x]),w=q),x=D)}w!==null&&y.push([w,x]);let S=" ",k=process.stdout.columns||120;function v(C,q,D){let ee=D.replace(/\x1b\[[0-9;]*m/g,""),ue=D+" ".repeat(Math.max(0,k-ee.length));return`${C}${q}${ue}${K.reset}`}for(let C=0;C<y.length;C++){C>0&&console.log(`${S}${K.dim}\xB7\xB7\xB7${K.reset}`);let[q,D]=y[C];for(let ee=q;ee<=D;ee++){let ue=c[ee],le=ue.newLine!=null?ue.newLine:ue.oldLine,de=String(le).padStart(4),M=ue.type!=="remove"?i.filter(G=>G.line===ue.newLine):[];ue.type==="remove"?console.log(v(tu.diff_rem_bg,K.red,`${S}${de} - ${ue.line}`)):ue.type==="add"?console.log(v(tu.diff_add_bg,K.green,`${S}${de} + ${ue.line}`)):console.log(`${S}${K.dim}${de} ${K.reset}${ue.line}`);for(let G of M){let te=K.cyan,ge="\u2139";G.severity==="error"?(te=K.red,ge="\u2716"):G.severity==="warn"&&(te=K.yellow,ge="\u26A0"),console.log(`${S} ${te}${ge} ${G.message}${K.reset}`)}}}console.log()}function Pk(t,e,n={}){let o=Ea.isAbsolute(t)?Ea.relative(process.cwd(),t):t,s=e.split(`
|
|
89
89
|
`),r=n.annotations||[];console.log(`
|
|
90
|
-
${K.green}\u23FA${K.reset} ${K.bold}Create(${o})${K.reset}`);let i=[`${s.length} line${s.length!==1?"s":""}`];if(r.length>0){let f=r.filter(g=>g.severity==="error").length,p=r.filter(g=>g.severity==="warn").length,m=r.filter(g=>g.severity==="info").length,h=[];f>0&&h.push(`${K.red}${f} error${f!==1?"s":""}${K.dim}`),p>0&&h.push(`${K.yellow}${p} warning${p!==1?"s":""}${K.dim}`),m>0&&h.push(`${K.cyan}${m} info${m!==1?"s":""}${K.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${K.dim}\u23BF ${i.join(", ")}${K.reset}`);let c=" ",u=process.stdout.columns||120,d=Math.min(s.length,20);for(let f=0;f<d;f++){let p=String(f+1).padStart(4),m=f+1,h=r.filter(x=>x.line===m),g=`${c}${p} + ${s[f]}`,y=g.replace(/\x1b\[[0-9;]*m/g,""),w=g+" ".repeat(Math.max(0,u-y.length));console.log(`${tu.diff_add_bg}${K.green}${w}${K.reset}`);for(let x of h){let S=K.cyan,k="\u2139";x.severity==="error"?(S=K.red,k="\u2716"):x.severity==="warn"&&(S=K.yellow,k="\u26A0"),console.log(`${c} ${S}${k} ${x.message}${K.reset}`)}}s.length>20&&console.log(`${c}${K.dim} ...+${s.length-20} more lines${K.reset}`),console.log()}
|
|
91
|
-
`).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function Ra(t=!1){return await nu(`git diff ${t?"--cached":""}`)||""}async function ou(){return(await su()).map(e=>e.file)}async function
|
|
92
|
-
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&s++,f.startsWith("-")&&!f.startsWith("---")&&r++}else s=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":s>r*2?i="feat":r>s?i="refactor":i="fix";let 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:s,deletions:r}}}async function Dk(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Ta("checkout","-b",n)!==null?n:null}async function qk(t){return await Ta("add","-A"),await Ta("commit","-m",t)?await Ta("rev-parse","--short","HEAD"):null}async function Fk(){let t=await
|
|
93
|
-
${
|
|
94
|
-
${
|
|
95
|
-
${
|
|
90
|
+
${K.green}\u23FA${K.reset} ${K.bold}Create(${o})${K.reset}`);let i=[`${s.length} line${s.length!==1?"s":""}`];if(r.length>0){let f=r.filter(g=>g.severity==="error").length,p=r.filter(g=>g.severity==="warn").length,m=r.filter(g=>g.severity==="info").length,h=[];f>0&&h.push(`${K.red}${f} error${f!==1?"s":""}${K.dim}`),p>0&&h.push(`${K.yellow}${p} warning${p!==1?"s":""}${K.dim}`),m>0&&h.push(`${K.cyan}${m} info${m!==1?"s":""}${K.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${K.dim}\u23BF ${i.join(", ")}${K.reset}`);let c=" ",u=process.stdout.columns||120,d=Math.min(s.length,20);for(let f=0;f<d;f++){let p=String(f+1).padStart(4),m=f+1,h=r.filter(x=>x.line===m),g=`${c}${p} + ${s[f]}`,y=g.replace(/\x1b\[[0-9;]*m/g,""),w=g+" ".repeat(Math.max(0,u-y.length));console.log(`${tu.diff_add_bg}${K.green}${w}${K.reset}`);for(let x of h){let S=K.cyan,k="\u2139";x.severity==="error"?(S=K.red,k="\u2716"):x.severity==="warn"&&(S=K.yellow,k="\u26A0"),console.log(`${c} ${S}${k} ${x.message}${K.reset}`)}}s.length>20&&console.log(`${c}${K.dim} ...+${s.length-20} more lines${K.reset}`),console.log()}zh.exports={diffLines:Nr,showEditDiff:Rk,showWriteDiff:Ck,showNewFilePreview:Ak,confirmFileChange:Ok,showSideBySideDiff:Mk,showDiff:Nk,showNewFile:Pk}});var vs=X((MI,Jh)=>{var Xh=require("util").promisify(require("child_process").exec),Lk=require("util").promisify(require("child_process").execFile),{C:it}=He();async function nu(t){try{let{stdout:e}=await Xh(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Ta(...t){try{let{stdout:e}=await Lk("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Ik(){return await nu("git rev-parse --is-inside-work-tree")==="true"}async function jk(){return await nu("git branch --show-current")}async function su(){try{let{stdout:t}=await Xh("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
91
|
+
`).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function Ra(t=!1){return await nu(`git diff ${t?"--cached":""}`)||""}async function ou(){return(await su()).map(e=>e.file)}async function Vh(){let t=await ou();if(t.length===0)return null;let e=await Ra(),o=await Ra(!0)||e,s=0,r=0;if(o){let d=o.split(`
|
|
92
|
+
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&s++,f.startsWith("-")&&!f.startsWith("---")&&r++}else s=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":s>r*2?i="feat":r>s?i="refactor":i="fix";let 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:s,deletions:r}}}async function Dk(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Ta("checkout","-b",n)!==null?n:null}async function qk(t){return await Ta("add","-A"),await Ta("commit","-m",t)?await Ta("rev-parse","--short","HEAD"):null}async function Fk(){let t=await Vh();if(!t)return`${it.dim}No changes${it.reset}`;let e=[];e.push(`
|
|
93
|
+
${it.bold}${it.cyan}Git Diff Summary:${it.reset}`),e.push(` ${it.green}+${t.stats.additions}${it.reset} ${it.red}-${t.stats.deletions}${it.reset} in ${t.files.length} file(s)`),e.push(`
|
|
94
|
+
${it.bold}${it.cyan}Files:${it.reset}`);for(let n of t.files.slice(0,20))e.push(` ${it.dim}${n}${it.reset}`);return t.files.length>20&&e.push(` ${it.dim}...+${t.files.length-20} more${it.reset}`),e.push(`
|
|
95
|
+
${it.bold}${it.cyan}Suggested message:${it.reset}`),e.push(` ${it.cyan}${t.summary}${it.reset}
|
|
96
96
|
`),e.join(`
|
|
97
97
|
`)}async function Bk(){return(await su()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Uk(){let t=await ou();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let o of t.slice(0,10))e.push(` ${o}`);let n=await Ra();if(n){let o=n.length>5e3?n.substring(0,5e3)+`
|
|
98
98
|
...(truncated)`:n;e.push(`
|
|
99
99
|
DIFF:
|
|
100
100
|
${o}`)}return e.join(`
|
|
101
|
-
`)}
|
|
102
|
-
`).map(n=>{let o=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let s=o[2].trim();return s.startsWith(Ca)?{index:parseInt(o[1],10),label:s,shortName:s.replace(`${Ca}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function tS(t,e=process.cwd()){try{let n=
|
|
103
|
-
`)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?s.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:s,body:o}}function iu(t){try{let e=Qe.readFileSync(t,"utf-8").trim();if(!e)return null;let n=Yt.basename(t,".md"),{triggers:o,body:s}=
|
|
101
|
+
`)}Jh.exports={isGitRepo:Ik,getCurrentBranch:jk,getStatus:su,getDiff:Ra,getChangedFiles:ou,analyzeDiff:Vh,createBranch:Dk,commit:qk,formatDiffSummary:Fk,getDiffContext:Uk,getMergeConflicts:Bk}});var rs=X((PI,om)=>{var kt=require("fs").promises,NI=require("fs"),hn=require("path"),Wk=require("crypto"),{execSync:ru,execFileSync:em}=require("child_process"),Hk=100*1024,tm=50,Gt=[],Wo=[];function Gk(t,e,n,o){for(Gt.push({tool:t,filePath:e,oldContent:n,newContent:o,timestamp:Date.now()});Gt.length>tm;)Gt.shift();Wo.length=0,nm(Gt[Gt.length-1]).catch(()=>{})}async function Yk(){if(Gt.length===0)return null;let t=Gt.pop();if(t.oldContent===null)try{await kt.unlink(t.filePath)}catch{}else await kt.writeFile(t.filePath,t.oldContent,"utf-8");return Wo.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function zk(){if(Wo.length===0)return null;let t=Wo.pop();return await kt.writeFile(t.filePath,t.newContent,"utf-8"),Gt.push(t),{tool:t.tool,filePath:t.filePath}}function Kk(t=10){return Gt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Xk(){return Gt.length}function Vk(){return Wo.length}function Jk({diskToo:t=!0}={}){if(Gt.length=0,Wo.length=0,t){let e=Aa();kt.readdir(e).then(n=>{for(let o of n)o.endsWith(".json")&&kt.unlink(hn.join(e,o)).catch(()=>{})}).catch(()=>{})}}function Aa(){return hn.join(process.cwd(),".nex","history")}async function Zh(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=Hk)return{inline:!0,content:t};let n=Wk.createHash("sha256").update(t,"utf-8").digest("hex"),o=hn.join(e,"blobs");return await kt.mkdir(o,{recursive:!0}),await kt.writeFile(hn.join(o,n),t,"utf-8"),{inline:!1,hash:n}}async function nm(t){let e=Aa();await kt.mkdir(e,{recursive:!0});let n=hn.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${n}.json`,s=await Zh(t.oldContent,e),r=await Zh(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:s.inline?{inline:!0,content:s.content}:{inline:!1,hash:s.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await kt.writeFile(hn.join(e,o),JSON.stringify(i),"utf-8")}async function Qh(t,e){if(!t)return null;if(t.inline)return t.content;let n=hn.join(e,"blobs",t.hash);return kt.readFile(n,"utf-8")}async function Zk(){let t=Aa(),e;try{e=await kt.readdir(t)}catch{return 0}let n=e.filter(s=>s.endsWith(".json")).sort(),o=0;for(let s of n)try{let r=await kt.readFile(hn.join(t,s),"utf-8"),i=JSON.parse(r),a=await Qh(i.oldContent,t),c=await Qh(i.newContent,t);Gt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:c}),o++}catch{}for(;Gt.length>tm;)Gt.shift();return o}async function Qk(t=7){let e=Aa(),n;try{n=await kt.readdir(e)}catch{return 0}let o=Date.now()-t*24*60*60*1e3,s=n.filter(u=>u.endsWith(".json")),r=0,i=new Set,a=[];for(let u of s)try{let d=await kt.readFile(hn.join(e,u),"utf-8"),f=JSON.parse(d);f.timestamp<o?(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 kt.unlink(hn.join(e,u))}catch{}let c=hn.join(e,"blobs");try{let u=await kt.readdir(c);for(let d of u)if(!i.has(d))try{await kt.unlink(hn.join(c,d))}catch{}}catch{}return r}var Ca="nex-snapshot";function eS(t,e=process.cwd()){let n=t?`${Ca}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Ca}-${Date.now()}`;try{return ru("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(em("git",["stash","push","-u","-m",n],{cwd:e,timeout:15e3}),ru("git stash pop",{cwd:e,timeout:1e4}),{name:n,label:n,ok:!0}):{name:n,label:n,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(o){return{name:n,label:n,ok:!1,error:o.message}}}function sm(t=process.cwd()){try{let e=ru("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
|
|
102
|
+
`).map(n=>{let o=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let s=o[2].trim();return s.startsWith(Ca)?{index:parseInt(o[1],10),label:s,shortName:s.replace(`${Ca}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function tS(t,e=process.cwd()){try{let n=sm(e);if(n.length===0)return{ok:!1,error:"No snapshots found"};let o;return t===void 0||t==="last"?o=n[0]:typeof t=="number"?o=n.find(s=>s.index===t):o=n.find(s=>s.label===t||s.shortName===t||s.shortName.includes(String(t))),o?(em("git",["stash","apply",`stash@{${o.index}}`],{cwd:e,timeout:15e3}),{ok:!0,label:o.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(n){return{ok:!1,error:n.message}}}om.exports={recordChange:Gk,undo:Yk,redo:zk,getHistory:Kk,getUndoCount:Xk,getRedoCount:Vk,clearHistory:Jk,persistEntry:nm,loadPersistedHistory:Zk,pruneHistory:Qk,createSnapshot:eS,listSnapshots:sm,restoreSnapshot:tS}});var is=X((LI,um)=>{var Qe=require("fs"),Yt=require("path"),{atomicWrite:nS,withFileLockSync:sS}=os(),jt=[];function Pr(){return Yt.join(process.cwd(),".nex","skills")}function rm(){return Yt.join(process.cwd(),".nex","config.json")}function im(){let t=Pr();return Qe.existsSync(t)||Qe.mkdirSync(t,{recursive:!0}),t}function cu(){let t=rm();if(!Qe.existsSync(t))return[];try{let e=JSON.parse(Qe.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function am(t){let e=rm(),n=Yt.dirname(e);Qe.existsSync(n)||Qe.mkdirSync(n,{recursive:!0}),sS(e,()=>{let o={};if(Qe.existsSync(e))try{o=JSON.parse(Qe.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t,nS(e,JSON.stringify(o,null,2))})}function cm(t,e){let n=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&n.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&n.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&n.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))n.push("commands must be an array");else for(let o=0;o<t.commands.length;o++){let s=t.commands[o];(!s.cmd||typeof s.cmd!="string")&&n.push(`commands[${o}].cmd must be a non-empty string`),s.handler!==void 0&&typeof s.handler!="function"&&n.push(`commands[${o}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))n.push("tools must be an array");else for(let o=0;o<t.tools.length;o++){let s=t.tools[o];(!s.function||!s.function.name||typeof s.function.name!="string")&&n.push(`tools[${o}].function.name must be a non-empty string`),s.execute!==void 0&&typeof s.execute!="function"&&n.push(`tools[${o}].execute must be a function`)}return{valid:n.length===0,errors:n}}function lm(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let n=e[1],o=e[2].trim(),s=[],r=!1;for(let i of n.split(`
|
|
103
|
+
`)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?s.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:s,body:o}}function iu(t){try{let e=Qe.readFileSync(t,"utf-8").trim();if(!e)return null;let n=Yt.basename(t,".md"),{triggers:o,body:s}=lm(e);return{name:n,type:"prompt",filePath:t,instructions:s||e,triggers:o,commands:[],tools:[]}}catch{return null}}function au(t){try{let e=require(t),{valid:n,errors:o}=cm(e,t);return n?{name:e.name||Yt.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}
|
|
104
104
|
${o.join(`
|
|
105
105
|
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function lu(){jt=[];let t=cu(),e=Pr(),n=[];if(Qe.existsSync(e))try{n=Qe.readdirSync(e)}catch{n=[]}for(let s of n){let r=Yt.join(e,s),i;try{i=Qe.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;s.endsWith(".md")?a=iu(r):s.endsWith(".js")&&(a=au(r)),a&&(a.enabled=!t.includes(a.name),jt.push(a))}let o=Yt.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Qe.existsSync(o)){let s;try{s=Qe.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{s=[]}for(let r of s){let i=Yt.join(o,r),a=Yt.basename(r,Yt.extname(r));if(jt.some(d=>d.name===a))continue;let c;try{c=Qe.statSync(i)}catch{continue}if(!c.isFile())continue;let u=r.endsWith(".md")?iu(i):au(i);u&&(u._builtin=!0,u.enabled=!t.includes(u.name),jt.push(u))}}return jt}function oS(){let t=[];for(let e of jt)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
106
106
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
107
107
|
${t.join(`
|
|
108
108
|
|
|
109
|
-
`)}`}function rS(){let t=[];for(let e of jt)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function iS(){let t=[];for(let e of jt)if(e.enabled)for(let n of e.tools)t.push({type:"function",function:{name:`skill_${n.function.name}`,description:`[Skill:${e.name}] ${n.function.description}`,parameters:n.function.parameters}});return t}async function aS(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let o of jt)if(o.enabled){for(let s of o.tools)if(s.function.name===n&&s.execute)try{let r=await s.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${n}' failed: ${r.message}`}}return`ERROR: Skill tool '${n}' not found`}function cS(t){let[e,...n]=t.split(/\s+/),o=n.join(" ").trim();for(let s of jt)if(s.enabled){for(let r of s.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(o);if(typeof i=="string"&&i.length>0)return{handled:!0,agentPrompt:i}}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return{handled:!0}}}return!1}function lS(){return jt.map(t=>({name:t.name,type:t.type,enabled:t.enabled,description:t.description||"",commands:t.commands.length,tools:t.tools.length,filePath:t.filePath}))}function uS(t){let e=jt.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let n=cu().filter(o=>o!==t);return
|
|
109
|
+
`)}`}function rS(){let t=[];for(let e of jt)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function iS(){let t=[];for(let e of jt)if(e.enabled)for(let n of e.tools)t.push({type:"function",function:{name:`skill_${n.function.name}`,description:`[Skill:${e.name}] ${n.function.description}`,parameters:n.function.parameters}});return t}async function aS(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let o of jt)if(o.enabled){for(let s of o.tools)if(s.function.name===n&&s.execute)try{let r=await s.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${n}' failed: ${r.message}`}}return`ERROR: Skill tool '${n}' not found`}function cS(t){let[e,...n]=t.split(/\s+/),o=n.join(" ").trim();for(let s of jt)if(s.enabled){for(let r of s.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(o);if(typeof i=="string"&&i.length>0)return{handled:!0,agentPrompt:i}}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return{handled:!0}}}return!1}function lS(){return jt.map(t=>({name:t.name,type:t.type,enabled:t.enabled,description:t.description||"",commands:t.commands.length,tools:t.tools.length,filePath:t.filePath}))}function uS(t){let e=jt.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let n=cu().filter(o=>o!==t);return am(n),!0}function dS(t){let e=jt.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let n=cu();return n.includes(t)||(n.push(t),am(n)),!0}function fS(){return jt}async function pS(t,e={}){let{execFileSync:n}=require("child_process"),o=im(),s=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(s=`https://github.com/${t}.git`);let r=e.name||Yt.basename(s,".git").replace(/^nex-skill-/,""),i=Yt.join(o,r);if(Qe.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:.@]+$/.test(s))throw new Error(`Invalid git URL: ${s}`);n("git",["clone","--depth","1",s,i],{timeout:3e4,stdio:"pipe"})}catch(d){return{ok:!1,name:r,error:`Git clone failed: ${d.stderr?.toString().trim()||d.message}`}}let a=Yt.join(i,"skill.json"),c=Qe.existsSync(a),u=Qe.readdirSync(i).some(d=>(d.endsWith(".md")||d.endsWith(".js"))&&!d.startsWith("."));if(!c&&!u){try{Qe.rmSync(i,{recursive:!0,force:!0})}catch(d){console.error("skills.js line 562 failed:",d.message)}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(Qe.readFileSync(a,"utf-8"));d.name||(d.name=r)}catch{try{Qe.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return lu(),{ok:!0,name:r}}async function hS(t){let e=require("axios");try{let n=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(s=>({name:s.name.replace(/^nex-skill-/,""),description:s.description||"(no description)",url:s.clone_url,stars:s.stargazers_count,owner:s.owner.login}))}catch(n){return[{name:"error",description:`Search failed: ${n.message}`,url:"",stars:0,owner:""}]}}function mS(t){let e=Yt.join(Pr(),t);if(!Qe.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${Pr()}`};try{return Qe.rmSync(e,{recursive:!0,force:!0}),lu(),{ok:!0}}catch(n){return{ok:!1,error:n.message}}}function gS(t){if(!t)return[];let e=t.toLowerCase(),n=[];for(let o of jt){if(!o.enabled||!o.triggers||o.triggers.length===0)continue;if(o.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(o.instructions||"").split(`
|
|
110
110
|
`).slice(0,3).join(`
|
|
111
|
-
`);n.push({name:o.name,instructions:r})}}return n}
|
|
111
|
+
`);n.push({name:o.name,instructions:r})}}return n}um.exports={initSkillsDir:im,loadAllSkills:lu,getSkillInstructions:oS,getSkillCommands:rS,getSkillToolDefinitions:iS,routeSkillCall:aS,handleSkillCommand:cS,listSkills:lS,enableSkill:uS,disableSkill:dS,getLoadedSkills:fS,installSkill:pS,searchSkills:hS,removeSkill:mS,matchSkillTriggers:gS,_getSkillsDir:Pr,_validateScriptSkill:cm,_loadMarkdownSkill:iu,_loadScriptSkill:au,_parseFrontmatter:lm}});var Ma=X((II,gm)=>{var{spawn:yS}=require("child_process"),$S=require("path"),dm=require("fs"),as=new Map;function wS(){return $S.join(process.cwd(),".nex","config.json")}function uu(){let t=wS();if(!dm.existsSync(t))return{};try{return JSON.parse(dm.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Oa(t,e,n={},o=1e4){return new Promise((s,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:n})+`
|
|
112
112
|
`,c="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},o);function d(p){c+=p.toString();let m=c.split(`
|
|
113
|
-
`);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)}`)):s(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
|
|
114
|
-
`):JSON.stringify(s)}function
|
|
113
|
+
`);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)}`)):s(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 fm(t,e){if(as.has(t))return as.get(t);let n=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],o={};for(let i of n)process.env[i]&&(o[i]=process.env[i]);let s=yS(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:s,tools:[],config:e};try{await Oa(s,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await Oa(s,"tools/list",{});return r.tools=i&&i.tools||[],as.set(t,r),r}catch(i){throw s.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function pm(t){let e=as.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return as.delete(t),!0}function bS(){for(let[t]of as)pm(t)}async function hm(t,e,n={}){let o=as.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await Oa(o.proc,"tools/call",{name:e,arguments:n});return s&&Array.isArray(s.content)?s.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
114
|
+
`):JSON.stringify(s)}function mm(){let t=[];for(let[e,n]of as)for(let o of n.tools)t.push({server:e,name:o.name,description:o.description||"",inputSchema:o.inputSchema||{type:"object",properties:{}}});return t}function _S(){return mm().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function xS(t,e){if(!t.startsWith("mcp_"))return null;let n=t.substring(4).split("_");if(n.length<2)return null;let o=n[0],s=n.slice(1).join("_");return hm(o,s,e)}function vS(){let t=uu();return Object.entries(t).map(([e,n])=>{let o=as.get(e);return{name:e,command:n.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function kS(){let t=uu(),e=[];for(let[n,o]of Object.entries(t))try{let s=await fm(n,o);e.push({name:n,tools:s.tools.length})}catch(s){e.push({name:n,tools:0,error:s.message})}return e}gm.exports={loadMCPConfig:uu,sendRequest:Oa,connectServer:fm,disconnectServer:pm,disconnectAll:bS,callTool:hm,getAllTools:mm,getMCPToolDefinitions:_S,routeMCPCall:xS,listServers:vS,connectAll:kS}});var Pa=X((jI,bm)=>{var ym=require("fs"),du=require("path"),Na=[],Lr=[],Ys={},Ir=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function $m(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 Lr.some(o=>o.definition.function.name===n)?{ok:!1,error:`Tool "${n}" is already registered`}:(Lr.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function wm(t,e){return Ir.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(Ys[t]||(Ys[t]=[]),Ys[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Ir.join(", ")}`}}async function fu(t,e){let n=Ys[t]||[],o=e;for(let s of n)try{let r=await s(o);r!==void 0&&(o=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return o}function SS(){let t=du.join(process.cwd(),".nex","plugins"),e=[];if(!ym.existsSync(t))return{loaded:0,errors:[]};let n=ym.readdirSync(t).filter(s=>s.endsWith(".js")),o={registerTool:$m,registerHook:wm,EVENTS:Ir};for(let s of n){let r=du.join(t,s);try{let i=require(r);if(typeof i=="function")i(o);else if(typeof i.setup=="function")i.setup(o);else{e.push(`${s}: Plugin must export a function or { setup: function }`);continue}Na.push({name:i.name||du.basename(s,".js"),filePath:r})}catch(i){e.push(`${s}: ${i.message}`)}}return{loaded:Na.length,errors:e}}function ES(){return Lr.map(t=>t.definition)}async function TS(t,e,n={}){let o=Lr.find(a=>a.definition.function.name===t);if(!o)return null;let s=await fu("beforeToolExec",{name:t,args:e,options:n}),r=await o.handler(s.args||e,n);return(await fu("afterToolExec",{name:t,args:e,result:r})).result||r}function RS(){return[...Na]}function CS(){let t={};for(let e of Ir)t[e]=(Ys[e]||[]).length;return t}function AS(){Na.length=0,Lr.length=0;for(let t of Object.keys(Ys))delete Ys[t]}bm.exports={registerTool:$m,registerHook:wm,emit:fu,loadPlugins:SS,getPluginToolDefinitions:ES,executePluginTool:TS,getLoadedPlugins:RS,getHookCounts:CS,clearPlugins:AS,EVENTS:Ir}});var pu=X((DI,km)=>{var{getSkillToolDefinitions:OS}=is(),{getMCPToolDefinitions:MS}=Ma(),{getPluginToolDefinitions:NS}=Pa(),La=new Map;function _m(){let{TOOL_DEFINITIONS:t}=Sn();return[...t,...OS(),...MS(),...NS()]}function xm(t){if(La.has(t))return La.get(t);let n=_m().find(s=>s.function.name===t);if(!n)return null;let o=n.function.parameters;return La.set(t,o),o}function PS(){La.clear()}function Ia(t,e){if(!t||e.length===0)return null;let n=null,o=1/0;for(let s of e){let r=vm(t.toLowerCase(),s.toLowerCase());r<o&&(o=r,n=s)}return o<=Math.ceil(t.length/2)?n:null}function vm(t,e){let n=t.length,o=e.length,s=Array.from({length:n+1},()=>Array(o+1).fill(0));for(let r=0;r<=n;r++)s[r][0]=r;for(let r=0;r<=o;r++)s[0][r]=r;for(let r=1;r<=n;r++)for(let i=1;i<=o;i++)s[r][i]=t[r-1]===e[i-1]?s[r-1][i-1]:1+Math.min(s[r-1][i],s[r][i-1],s[r-1][i-1]);return s[n][o]}function LS(t,e){let n=xm(t);if(n===null){let f=_m().map(m=>m.function.name),p=Ia(t,f);return{valid:!1,error:`Unknown tool "${t}".${p?` Did you mean "${p}"?`:""}
|
|
115
115
|
Available tools: ${f.join(", ")}`}}if(!n||!n.properties)return{valid:!0};let o=n.required||[],s=Object.keys(n.properties),r=Object.keys(e),i=[],a={...e},c=!1;for(let d of o)if(!(d in e)||e[d]===void 0||e[d]===null){let f=Ia(d,r);f&&!s.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)&&!s.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(!s.includes(d)){let f=Ia(d,s);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:
|
|
116
116
|
`+i.map(d=>` - ${d}`).join(`
|
|
117
117
|
`)+`
|
|
118
118
|
|
|
119
|
-
Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:c?a:null}}function IS(t,e){let n=[],o={...t};if(!o.function&&!o.name)return n.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:o,errors:n};if(!o.function&&o.name&&(o.function={name:o.name,arguments:o.arguments||o.args||{}},delete o.name,delete o.args),o.function&&o.function.args!==void 0&&o.function.arguments===void 0&&(o.function.arguments=o.function.args,delete o.function.args),o.function&&(o.function.arguments===void 0||o.function.arguments===null)&&(o.function.arguments={}),o.function&&typeof o.function.arguments=="string"){let s=o.function.arguments;if(s.trim()==="")o.function.arguments={};else try{o.function.arguments=JSON.parse(s)}catch(r){return n.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:o,errors:n}}}return o.function&&typeof o.function.arguments!="object"?(n.push(`Arguments must be an object, got ${typeof o.function.arguments}`),{valid:!1,normalized:o,errors:n}):!o.function.name||typeof o.function.name!="string"?(n.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:o,errors:n}):{valid:n.length===0,normalized:o,errors:n}}
|
|
119
|
+
Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:c?a:null}}function IS(t,e){let n=[],o={...t};if(!o.function&&!o.name)return n.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:o,errors:n};if(!o.function&&o.name&&(o.function={name:o.name,arguments:o.arguments||o.args||{}},delete o.name,delete o.args),o.function&&o.function.args!==void 0&&o.function.arguments===void 0&&(o.function.arguments=o.function.args,delete o.function.args),o.function&&(o.function.arguments===void 0||o.function.arguments===null)&&(o.function.arguments={}),o.function&&typeof o.function.arguments=="string"){let s=o.function.arguments;if(s.trim()==="")o.function.arguments={};else try{o.function.arguments=JSON.parse(s)}catch(r){return n.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:o,errors:n}}}return o.function&&typeof o.function.arguments!="object"?(n.push(`Arguments must be an object, got ${typeof o.function.arguments}`),{valid:!1,normalized:o,errors:n}):!o.function.name||typeof o.function.name!="string"?(n.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:o,errors:n}):{valid:n.length===0,normalized:o,errors:n}}km.exports={validateToolArgs:LS,validateToolCallFormat:IS,closestMatch:Ia,levenshtein:vm,getCachedSchema:xm,clearSchemaCache:PS}});var Rm=X((qI,Tm)=>{var{levenshtein:ja}=pu(),jS=200,DS=.3,qS=2;function hu(t){return t.replace(/\r\n/g,`
|
|
120
120
|
`).replace(/\r/g,`
|
|
121
121
|
`).replace(/\t/g," ".repeat(qS)).split(`
|
|
122
122
|
`).map(e=>{let n=e.replace(/\s+$/,""),o=n.match(/^(\s*)(.*)/);if(!o)return n;let[,s,r]=o;return s+r.replace(/ {2,}/g," ")}).join(`
|
|
@@ -126,31 +126,31 @@ Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,correcte
|
|
|
126
126
|
`),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 s.slice(u,u+i.length).join(`
|
|
127
127
|
`)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(o)!==-1)return s[u]}return null}function BS(t,e){if(!t||!e)return null;let n=t.split(`
|
|
128
128
|
`),s=e.split(`
|
|
129
|
-
`).length;return n.length===0||s===0?null:s===1?US(n,e):HS(n,e,s)}function
|
|
130
|
-
`),u=ja(c,e);u<i&&(i=u,r={text:c,distance:u,line:a+1})}return r&&s>1&&(r=GS(t,e,r,s,n,o)||r,i=r.distance),
|
|
131
|
-
`),m=ja(p,e);m<u&&(u=m,d={text:p,distance:m,line:f+1})}return d}
|
|
132
|
-
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")):[]}function mu(t,e){return e.some(n=>t.includes(n))}function
|
|
133
|
-
`),n=[],o="";for(let s=0;s<e.length;s++){let r=e[s];if(r.startsWith("+++ b/")){o=r.slice(6);continue}!r.startsWith("+")||r.startsWith("+++")||n.push({filePath:o,lineNumber:s+1,text:r.slice(1),raw:r})}return n}function
|
|
129
|
+
`).length;return n.length===0||s===0?null:s===1?US(n,e):HS(n,e,s)}function Sm(t){return Math.max(1,Math.floor(t/jS))}function Em(t,e){return t<=Math.ceil(e*DS)}function US(t,e){let n=e.trim(),o=Sm(t.length),s=null,r=1/0;for(let i=0;i<t.length;i+=o){let a=t[i];if(!a.trim())continue;let c=ja(a.trim(),n);c<r&&(r=c,s={text:a,distance:c,line:i+1})}return s&&o>1&&(s=WS(t,n,s,o)||s,r=s.distance),Em(r,e.length)?s:null}function WS(t,e,n,o){let s=n.line-1,r=Math.max(0,s-o),i=Math.min(t.length-1,s+o),a=n.distance,c=null;for(let u=r;u<=i;u++){let d=t[u];if(!d.trim())continue;let f=ja(d.trim(),e);f<a&&(a=f,c={text:d,distance:f,line:u+1})}return c}function HS(t,e,n){let o=t.length-n+1;if(o<=0)return null;let s=Sm(o),r=null,i=1/0;for(let a=0;a<o;a+=s){let c=t.slice(a,a+n).join(`
|
|
130
|
+
`),u=ja(c,e);u<i&&(i=u,r={text:c,distance:u,line:a+1})}return r&&s>1&&(r=GS(t,e,r,s,n,o)||r,i=r.distance),Em(i,e.length)?r:null}function GS(t,e,n,o,s,r){let i=n.line-1,a=Math.max(0,i-o),c=Math.min(r-1,i+o),u=n.distance,d=null;for(let f=a;f<=c;f++){let p=t.slice(f,f+s).join(`
|
|
131
|
+
`),m=ja(p,e);m<u&&(u=m,d={text:p,distance:m,line:f+1})}return d}Tm.exports={normalizeWhitespace:hu,fuzzyFindText:FS,findMostSimilar:BS}});var jm=X((FI,gu)=>{var Cm=require("fs"),YS=require("path"),{execFileSync:zS}=require("child_process"),Am=["--",".",":!*.lock",":!*.min.js",":!*.min.css",":!package-lock.json",":!yarn.lock",":!dist/",":!tests/hooks-pre-push.test.js"],KS=/(^|\/)(tests\/.*\.test\.(js|ts|jsx|tsx)|__tests__\/.*\.(js|ts|jsx|tsx))$/i,Om=[{category:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{category:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{category:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{category:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{category:"GitHub Token (ghp_)",regex:/ghp_[a-zA-Z0-9]{36}/i},{category:"GitHub OAuth (gho_)",regex:/gho_[a-zA-Z0-9]{36}/i},{category:"GitHub App Token (ghs_)",regex:/ghs_[a-zA-Z0-9]{36}/i},{category:"GitHub Fine-Grained Token",regex:/github_pat_[a-zA-Z0-9_]{20,}/i},{category:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{category:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{category:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{category:"Credential URL",regex:/\b[a-z][a-z0-9+.-]*:\/\/[^/\s:@]+:[^/\s@]+@[^/\s]+/i},{category:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"][^'"]{8,}/i},{category:"SSH + IP",regex:/\bssh\s+.*@[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\b/i},{category:"SSH Config HostName",regex:/\bHostName\s+[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\b/i},{category:"Server IP Assignment",regex:/\b(host|hostname|server|server_ip|public_ip|private_ip|vps_ip|ssh_host|remote_host|db_host)\b\s*[:=]\s*['"]?[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+['"]?/i},{category:".env Secret Assignment",regex:/\b(API_KEY|SECRET_KEY|SECRET|TOKEN|PASSWORD|PRIVATE_KEY|ACCESS_KEY|AUTH_TOKEN|DB_PASSWORD|DATABASE_URL)\s*=/i}],XS=/(^|\/)\.env(?:\.[^/]+)?\.(example|sample|template)$/i,Mm=[{category:"Sensitive Env File",regex:/(^|\/)\.env(?:\.[^/]+)?$/i},{category:"Private Key File",regex:/(^|\/)(id_(rsa|dsa|ecdsa|ed25519)(\.pub)?|.*\.key)$/i},{category:"Certificate Bundle",regex:/(^|\/).*\.(p12|pfx|mobileprovision)$/i},{category:"Terraform Secrets",regex:/(^|\/).*\.(tfvars|tfstate)(\..+)?$/i},{category:"Credential File",regex:/(^|\/)(\.npmrc|\.netrc)$/i},{category:"Cloud Credentials",regex:/(^|\/)\.(aws\/credentials|kube\/config)$/i}];function Da(t,e=process.cwd()){return zS("git",t,{cwd:e,encoding:"utf8"})}function VS(t=process.cwd()){return Da(["rev-parse","--show-toplevel"],t).trim()}function JS(t){let e=YS.join(t,".nex","push-allowlist");return Cm.existsSync(e)?Cm.readFileSync(e,"utf8").split(`
|
|
132
|
+
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")):[]}function mu(t,e){return e.some(n=>t.includes(n))}function Nm(t){return XS.test(t)}function Pm(t,e){let n=[];for(let o of t)if(!Nm(o))for(let s of Mm)s.regex.test(o)&&(mu(o,e)||n.push({category:s.category,location:o,preview:o}));return n}function ZS(t){let e=t.split(`
|
|
133
|
+
`),n=[],o="";for(let s=0;s<e.length;s++){let r=e[s];if(r.startsWith("+++ b/")){o=r.slice(6);continue}!r.startsWith("+")||r.startsWith("+++")||n.push({filePath:o,lineNumber:s+1,text:r.slice(1),raw:r})}return n}function Lm(t,e){let n=[];for(let o of ZS(t))if(!KS.test(o.filePath||""))for(let s of Om)s.regex.test(o.text)&&(mu(o.raw,e)||mu(o.text,e)||n.push({category:s.category,location:`${o.lineNumber}:${o.raw}`,preview:o.raw}));return n}function QS(t){return Da(["diff","--cached","--name-only","--diff-filter=ACMR","-z"],t).split("\0").filter(Boolean)}function eE(t,e){return Da(["diff",e,...Am],t)}function tE(t){return Da(["diff","--cached",...Am],t)}function Im({repoRoot:t,mode:e,range:n}){let o=JS(t),s=e==="staged"?QS(t):[],r=Pm(s,o),i=e==="range"?eE(t,n):tE(t),a=Lm(i,o);return[...r,...a]}function nE(t){return t.map(e=>` [${e.category}]
|
|
134
134
|
${e.location}`).join(`
|
|
135
|
-
`)}function sE(t){let e={mode:"staged",range:""};for(let n=0;n<t.length;n++)t[n]==="--staged"&&(e.mode="staged"),t[n]==="--range"&&(e.mode="range",e.range=t[n+1]||"",n++);return e}function oE(){let t=sE(process.argv.slice(2)),e=VS(),n=
|
|
136
|
-
`),o=[],s=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],a=r+1;for(let c of rE)c.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${c.category}`,severity:"error"});for(let c of iE)c.ext&&!c.ext.includes(s)||c.regex.test(i)&&o.push({line:a,message:c.message||`Found ${c.name}`,severity:c.severity||"warn"})}return n.length>500&&o.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),o}function cE(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}
|
|
137
|
-
`).filter(Boolean),$u=Date.now(),qa=!1;return}catch{}let e=[],n=async(o,s)=>{let r;try{r=await zs.readdir(o,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=s?`${s}/${i.name}`:i.name;i.isDirectory()?await n(zt.join(o,i.name),a):e.push(a)}};await n(t,""),ks=e,$u=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{qa=!1}}}function jr(){return ks}function dE(){return wu}function fE(t){return ks.filter(e=>zt.basename(e)===t)}function pE(t){let e=t.toLowerCase();return ks.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}function
|
|
138
|
-
`);for(let s=0;s<o.length;s++){let r=o[s],i=s+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let 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 Ba(t){t=t||process.cwd();let e=zt.join(t,".nex","index","content-index.json"),n={};if(yu&&
|
|
139
|
-
`);for(let y=0;y<g.length;y++){let w=g[y],x=y+1;if(!u.test(w)||o&&p===o&&s===x||wE(w,t))continue;let S=(p===o?0:4)+(c.test(w)?3:1);d.push({file:p,line:x,context:w.trim(),score:S})}}catch{}}return d.sort((f,p)=>p.score!==f.score?p.score-f.score:f.file.localeCompare(p.file)||f.line-p.line),d.slice(0,r)}
|
|
135
|
+
`)}function sE(t){let e={mode:"staged",range:""};for(let n=0;n<t.length;n++)t[n]==="--staged"&&(e.mode="staged"),t[n]==="--range"&&(e.mode="range",e.range=t[n+1]||"",n++);return e}function oE(){let t=sE(process.argv.slice(2)),e=VS(),n=Im({repoRoot:e,mode:t.mode,range:t.range});if(n.length===0)return;let o=t.mode==="range"?"pushed commits":"staged changes";console.log(""),console.log("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),console.log("\u2551 SECRET DETECTED \u2014 operation blocked \u2551"),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log(`\u2551 Found ${n.length} potential secret(s) in ${o}:`),console.log(nE(n)),console.log("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"),console.log("\u2551 Remove secrets or move them to local-only config. \u2551"),console.log("\u2551 To allowlist: add a specific pattern to .nex/push-allowlist"),console.log("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),console.log(""),process.exit(1)}require.main===gu&&oE();gu.exports={SECRET_PATTERNS:Om,SENSITIVE_FILE_RULES:Mm,scanDiffText:Lm,scanFileNames:Pm,scanRepo:Im,isSafeExampleFile:Nm}});var qm=X((UI,Dm)=>{var{C:BI}=He(),{SECRET_PATTERNS:rE}=jm(),iE=[{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 aE(t,e){let n=e.split(`
|
|
136
|
+
`),o=[],s=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],a=r+1;for(let c of rE)c.regex.test(i)&&o.push({line:a,message:`Potential secret detected: ${c.category}`,severity:"error"});for(let c of iE)c.ext&&!c.ext.includes(s)||c.regex.test(i)&&o.push({line:a,message:c.message||`Found ${c.name}`,severity:c.severity||"warn"})}return n.length>500&&o.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),o}function cE(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Dm.exports={runDiagnostics:aE,getMemoryUsage:cE}});var Hn=X((WI,Jm)=>{var zs=require("fs").promises,zt=require("path"),{exec:lE}=require("util").promisify(require("child_process").exec),ks=[],wu=null,qa=!1,$u=0,uE=6e4;function bu(t){return!(ks.length===0||wu!==t||Date.now()-$u>uE)}async function Hm(t){if(!qa&&!bu(t)){qa=!0,wu=t;try{try{let{stdout:o}=await lE("rg --files",{cwd:t,timeout:5e3});ks=o.split(`
|
|
137
|
+
`).filter(Boolean),$u=Date.now(),qa=!1;return}catch{}let e=[],n=async(o,s)=>{let r;try{r=await zs.readdir(o,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=s?`${s}/${i.name}`:i.name;i.isDirectory()?await n(zt.join(o,i.name),a):e.push(a)}};await n(t,""),ks=e,$u=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{qa=!1}}}function jr(){return ks}function dE(){return wu}function fE(t){return ks.filter(e=>zt.basename(e)===t)}function pE(t){let e=t.toLowerCase();return ks.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}function Gm(t,e){let n=t.length,o=e.length;if(n===0)return o;if(o===0)return n;let s=Array.from({length:o+1},(r,i)=>i);for(let r=1;r<=n;r++){let i=r-1;s[0]=r;for(let a=1;a<=o;a++){let c=t[r-1]===e[a-1]?i:1+Math.min(s[a],s[a-1],i);i=s[a],s[a]=c}}return s[o]}function Ym(t,e){let n=t.toLowerCase(),o=e.toLowerCase();if(n===o)return 1e3;let s=n.split("/").filter(Boolean),r=o.split("/").filter(Boolean),i=0;for(let d=1;d<=Math.min(s.length,r.length)&&s[s.length-d]===r[r.length-d];d++)i=d;if(i>0&&i===r.length)return 500+i*100;let a=zt.basename(t).toLowerCase(),c=zt.basename(e).toLowerCase(),u=0;if(a===c)u+=80;else{let d=Math.max(a.length,c.length);if(d>0&&d<100){let p=1-Gm(a,c)/d;p>=.6&&(u+=Math.round(p*50))}}if((n.includes(o)||o.includes(n))&&(u+=20),r.length>1){let d=new Set(s),f=0;for(let p of r)d.has(p)&&f++;u+=f*10}return i>0&&(u+=i*30),u}function hE(t,{limit:e=10,minScore:n=15}={}){if(!t||ks.length===0)return[];let o=[];for(let s of ks){let r=Ym(s,t);r>=n&&o.push({file:s,score:r})}return o.sort((s,r)=>r.score-s.score),o.slice(0,e)}var yu=null,Fm=0,Bm=null,zm=12e4,Fa=null,Um=0,Wm=null,Km=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Xm(t,e){let n=[],o=t.split(`
|
|
138
|
+
`);for(let s=0;s<o.length;s++){let r=o[s],i=s+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&n.push({type:"function",name:a[1],line:i});let 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 Ba(t){t=t||process.cwd();let e=zt.join(t,".nex","index","content-index.json"),n={};if(yu&&Bm===t&&Date.now()-Fm<zm)return yu;try{let i=await zs.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}let o=jr();(!bu(t)||o.length===0)&&(await Hm(t),o=jr());let s={files:{}},r=!1;for(let i of jr()){let a=zt.extname(i);if(!Km.has(a))continue;let c=zt.join(t,i);try{let d=(await zs.stat(c)).mtimeMs;if(n.files[i]&&n.files[i].mtime===d){s.files[i]=n.files[i];continue}let f=await zs.readFile(c,"utf-8"),p=Xm(f,a);s.files[i]={defs:p,mtime:d},r=!0}catch{}}if(r){let i=zt.join(t,".nex","index");await zs.mkdir(i,{recursive:!0}),await zs.writeFile(e,JSON.stringify(s),"utf-8")}return yu=s,Fm=Date.now(),Bm=t,s}async function mE(t,e,n){let o=await Ba(n),s=[],r=t.toLowerCase();for(let[i,a]of Object.entries(o.files))for(let c of a.defs)e&&c.type!==e||c.name.toLowerCase().includes(r)&&s.push({file:i,type:c.type,name:c.name,line:c.line});return s.sort((i,a)=>{let c=i.name.toLowerCase()===r?0:1,u=a.name.toLowerCase()===r?0:1;if(c!==u)return c-u;let d=i.name.toLowerCase().startsWith(r)?0:1,f=a.name.toLowerCase().startsWith(r)?0:1;return d-f}),s.slice(0,50)}function gE(t,e,n){if(!e||!e.startsWith("."))return null;let o=zt.posix.dirname(t.replace(/\\/g,"/")),s=zt.posix.normalize(zt.posix.join(o==="."?"":o,e)),r=[];if(zt.posix.extname(s))r.push(s);else for(let a of Km)r.push(`${s}${a}`),r.push(zt.posix.join(s,`index${a}`));for(let a of r)if(n.has(a))return a;return null}async function _u(t){if(t=t||process.cwd(),Fa&&Wm===t&&Date.now()-Um<zm)return Fa;let e=await Ba(t),n=jr(),o=new Set(n.map(i=>i.replace(/\\/g,"/"))),s={},r={};for(let i of Object.keys(e.files||{})){let a=i.replace(/\\/g,"/"),c=Array.isArray(e.files[i]?.defs)?e.files[i].defs:[],u=[],d=new Set;for(let f of c){if(f.type!=="import")continue;let p=gE(a,f.name,o);!p||p===a||d.has(p)||(d.add(p),u.push(p),r[p]||(r[p]=[]),r[p].push(a))}s[a]=u}for(let[i,a]of Object.entries(r))r[i]=[...new Set(a)].sort();return Fa={importsByFile:s,importedByFile:r},Um=Date.now(),Wm=t,Fa}async function yE(t,e,n=6){if(!t)return[];let o=await _u(e),s=String(t).replace(/\\/g,"/"),r=[...o.importsByFile[s]||[],...o.importedByFile[s]||[]];return[...new Set(r)].filter(i=>i!==s).slice(0,n)}async function $E(t,e=4){let n=await _u(t),o=new Map;for(let[s,r]of Object.entries(n.importsByFile||{}))o.set(s,(o.get(s)||0)+r.length);for(let[s,r]of Object.entries(n.importedByFile||{}))o.set(s,(o.get(s)||0)+r.length);return[...o.entries()].filter(([,s])=>s>0).sort((s,r)=>r[1]-s[1]||s[0].localeCompare(r[0])).slice(0,e).map(([s,r])=>`${s} (${r} links)`)}function Vm(t){return String(t).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wE(t,e){let n=Vm(e);return[new RegExp(`\\bfunction\\s+${n}\\b`),new RegExp(`\\bclass\\s+${n}\\b`),new RegExp(`\\b(?:const|let|var)\\s+${n}\\b\\s*=`),new RegExp(`\\bdef\\s+${n}\\b`),new RegExp(`\\btype\\s+${n}\\b\\s+struct\\b`),new RegExp(`\\bmodule\\.exports\\b[^\\n]*\\b${n}\\b`),new RegExp(`\\bexport\\b[^\\n]*\\b${n}\\b`)].some(s=>s.test(t))}async function bE(t,e,n={}){e=e||process.cwd();let{excludeFile:o=null,excludeLine:s=null,limit:r=6}=n;if(!t||typeof t!="string")return[];let i=await Ba(e),a=Vm(t),c=new RegExp(`\\b${a}\\s*\\(`),u=new RegExp(`\\b${a}\\b`),d=[];for(let f of Object.keys(i.files||{})){let p=f.replace(/\\/g,"/");try{let m=zt.join(e,p),g=(await zs.readFile(m,"utf-8")).split(`
|
|
139
|
+
`);for(let y=0;y<g.length;y++){let w=g[y],x=y+1;if(!u.test(w)||o&&p===o&&s===x||wE(w,t))continue;let S=(p===o?0:4)+(c.test(w)?3:1);d.push({file:p,line:x,context:w.trim(),score:S})}}catch{}}return d.sort((f,p)=>p.score!==f.score?p.score-f.score:f.file.localeCompare(p.file)||f.line-p.line),d.slice(0,r)}Jm.exports={refreshIndex:Hm,getFileIndex:jr,getIndexedCwd:dE,findFileInIndex:fE,searchIndex:pE,isIndexValid:bu,buildContentIndex:Ba,searchContentIndex:mE,extractDefinitions:Xm,buildImportGraph:_u,getRelatedFiles:yE,summarizeModuleHubs:$E,findSymbolReferences:bE,smartSearch:hE,scorePathMatch:Ym,pathLevenshtein:Gm}});var cs=X((HI,sg)=>{var Ua=require("fs"),Ya=require("path"),za=require("os"),{execFile:_E}=require("child_process"),{promisify:xE}=require("util"),xu=xE(_E),vE=Ya.join(za.homedir(),".nex","servers.json"),Wa=Ya.join(za.tmpdir(),"nex-ssh-sockets");function kE(){return Ya.join(process.cwd(),".nex","servers.json")}function Zm(){let t=o=>{if(!Ua.existsSync(o))return{};try{return JSON.parse(Ua.readFileSync(o,"utf-8"))}catch{return{}}},e=t(vE),n=t(kE());return{...e,...n}}function SE(t){let e=Zm();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[s,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:s}}let n=Object.keys(e),o=n.length?`Available profiles: ${n.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${o}`)}function EE(){Ua.existsSync(Wa)||Ua.mkdirSync(Wa,{recursive:!0})}function Qm(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,za.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),EE();let n=t.user?`${t.user}@${t.host}`:t.host,o=Ya.join(Wa,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function eg(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=yes","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,za.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Ha(t,e,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=Qm(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await xu("ssh",[...s,r],{timeout:n,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,c=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:c,exitCode:a,error:Ka(c,t)}}}async function TE(t,e,n,{timeout:o=12e4}={}){let s=eg(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(e,`${r}:${n}`);try{let{stdout:i,stderr:a}=await xu("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(Ka(a,t)||a)}}async function RE(t,e,n,{timeout:o=12e4}={}){let s=eg(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(`${r}:${e}`,n);try{let{stdout:i,stderr:a}=await xu("scp",s,{timeout:o,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${n}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(Ka(a,t)||a)}}function Ka(t,e){if(!t)return"";if(/connection refused/i.test(t)){let n=e.port||22;return`${t}
|
|
140
140
|
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}
|
|
141
141
|
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}
|
|
142
142
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
143
143
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
144
144
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
145
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function CE(t,e){let n=e.user?`${e.user}@${e.host}`:e.host,o=e.port&&Number(e.port)!==22?`:${e.port}`:"",s=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${n}${o}${s}${r}${i}`}var Ga=new Map,AE=12e4;async function
|
|
146
|
-
`).filter(Boolean).map(f=>f.startsWith(u)?f.slice(u.length):f);return Ga.set(s,{files:d,time:Date.now()}),d}async function
|
|
145
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function CE(t,e){let n=e.user?`${e.user}@${e.host}`:e.host,o=e.port&&Number(e.port)!==22?`:${e.port}`:"",s=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${n}${o}${s}${r}${i}`}var Ga=new Map,AE=12e4;async function tg(t,e,{force:n=!1}={}){let s=`${t.user?`${t.user}@${t.host}`:t.host}:${e}`,r=Ga.get(s);if(!n&&r&&Date.now()-r.time<AE)return r.files;let i=`find ${e} -maxdepth 6 -type f -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/venv/*' -not -path '*/__pycache__/*' -not -path '*/dist/*' -not -name '*.pyc' 2>/dev/null | head -5000`,{stdout:a,exitCode:c}=await Ha(t,i,{timeout:15e3});if(c!==0||!a.trim())return[];let u=e.endsWith("/")?e:e+"/",d=a.split(`
|
|
146
|
+
`).filter(Boolean).map(f=>f.startsWith(u)?f.slice(u.length):f);return Ga.set(s,{files:d,time:Date.now()}),d}async function ng(t,e,n,{limit:o=5,minScore:s=15}={}){let r=await tg(t,e);if(r.length===0)return[];let{scorePathMatch:i}=Hn(),a=[];for(let c of r){let u=i(c,n);u>=s&&a.push({file:c,score:u})}return a.sort((c,u)=>u.score-c.score),a.slice(0,o)}async function OE(t,e,n){if(!n)return{fixedPath:null,message:""};let o=n.replace(/\/+/g,"/");if(o.startsWith("~/")){let{stdout:r}=await Ha(t,"echo $HOME",{timeout:5e3}),i=r.trim();i&&(o=o.replace("~/",i+"/"))}if(o.startsWith("/")){let{exitCode:r}=await Ha(t,`test -f ${JSON.stringify(o)}`,{timeout:5e3});if(r===0)return{fixedPath:o,message:"(auto-fixed: normalized path)"}}let s=await ng(t,e,n,{limit:5,minScore:15});if(s.length>0){let i=(e.endsWith("/")?e:e+"/")+s[0].file;if(s[0].score>=200||s.length===1&&s[0].score>=50)return{fixedPath:i,message:`(auto-fixed: remote smart match \u2192 ${s[0].file})`};if(s.length>=2&&s[0].score>=80&&s[0].score>=s[1].score*1.5)return{fixedPath:i,message:`(auto-fixed: remote best match \u2192 ${s[0].file})`};if(s.length<=5)return{fixedPath:null,message:`File not found on remote. Did you mean:
|
|
147
147
|
${s.map(a=>` - ${a.file}`).join(`
|
|
148
|
-
`)}`}}return{fixedPath:null,message:""}}function ME(t){t?Ga.delete(t):Ga.clear()}
|
|
149
|
-
`,"utf-8")}
|
|
148
|
+
`)}`}}return{fixedPath:null,message:""}}function ME(t){t?Ga.delete(t):Ga.clear()}sg.exports={loadServerProfiles:Zm,resolveProfile:SE,buildSSHArgs:Qm,sshExec:Ha,scpUpload:TE,scpDownload:RE,enrichSSHError:Ka,formatProfile:CE,SSH_SOCKET_DIR:Wa,getRemoteIndex:tg,remoteSmartSearch:ng,remoteAutoFixPath:OE,clearRemoteIndex:ME}});var Su=X((GI,rg)=>{var Dr=require("fs"),vu=require("path"),NE=vu.join(".nex","deploy.json");function ku(){return vu.join(process.cwd(),NE)}function og(){let t=ku();if(!Dr.existsSync(t))return{};try{return JSON.parse(Dr.readFileSync(t,"utf-8"))}catch{return{}}}function PE(t){let e=og();if(e[t])return{...e[t],_name:t};let n=Object.keys(e),o=n.length?`Available: ${n.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${o}`)}function LE(t){let e=vu.join(process.cwd(),".nex");Dr.existsSync(e)||Dr.mkdirSync(e,{recursive:!0}),Dr.writeFileSync(ku(),JSON.stringify(t,null,2)+`
|
|
149
|
+
`,"utf-8")}rg.exports={loadDeployConfigs:og,resolveDeployConfig:PE,saveDeployConfigs:LE,getDeployConfigPath:ku}});var Ur=X((YI,cg)=>{var{getActiveModel:IE,getActiveProviderName:jE}=Xe(),qr={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},Fr={"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"},Br={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Gn={};function ag(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(Gn=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{Gn={}}}ag();function Eu(){let e=IE()?.id,n=jE();return e&&Gn[e]?Gn[e]:n&&Gn[`${n}:*`]?Gn[`${n}:*`]:e&&Fr[e]?Fr[e]:n&&Br[n]?Br[n]:"full"}var DE=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"]),ig={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function qE(t,e){return t&&(DE.has(t)||t.startsWith("claude-"))?"strict":e&&ig[e]?ig[e]:"fuzzy"}function FE(t,e){return t&&Gn[t]?Gn[t]:e&&Gn[`${e}:*`]?Gn[`${e}:*`]:t&&Fr[t]?Fr[t]:e&&Br[e]?Br[e]:"full"}function BE(t,e){let n=e||Eu();if(n==="full"||!qr[n])return t;let o=new Set(qr[n]);return t.filter(s=>o.has(s.function.name))}function UE(){let t=Eu(),e=qr[t]?qr[t].length:"all";return{tier:t,toolCount:e}}cg.exports={filterToolsForModel:BE,getActiveTier:Eu,getModelTier:FE,getEditMode:qE,getTierInfo:UE,TIERS:qr,MODEL_TIERS:Fr,PROVIDER_DEFAULT_TIER:Br,loadConfigOverrides:ag}});var us=X((zI,dg)=>{var Tu=null,ls=null,Wr=null,lg=`Playwright is not installed. Install with:
|
|
150
150
|
npm install playwright && npx playwright install chromium
|
|
151
|
-
Then restart nex-code.`;function
|
|
152
|
-
...(truncated)`:""),links:a.slice(0,20)}}finally{await s.close()}}async function GE(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await Xa()).newPage();try{await i.setViewportSize({width:e,height:n}),await i.goto(t,{waitUntil:"networkidle",timeout:s});let a=await i.screenshot({type:"png",fullPage:o}),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 YE(t,{selector:e,text:n,timeout:o=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await Xa()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:o}),n?await r.getByText(n,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function zE(t,{selector:e,value:n,submit:o=!1,timeout:s=3e4}={}){if(!e||n===void 0)throw new Error("selector and value are required");let i=await(await Xa()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:s}),await i.fill(e,String(n)),o&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${o?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}ug.exports={isPlaywrightAvailable:lg,browserNavigate:HE,browserScreenshot:GE,browserClick:YE,browserFill:zE,closeBrowser:WE,INSTALL_MSG:cg}});var Ru=X((zI,fg)=>{"use strict";var KE=require("util"),dg=require("stream"),En=fg.exports=function(){dg.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};KE.inherits(En,dg);En.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))};En.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};En.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()))};En.prototype.destroySoon=En.prototype.end;En.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};En.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};En.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))};En.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,o=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],r=Math.min(s.length,t.length-e);s.copy(o,e,0,r),e+=r,r!==s.length&&(this._buffers[--n]=s.slice(r))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,o)};En.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 Au=X(Cu=>{"use strict";var Ss=[{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]}];Cu.getImagePasses=function(t,e){let n=[],o=t%8,s=e%8,r=(t-o)/8,i=(e-s)/8;for(let a=0;a<Ss.length;a++){let c=Ss[a],u=r*c.x.length,d=i*c.y.length;for(let f=0;f<c.x.length&&c.x[f]<o;f++)u++;for(let f=0;f<c.y.length&&c.y[f]<s;f++)d++;u>0&&d>0&&n.push({width:u,height:d,index:a})}return n};Cu.getInterlaceIterator=function(t){return function(e,n,o){let s=e%Ss[o].x.length,r=(e-s)/Ss[o].x.length*8+Ss[o].x[s],i=n%Ss[o].y.length,a=(n-i)/Ss[o].y.length*8+Ss[o].y[i];return r*4+a*t*4}}});var Ou=X((XI,pg)=>{"use strict";pg.exports=function(e,n,o){let s=e+n-o,r=Math.abs(s-e),i=Math.abs(s-n),a=Math.abs(s-o);return r<=i&&r<=a?e:i<=a?n:o}});var Mu=X((VI,mg)=>{"use strict";var XE=Au(),VE=Ou();function hg(t,e,n){let o=t*e;return n!==8&&(o=Math.ceil(o/(8/n))),o}var Ho=mg.exports=function(t,e){let n=t.width,o=t.height,s=t.interlace,r=t.bpp,i=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=XE.getImagePasses(n,o);for(let c=0;c<a.length;c++)this._images.push({byteWidth:hg(a[c].width,r,i),height:a[c].height,lineIndex:0})}else this._images.push({byteWidth:hg(n,r,i),height:o,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Ho.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Ho.prototype._unFilterType1=function(t,e,n){let o=this._xComparison,s=o-1;for(let r=0;r<n;r++){let i=t[1+r],a=r>s?e[r-o]:0;e[r]=i+a}};Ho.prototype._unFilterType2=function(t,e,n){let o=this._lastLine;for(let s=0;s<n;s++){let r=t[1+s],i=o?o[s]:0;e[s]=r+i}};Ho.prototype._unFilterType3=function(t,e,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],c=r?r[i]:0,u=i>s?e[i-o]:0,d=Math.floor((u+c)/2);e[i]=a+d}};Ho.prototype._unFilterType4=function(t,e,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],c=r?r[i]:0,u=i>s?e[i-o]:0,d=i>s&&r?r[i-o]:0,f=VE(u,c,d);e[i]=a+f}};Ho.prototype._reverseFilterLine=function(t){let e=t[0],n,o=this._images[this._imageIndex],s=o.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),o.lineIndex++,o.lineIndex>=o.height?(this._lastLine=null,this._imageIndex++,o=this._images[this._imageIndex]):this._lastLine=n,o?this.read(o.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var $g=X((JI,yg)=>{"use strict";var JE=require("util"),gg=Ru(),ZE=Mu(),QE=yg.exports=function(t){gg.call(this);let e=[],n=this;this._filter=new ZE(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};JE.inherits(QE,gg)});var Go=X((ZI,wg)=>{"use strict";wg.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 Lu=X((QI,bg)=>{"use strict";var Nu=[];(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;Nu[t]=e}})();var Pu=bg.exports=function(){this._crc=-1};Pu.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Nu[(this._crc^t[e])&255]^this._crc>>>8;return!0};Pu.prototype.crc32=function(){return this._crc^-1};Pu.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Nu[(e^t[n])&255]^e>>>8;return e^-1}});var Iu=X((e2,_g)=>{"use strict";var wt=Go(),eT=Lu(),_t=_g.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[wt.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[wt.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[wt.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[wt.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[wt.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[wt.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(){}};_t.prototype.start=function(){this.read(wt.PNG_SIGNATURE.length,this._parseSignature.bind(this))};_t.prototype._parseSignature=function(t){let e=wt.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))};_t.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),o="";for(let r=4;r<8;r++)o+=String.fromCharCode(t[r]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==wt.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new eT,this._crc.write(Buffer.from(o)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+o));return}this.read(e+4,this._skipChunk.bind(this))};_t.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};_t.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};_t.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))};_t.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};_t.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),o=t[8],s=t[9],r=t[10],i=t[11],a=t[12];if(o!==8&&o!==4&&o!==2&&o!==1&&o!==16){this.error(new Error("Unsupported bit depth "+o));return}if(!(s in wt.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(r!==0){this.error(new Error("Unsupported compression method"));return}if(i!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let c=wt.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:o,interlace:!!a,palette:!!(s&wt.COLORTYPE_PALETTE),color:!!(s&wt.COLORTYPE_COLOR),alpha:!!(s&wt.COLORTYPE_ALPHA),bpp:c,colorType:s}),this._handleChunkEnd()};_t.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};_t.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()};_t.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};_t.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===wt.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===wt.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===wt.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};_t.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};_t.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/wt.GAMMA_DIVISION),this._handleChunkEnd()};_t.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};_t.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===wt.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()};_t.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};_t.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var ju=X(vg=>{"use strict";var xg=Au(),tT=[function(){},function(t,e,n,o){if(o===e.length)throw new Error("Ran out of data");let s=e[o];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,o){if(o+1>=e.length)throw new Error("Ran out of data");let s=e[o];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[o+1]},function(t,e,n,o){if(o+2>=e.length)throw new Error("Ran out of data");t[n]=e[o],t[n+1]=e[o+1],t[n+2]=e[o+2],t[n+3]=255},function(t,e,n,o){if(o+3>=e.length)throw new Error("Ran out of data");t[n]=e[o],t[n+1]=e[o+1],t[n+2]=e[o+2],t[n+3]=e[o+3]}],nT=[function(){},function(t,e,n,o){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=o},function(t,e,n){let o=e[0];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=e[1]},function(t,e,n,o){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=o},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function sT(t,e){let n=[],o=0;function s(){if(o===t.length)throw new Error("Ran out of data");let r=t[o];o++;let i,a,c,u,d,f,p,m;switch(e){default:throw new Error("unrecognised depth");case 16:p=t[o],o++,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;)s();let i=n.slice(0,r);return n=n.slice(r),i},resetAfterLine:function(){n.length=0},end:function(){if(o!==t.length)throw new Error("extra data found")}}}function oT(t,e,n,o,s,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);tT[o](e,s,f,r),r+=o}return r}function rT(t,e,n,o,s,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=s.get(o),p=n(d,u,c);nT[o](e,f,p,r)}s.resetAfterLine()}}vg.dataToBitMap=function(t,e){let n=e.width,o=e.height,s=e.depth,r=e.bpp,i=e.interlace,a;s!==8&&(a=sT(t,s));let c;s<=8?c=Buffer.alloc(n*o*4):c=new Uint16Array(n*o*4);let u=Math.pow(2,s)-1,d=0,f,p;if(i)f=xg.getImagePasses(n,o),p=xg.getInterlaceIterator(n,o);else{let m=0;p=function(){let h=m;return m+=4,h},f=[{width:n,height:o}]}for(let m=0;m<f.length;m++)s===8?d=oT(f[m],c,p,r,t,d):rT(f[m],c,p,r,a,u);if(s===8){if(d!==t.length)throw new Error("extra data found")}else a.end();return c}});var Du=X((n2,kg)=>{"use strict";function iT(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let c=s[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 aT(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let c=!1;if(s.length===1?s[0]===t[r]&&(c=!0):s[0]===t[r]&&s[1]===t[r+1]&&s[2]===t[r+2]&&(c=!0),c)for(let u=0;u<4;u++)e[r+u]=0;r+=4}}function cT(t,e,n,o,s){let r=255,i=Math.pow(2,s)-1,a=0;for(let c=0;c<o;c++)for(let u=0;u<n;u++){for(let d=0;d<4;d++)e[a+d]=Math.floor(t[a+d]*r/i+.5);a+=4}}kg.exports=function(t,e,n=!1){let o=e.depth,s=e.width,r=e.height,i=e.colorType,a=e.transColor,c=e.palette,u=t;return i===3?iT(t,u,s,r,c):(a&&aT(t,u,s,r,a),o!==8&&!n&&(o===16&&(u=Buffer.alloc(s*r*4)),cT(t,u,s,r,o))),u}});var Tg=X((s2,Eg)=>{"use strict";var lT=require("util"),qu=require("zlib"),Sg=Ru(),uT=$g(),dT=Iu(),fT=ju(),pT=Du(),Yn=Eg.exports=function(t){Sg.call(this),this._parser=new dT(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()};lT.inherits(Yn,Sg);Yn.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};Yn.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=qu.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,o=Math.max(n,qu.Z_MIN_CHUNK);this._inflate=qu.createInflate({chunkSize:o});let s=n,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};Yn.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new uT(this._bitmapInfo)};Yn.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};Yn.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};Yn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Yn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Yn.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};Yn.prototype._complete=function(t){if(this.errord)return;let e;try{let n=fT.dataToBitMap(t,this._bitmapInfo);e=pT(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Cg=X((o2,Rg)=>{"use strict";var mn=Go();Rg.exports=function(t,e,n,o){let s=[mn.COLORTYPE_COLOR_ALPHA,mn.COLORTYPE_ALPHA].indexOf(o.colorType)!==-1;if(o.colorType===o.inputColorType){let h=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(o.bitDepth===8||o.bitDepth===16&&h)return t}let r=o.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=mn.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let c=mn.COLORTYPE_TO_BPP_MAP[o.colorType];o.bitDepth===16&&(i=65535,c*=2);let u=Buffer.alloc(e*n*c),d=0,f=0,p=o.bgColor||{};p.red===void 0&&(p.red=i),p.green===void 0&&(p.green=i),p.blue===void 0&&(p.blue=i);function m(){let h,g,y,w=i;switch(o.inputColorType){case mn.COLORTYPE_COLOR_ALPHA:w=r[d+3],h=r[d],g=r[d+1],y=r[d+2];break;case mn.COLORTYPE_COLOR:h=r[d],g=r[d+1],y=r[d+2];break;case mn.COLORTYPE_ALPHA:w=r[d+1],h=r[d],g=h,y=h;break;case mn.COLORTYPE_GRAYSCALE:h=r[d],g=h,y=h;break;default:throw new Error("input color type:"+o.inputColorType+" is not supported at present")}return o.inputHasAlpha&&(s||(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),y=Math.min(Math.max(Math.round((1-w)*p.blue+w*y),0),i))),{red:h,green:g,blue:y,alpha:w}}for(let h=0;h<n;h++)for(let g=0;g<e;g++){let y=m(r,d);switch(o.colorType){case mn.COLORTYPE_COLOR_ALPHA:case mn.COLORTYPE_COLOR:o.bitDepth===8?(u[f]=y.red,u[f+1]=y.green,u[f+2]=y.blue,s&&(u[f+3]=y.alpha)):(u.writeUInt16BE(y.red,f),u.writeUInt16BE(y.green,f+2),u.writeUInt16BE(y.blue,f+4),s&&u.writeUInt16BE(y.alpha,f+6));break;case mn.COLORTYPE_ALPHA:case mn.COLORTYPE_GRAYSCALE:{let w=(y.red+y.green+y.blue)/3;o.bitDepth===8?(u[f]=w,s&&(u[f+1]=y.alpha)):(u.writeUInt16BE(w,f),s&&u.writeUInt16BE(y.alpha,f+2));break}default:throw new Error("unrecognised color Type "+o.colorType)}d+=a,f+=c}return u}});var Mg=X((r2,Og)=>{"use strict";var Ag=Ou();function hT(t,e,n,o,s){for(let r=0;r<n;r++)o[s+r]=t[e+r]}function mT(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++)o+=Math.abs(t[r]);return o}function gT(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,c=t[e+i]-a;o[s+i]=c}}function yT(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=t[e+r]-i;s+=Math.abs(a)}return s}function $T(t,e,n,o,s){for(let r=0;r<n;r++){let i=e>0?t[e+r-n]:0,a=t[e+r]-i;o[s+r]=a}}function wT(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++){let i=e>0?t[r-n]:0,a=t[r]-i;o+=Math.abs(a)}return o}function bT(t,e,n,o,s,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);o[s+i]=u}}function _T(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-n]:0,c=t[e+r]-(i+a>>1);s+=Math.abs(c)}return s}function xT(t,e,n,o,s,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]-Ag(a,c,u);o[s+i]=d}}function vT(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-n]:0,c=e>0&&r>=o?t[e+r-(n+o)]:0,u=t[e+r]-Ag(i,a,c);s+=Math.abs(u)}return s}var kT={0:hT,1:gT,2:$T,3:bT,4:xT},ST={0:mT,1:yT,2:wT,3:_T,4:vT};Og.exports=function(t,e,n,o,s){let r;if(!("filterType"in o)||o.filterType===-1)r=[0,1,2,3,4];else if(typeof o.filterType=="number")r=[o.filterType];else throw new Error("unrecognised filter types");o.bitDepth===16&&(s*=2);let i=e*s,a=0,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=ST[r[m]](t,c,i,s);h<p&&(d=r[m],p=h)}}u[a]=d,a++,kT[d](t,c,i,u,a,s),a+=i,c+=i}return u}});var Fu=X((i2,Ng)=>{"use strict";var Ct=Go(),ET=Lu(),TT=Cg(),RT=Mg(),CT=require("zlib"),Es=Ng.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||CT.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:Ct.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:Ct.COLORTYPE_COLOR_ALPHA,[Ct.COLORTYPE_GRAYSCALE,Ct.COLORTYPE_COLOR,Ct.COLORTYPE_COLOR_ALPHA,Ct.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([Ct.COLORTYPE_GRAYSCALE,Ct.COLORTYPE_COLOR,Ct.COLORTYPE_COLOR_ALPHA,Ct.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")};Es.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Es.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Es.prototype.filterData=function(t,e,n){let o=TT(t,e,n,this._options),s=Ct.COLORTYPE_TO_BPP_MAP[this._options.colorType];return RT(o,e,n,this._options,s)};Es.prototype._packChunk=function(t,e){let n=e?e.length:0,o=Buffer.alloc(n+12);return o.writeUInt32BE(n,0),o.writeUInt32BE(t,4),e&&e.copy(o,8),o.writeInt32BE(ET.crc32(o.slice(4,o.length-4)),o.length-4),o};Es.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Ct.GAMMA_DIVISION),0),this._packChunk(Ct.TYPE_gAMA,e)};Es.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(Ct.TYPE_IHDR,n)};Es.prototype.packIDAT=function(t){return this._packChunk(Ct.TYPE_IDAT,t)};Es.prototype.packIEND=function(){return this._packChunk(Ct.TYPE_IEND,null)}});var jg=X((a2,Ig)=>{"use strict";var AT=require("util"),Pg=require("stream"),OT=Go(),MT=Fu(),Lg=Ig.exports=function(t){Pg.call(this);let e=t||{};this._packer=new MT(e),this._deflate=this._packer.createDeflate(),this.readable=!0};AT.inherits(Lg,Pg);Lg.prototype.pack=function(t,e,n,o){this.emit("data",Buffer.from(OT.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),o&&this.emit("data",this._packer.packGAMA(o));let s=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(r){this.emit("data",this._packer.packIDAT(r))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var Wg=X((Hr,Ug)=>{"use strict";var Dg=require("assert").ok,Yo=require("zlib"),NT=require("util"),qg=require("buffer").kMaxLength;function Ks(t){if(!(this instanceof Ks))return new Ks(t);t&&t.chunkSize<Yo.Z_MIN_CHUNK&&(t.chunkSize=Yo.Z_MIN_CHUNK),Yo.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 PT(t){return new Ks(t)}function Fg(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Ks.prototype._processChunk=function(t,e,n){if(typeof n=="function")return Yo.Inflate._processChunk.call(this,t,e,n);let o=this,s=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(o._hadError)return;let y=r-g;if(Dg(y>=0,"have should not go down"),y>0){let w=o._buffer.slice(o._offset,o._offset+y);if(o._offset+=y,w.length>i&&(w=w.slice(0,i)),c.push(w),u+=w.length,i-=w.length,i===0)return!1}return(g===0||o._offset>=o._chunkSize)&&(r=o._chunkSize,o._offset=0,o._buffer=Buffer.allocUnsafe(o._chunkSize)),g===0?(a+=s-h,s=h,!0):!1}Dg(this._handle,"zlib binding closed");let p;do p=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,r),p=p||this._writeState;while(!this._hadError&&f(p[0],p[1]));if(this._hadError)throw d;if(u>=qg)throw Fg(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+qg.toString(16)+" bytes");let m=Buffer.concat(c,u);return Fg(this),m};NT.inherits(Ks,Yo.Inflate);function LT(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=Yo.Z_FINISH),t._processChunk(e,n)}function Bg(t,e){return LT(new Ks(e),t)}Ug.exports=Hr=Bg;Hr.Inflate=Ks;Hr.createInflate=PT;Hr.inflateSync=Bg});var Bu=X((c2,Gg)=>{"use strict";var Hg=Gg.exports=function(t){this._buffer=t,this._reads=[]};Hg.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Hg.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 zg=X(Yg=>{"use strict";var IT=Bu(),jT=Mu();Yg.process=function(t,e){let n=[],o=new IT(t);return new jT(e,{read:o.read.bind(o),write:function(r){n.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(n)}});var Jg=X((u2,Vg)=>{"use strict";var Kg=!0,Xg=require("zlib"),DT=Wg();Xg.deflateSync||(Kg=!1);var qT=Bu(),FT=zg(),BT=Iu(),UT=ju(),WT=Du();Vg.exports=function(t,e){if(!Kg)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function o(k){n=k}let s;function r(k){s=k}function i(k){s.transColor=k}function a(k){s.palette=k}function c(){s.alpha=!0}let u;function d(k){u=k}let f=[];function p(k){f.push(k)}let m=new qT(t);if(new BT(e,{read:m.read.bind(m),error:o,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 y;if(s.interlace)y=Xg.inflateSync(g);else{let v=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;y=DT(g,{chunkSize:v,maxLength:v})}if(g=null,!y||!y.length)throw new Error("bad png - invalid inflate data response");let w=FT.process(y,s);g=null;let x=UT.dataToBitMap(w,s);w=null;let S=WT(x,s,e.skipRescale);return s.data=S,s.gamma=u||0,s}});var ty=X((d2,ey)=>{"use strict";var Zg=!0,Qg=require("zlib");Qg.deflateSync||(Zg=!1);var HT=Go(),GT=Fu();ey.exports=function(t,e){if(!Zg)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},o=new GT(n),s=[];s.push(Buffer.from(HT.PNG_SIGNATURE)),s.push(o.packIHDR(t.width,t.height)),t.gamma&&s.push(o.packGAMA(t.gamma));let r=o.filterData(t.data,t.width,t.height),i=Qg.deflateSync(r,o.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return s.push(o.packIDAT(i)),s.push(o.packIEND()),Buffer.concat(s)}});var ny=X(Uu=>{"use strict";var YT=Jg(),zT=ty();Uu.read=function(t,e){return YT(t,e||{})};Uu.write=function(t,e){return zT(t,e)}});var ry=X(oy=>{"use strict";var KT=require("util"),sy=require("stream"),XT=Tg(),VT=jg(),JT=ny(),Dt=oy.PNG=function(t){sy.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 XT(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 VT(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"))};KT.inherits(Dt,sy);Dt.sync=JT;Dt.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};Dt.prototype.parse=function(t,e){if(e){let n,o;n=function(s){this.removeListener("error",o),this.data=s,e(null,this)}.bind(this),o=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",o)}return this.end(t),this};Dt.prototype.write=function(t){return this._parser.write(t),!0};Dt.prototype.end=function(t){this._parser.end(t)};Dt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Dt.prototype._gamma=function(t){this.gamma=t};Dt.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};Dt.bitblt=function(t,e,n,o,s,r,i,a){if(n|=0,o|=0,s|=0,r|=0,i|=0,a|=0,n>t.width||o>t.height||n+s>t.width||o+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+s>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let c=0;c<r;c++)t.data.copy(e.data,(a+c)*e.width+i<<2,(o+c)*t.width+n<<2,(o+c)*t.width+n+s<<2)};Dt.prototype.bitblt=function(t,e,n,o,s,r,i){return Dt.bitblt(this,t,e,n,o,s,r,i),this};Dt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let o=t.width*e+n<<2;for(let s=0;s<3;s++){let r=t.data[o+s]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[o+s]=Math.round(r*255)}}t.gamma=0}};Dt.prototype.adjustGamma=function(){Dt.adjustGamma(this)}});var uy={};wx(uy,{default:()=>cy});function cy(t,e,n,o,s,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:c=[255,255,0],diffColor:u=[255,0,0],includeAA:d,diffColorAlt:f,diffMask:p}=r;if(!Wu(t)||!Wu(e)||n&&!Wu(n))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||n&&n.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==o*s*4)throw new Error("Image data size does not match width/height.");let m=o*s,h=new Uint32Array(t.buffer,t.byteOffset,m),g=new Uint32Array(e.buffer,e.byteOffset,m),y=!0;for(let de=0;de<m;de++)if(h[de]!==g[de]){y=!1;break}if(y){if(n&&!p)for(let de=0;de<m;de++)ay(t,4*de,a,n);return 0}let w=35215*i*i,[x,S,k]=c,[v,C,q]=u,[D,ee,ue]=f||u,le=0;for(let de=0;de<s;de++)for(let M=0;M<o;M++){let G=de*o+M,te=G*4,ge=h[G]===g[G]?0:ly(t,e,te,te,!1);if(Math.abs(ge)>w){let xe=iy(t,M,de,o,s,h,g)||iy(e,M,de,o,s,g,h);!d&&xe?n&&!p&&Ja(n,te,x,S,k):(n&&(ge<0?Ja(n,te,D,ee,ue):Ja(n,te,v,C,q)),le++)}else n&&!p&&ay(t,te,a,n)}return le}function Wu(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function iy(t,e,n,o,s,r,i){let a=Math.max(e-1,0),c=Math.max(n-1,0),u=Math.min(e+1,o-1),d=Math.min(n+1,s-1),f=n*o+e,p=e===a||e===u||n===c||n===d?1:0,m=0,h=0,g=0,y=0,w=0,x=0;for(let S=a;S<=u;S++)for(let k=c;k<=d;k++){if(S===e&&k===n)continue;let v=ly(t,t,f*4,(k*o+S)*4,!0);if(v===0){if(p++,p>2)return!1}else v<m?(m=v,g=S,y=k):v>h&&(h=v,w=S,x=k)}return m===0||h===0?!1:Va(r,g,y,o,s)&&Va(i,g,y,o,s)||Va(r,w,x,o,s)&&Va(i,w,x,o,s)}function Va(t,e,n,o,s){let r=Math.max(e-1,0),i=Math.max(n-1,0),a=Math.min(e+1,o-1),c=Math.min(n+1,s-1),u=t[n*o+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*o+f]),d>2))return!0;return!1}function ly(t,e,n,o,s){let r=t[n],i=t[n+1],a=t[n+2],c=t[n+3],u=e[o],d=e[o+1],f=e[o+2],p=e[o+3],m=r-u,h=i-d,g=a-f,y=c-p;if(!m&&!h&&!g&&!y)return 0;if(c<255||p<255){let v=48+159*(n%2),C=48+159*((n/1.618033988749895|0)%2),q=48+159*((n/2.618033988749895|0)%2);m=(r*c-u*p-v*y)/255,h=(i*c-d*p-C*y)/255,g=(a*c-f*p-q*y)/255}let w=m*.29889531+h*.58662247+g*.11448223;if(s)return w;let x=m*.59597799-h*.2741761-g*.32180189,S=m*.21147017-h*.52261711+g*.31114694,k=.5053*w*w+.299*x*x+.1957*S*S;return w>0?-k:k}function Ja(t,e,n,o,s){t[e+0]=n,t[e+1]=o,t[e+2]=s,t[e+3]=255}function ay(t,e,n,o){let s=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*n*t[e+3]/255;Ja(o,e,s,s,s)}var dy=$x(()=>{});var Xs=X((h2,gy)=>{var ds=require("fs"),ZT=require("path"),QT=require("os"),e1="nex-visual-";function py(t){return ZT.join(QT.tmpdir(),`${e1}${Date.now()}-${t}`)}var Hu=null;function Za(){return Hu||(Hu=ry().PNG),Hu}var Gu=null;function t1(){if(!Gu){let t=(dy(),_x(uy));Gu=t.default||t}return Gu}function Ku(t,e,{threshold:n=.1}={}){let o=Za(),s=t1(),r=o.sync.read(ds.readFileSync(t)),i=o.sync.read(ds.readFileSync(e)),a=Math.max(r.width,i.width),c=Math.max(r.height,i.height),u=fy(r,a,c),d=fy(i,a,c),f=new o({width:a,height:c}),p=s(u,d,f.data,a,c,{threshold:n,includeAA:!1}),m=a*c,h=(p/m*100).toFixed(1),g=n1(f.data,a,c,3,3),y=py("diff.png");return ds.writeFileSync(y,o.sync.write(f),{mode:384}),{diffPath:y,diffPercent:parseFloat(h),totalPixels:m,changedPixels:p,regionSummary:g,beforePath:t,afterPath:e,width:a,height:c}}function fy(t,e,n){if(t.width===e&&t.height===n)return t.data;let o=Buffer.alloc(e*n*4,0);for(let s=0;s<t.height;s++){let r=s*t.width*4,i=s*e*4;t.data.copy(o,i,r,r+t.width*4)}return o}function n1(t,e,n,o,s){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/o),a=Math.ceil(n/s),c=[];for(let u=0;u<s;u++)for(let d=0;d<o;d++){let f=0,p=0,m=d*i,h=u*a,g=Math.min(m+i,e),y=Math.min(h+a,n);for(let w=h;w<y;w++)for(let x=m;x<g;x++){p++;let S=(w*e+x)*4;(t[S]>0||t[S+1]>0)&&f++}if(f>0){let w=(f/p*100).toFixed(1),x=r[u]&&r[u][d]?r[u][d]:`row${u}-col${d}`;c.push({name:x,changedPercent:parseFloat(w),changed:f,total:p})}}return c.sort((u,d)=>d.changedPercent-u.changedPercent),c}var hy=[{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 s1(t,{viewports:e=hy,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let{browserScreenshot:r}=us(),i=[];for(let a of e){let c=await r(t,{width:a.width,height:n,fullPage:o,timeout:s});i.push({label:a.label,width:a.width,path:c.path,base64:c.base64,media_type:c.media_type})}return i}function my(t,e=[]){let n=Za(),o=n.sync.read(ds.readFileSync(t));for(let i of e){let a=o1(i.color||"#FF0000");i.type==="box"?(r1(o,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&zu(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(i1(o,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&zu(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(a1(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&zu(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let s=py("annotated.png");ds.writeFileSync(s,n.sync.write(o),{mode:384});let r=ds.readFileSync(s).toString("base64");return{path:s,base64:r,media_type:"image/png"}}function o1(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 zn(t,e,n,o){if(e<0||n<0||e>=t.width||n>=t.height)return;let s=(n*t.width+e)*4;t.data[s]=o.r,t.data[s+1]=o.g,t.data[s+2]=o.b,t.data[s+3]=o.a}function r1(t,e,n,o,s,r,i=3){for(let a=0;a<i;a++){for(let c=0;c<o;c++)zn(t,e+c,n+a,r),zn(t,e+c,n+s-1-a,r);for(let c=0;c<s;c++)zn(t,e+a,n+c,r),zn(t,e+o-1-a,n+c,r)}}function Yu(t,e,n,o,s,r,i=3){let a=Math.abs(o-e),c=Math.abs(s-n),u=e<o?1:-1,d=n<s?1:-1,f=a-c,p=e,m=n;for(;;){let h=Math.floor(i/2);for(let y=-h;y<=h;y++)for(let w=-h;w<=h;w++)zn(t,p+y,m+w,r);if(p===o&&m===s)break;let g=2*f;g>-c&&(f-=c,p+=u),g<a&&(f+=a,m+=d)}}function i1(t,e,n,o,s,r,i=3){Yu(t,e,n,o,s,r,i);let a=Math.atan2(s-n,o-e),c=15,u=a+Math.PI*.8,d=a-Math.PI*.8;Yu(t,o,s,Math.round(o+c*Math.cos(u)),Math.round(s+c*Math.sin(u)),r,i),Yu(t,o,s,Math.round(o+c*Math.cos(d)),Math.round(s+c*Math.sin(d)),r,i)}function a1(t,e,n,o,s,r=3){for(let i=0;i<r;i++){let a=o-i;for(let c=0;c<360;c+=.5){let u=c*Math.PI/180,d=Math.round(e+a*Math.cos(u)),f=Math.round(n+a*Math.sin(u));zn(t,d,f,s)}}}function zu(t,e,n,o,s){let i=o.length*6+4,a=12;for(let c=0;c<a;c++)for(let u=0;u<i;u++)zn(t,e+u,n+c,{r:0,g:0,b:0,a:200});for(let c=0;c<i;c++)zn(t,e+c,n+a-1,s),zn(t,e+c,n+a-2,s);for(let c=0;c<o.length;c++){let u=e+2+c*6;for(let d=2;d<9;d++)for(let f=0;f<4;f++)zn(t,u+f,n+d,s)}}async function*c1(t,e,{maxIterations:n=20,hmrDelay:o=1500,width:s=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=us(),c=l1("chokidar"),u=await a(t,{width:s,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:u.path,base64:u.base64,media_type:u.media_type},!c){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let d=0,f=!1,p=c.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});p.on("change",()=>{f=!0});try{for(;d<n;){await d1(()=>f,3e5),f=!1,d++,await u1(o);let m=await a(t,{width:s,height:r,timeout:i}),h=null;try{h=Ku(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 l1(t){try{return require(t)}catch{return null}}function u1(t){return new Promise(e=>setTimeout(e,t))}function d1(t,e=6e4){return new Promise((n,o)=>{let s=setInterval(()=>{t()&&(clearInterval(s),clearTimeout(r),n())},200),r=setTimeout(()=>{clearInterval(s),o(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function f1(t,{sampleRate:e=4}={}){let o=Za().sync.read(ds.readFileSync(t)),s=new Map;for(let u=0;u<o.height;u+=e)for(let d=0;d<o.width;d+=e){let f=(u*o.width+d)*4,p=o.data[f],m=o.data[f+1],h=o.data[f+2];if(o.data[f+3]<128)continue;let y=Math.round(p/8)*8,w=Math.round(m/8)*8,x=Math.round(h/8)*8,S=`${y},${w},${x}`;s.set(S,(s.get(S)||0)+1)}let r=[...s.entries()].sort((u,d)=>d[1]-u[1]).slice(0,20),i=r.reduce((u,d)=>u+d[1],0),a=r.map(([u,d])=>{let[f,p,m]=u.split(",").map(Number);return{hex:p1(f,p,m),rgb:`rgb(${f}, ${p}, ${m})`,frequency:parseFloat((d/i*100).toFixed(1)),category:h1(f,p,m)}}),c=m1(o);return{colors:a,spacing:c,dimensions:{width:o.width,height:o.height},imagePath:t}}function p1(t,e,n){return"#"+[t,e,n].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function h1(t,e,n){let o=(t*299+e*587+n*114)/1e3;return o>240?"white/background":o<30?"black/text":o<80?"dark":t>200&&e<100&&n<100?"red/danger":t<100&&e>150&&n<100?"green/success":t<100&&e<100&&n>200?"blue/primary":t>200&&e>200&&n<100?"yellow/warning":t>200&&e>100&&n<50?"orange/accent":o>200?"light/subtle":"midtone"}function m1(t){let e=[],n=!1,o=0,s=g1(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]-s.r)>20||Math.abs(t.data[u+1]-s.g)>20||Math.abs(t.data[u+2]-s.b)>20){a=!1;break}}if(a&&n)n=!1,o=i;else if(!a&&!n&&(n=!0,o>0)){let c=i-o;c>=4&&c<=200&&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 g1(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],n=0,o=0,s=0;for(let[r,i]of e){let a=(i*t.width+r)*4;n+=t.data[a],o+=t.data[a+1],s+=t.data[a+2]}return{r:Math.round(n/4),g:Math.round(o/4),b:Math.round(s/4)}}async function y1(t,e,{width:n,height:o=800,fullPage:s=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=us(),u=Za().sync.read(ds.readFileSync(e)),d=n||u.width,f=o||u.height,p=await a(t,{width:d,height:f,fullPage:s,timeout:i}),m=Ku(e,p.path,{threshold:r}),h=my(p.path,m.regionSummary.filter(g=>g.changedPercent>1).map((g,y)=>{let S=Math.ceil(m.width/3),k=Math.ceil(m.height/3),v=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],C=0,q=0;for(let D=0;D<3;D++)for(let ee=0;ee<3;ee++)v[D][ee]===g.name&&(C=ee,q=D);return{type:"box",x:C*S+2,y:q*k+2,width:S-4,height:k-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:ds.readFileSync(m.diffPath).toString("base64"),annotatedBase64:h.base64}}gy.exports={pixelDiff:Ku,responsiveSweep:s1,annotateImage:my,visualWatch:c1,extractDesignTokens:f1,designCompare:y1,DEFAULT_VIEWPORTS:hy}});var Qa=X((m2,yy)=>{var{C:et}=He(),Yr="",qt=[],Gr=0,Vs=null;function $1(t){Vs=t}function w1(t,e){Yr=t,qt=[],Gr=0;for(let o of e){Gr++;let s=`t${Gr}`;qt.push({id:s,description:o.description||o.title||o.name||o.task||`Task ${Gr}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let n=qt.map(o=>({...o}));return Vs&&Vs("create",{name:t,tasks:n}),n}function b1(t,e,n){let o=qt.find(s=>s.id===t);return o?(o.status=e,n!==void 0&&(o.result=n),Vs&&Vs("update",{id:t,status:e,result:n}),{...o}):null}function _1(){return{name:Yr,tasks:qt.map(t=>({...t}))}}function x1(){Yr="",qt=[],Gr=0,Vs&&Vs("clear",{})}function v1(){return qt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=qt.find(o=>o.id===e);return n&&n.status==="done"}))}function k1(){if(qt.length===0)return`${et.dim}No active tasks${et.reset}`;let t=[];Yr&&(t.push(` ${et.bold}${et.cyan}Tasks: ${Yr}${et.reset}`),t.push(` ${et.dim}${"\u2500".repeat(40)}${et.reset}`));for(let s of qt){let r,i;switch(s.status){case"done":r="\u2713",i=et.green;break;case"in_progress":r="\u2192",i=et.cyan;break;case"failed":r="\u2717",i=et.red;break;default:r="\xB7",i=et.dim}let a=s.dependsOn.length>0?` ${et.dim}(after: ${s.dependsOn.join(", ")})${et.reset}`:"",c=`[${s.status}]`,u=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(t.push(` ${i}${r}${et.reset} ${et.bold}${s.id}${et.reset} ${u.padEnd(40)} ${i}${c}${et.reset}${a}`),s.result&&s.status==="done"){let d=s.result.length>60?s.result.substring(0,57)+"...":s.result;t.push(` ${et.dim}\u2192 ${d}${et.reset}`)}}let e=qt.filter(s=>s.status==="done").length,n=qt.filter(s=>s.status==="failed").length,o=qt.length;return t.push(` ${et.dim}${"\u2500".repeat(40)}${et.reset}`),t.push(` ${et.dim}${e}/${o} done${n>0?`, ${n} failed`:""}${et.reset}`),t.join(`
|
|
153
|
-
`)}function S1(){return qt.length>0&&qt.some(t=>t.status==="pending"||t.status==="in_progress")}
|
|
151
|
+
Then restart nex-code.`;function ug(){if(Wr!==null)return Wr;try{require("playwright"),Wr=!0}catch{Wr=!1}return Wr}async function Xa(){if(!ug())throw new Error(lg);return Tu||(Tu=require("playwright")),(!ls||!ls.isConnected())&&(ls=await Tu.chromium.launch({headless:!0})),ls}async function WE(){if(ls){try{await ls.close()}catch(t){console.error("closeBrowser failed:",t.message)}ls=null}}process.on("exit",()=>{if(ls)try{ls.close()}catch(t){console.error("Error closing browser on exit:",t.message)}});async function HE(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let s=await(await Xa()).newPage();try{await s.goto(t,{waitUntil:n,timeout:e});let r=await s.title(),i=await s.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),a=await s.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(c=>({text:(c.innerText||c.textContent||"").trim().substring(0,80),href:c.href})).filter(c=>c.text&&c.href&&!c.href.startsWith("javascript:")));return{title:r,url:s.url(),text:i.substring(0,8e3)+(i.length>8e3?`
|
|
152
|
+
...(truncated)`:""),links:a.slice(0,20)}}finally{await s.close()}}async function GE(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await Xa()).newPage();try{await i.setViewportSize({width:e,height:n}),await i.goto(t,{waitUntil:"networkidle",timeout:s});let a=await i.screenshot({type:"png",fullPage:o}),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 YE(t,{selector:e,text:n,timeout:o=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await Xa()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:o}),n?await r.getByText(n,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function zE(t,{selector:e,value:n,submit:o=!1,timeout:s=3e4}={}){if(!e||n===void 0)throw new Error("selector and value are required");let i=await(await Xa()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:s}),await i.fill(e,String(n)),o&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${o?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}dg.exports={isPlaywrightAvailable:ug,browserNavigate:HE,browserScreenshot:GE,browserClick:YE,browserFill:zE,closeBrowser:WE,INSTALL_MSG:lg}});var Ru=X((KI,pg)=>{"use strict";var KE=require("util"),fg=require("stream"),En=pg.exports=function(){fg.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};KE.inherits(En,fg);En.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))};En.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};En.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()))};En.prototype.destroySoon=En.prototype.end;En.prototype._end=function(){this._reads.length>0&&this.emit("error",new Error("Unexpected end of input")),this.destroy()};En.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit("close"))};En.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))};En.prototype._processRead=function(t){this._reads.shift();let e=0,n=0,o=Buffer.alloc(t.length);for(;e<t.length;){let s=this._buffers[n++],r=Math.min(s.length,t.length-e);s.copy(o,e,0,r),e+=r,r!==s.length&&(this._buffers[--n]=s.slice(r))}n>0&&this._buffers.splice(0,n),this._buffered-=t.length,t.func.call(this,o)};En.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 Au=X(Cu=>{"use strict";var Ss=[{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]}];Cu.getImagePasses=function(t,e){let n=[],o=t%8,s=e%8,r=(t-o)/8,i=(e-s)/8;for(let a=0;a<Ss.length;a++){let c=Ss[a],u=r*c.x.length,d=i*c.y.length;for(let f=0;f<c.x.length&&c.x[f]<o;f++)u++;for(let f=0;f<c.y.length&&c.y[f]<s;f++)d++;u>0&&d>0&&n.push({width:u,height:d,index:a})}return n};Cu.getInterlaceIterator=function(t){return function(e,n,o){let s=e%Ss[o].x.length,r=(e-s)/Ss[o].x.length*8+Ss[o].x[s],i=n%Ss[o].y.length,a=(n-i)/Ss[o].y.length*8+Ss[o].y[i];return r*4+a*t*4}}});var Ou=X((VI,hg)=>{"use strict";hg.exports=function(e,n,o){let s=e+n-o,r=Math.abs(s-e),i=Math.abs(s-n),a=Math.abs(s-o);return r<=i&&r<=a?e:i<=a?n:o}});var Mu=X((JI,gg)=>{"use strict";var XE=Au(),VE=Ou();function mg(t,e,n){let o=t*e;return n!==8&&(o=Math.ceil(o/(8/n))),o}var Ho=gg.exports=function(t,e){let n=t.width,o=t.height,s=t.interlace,r=t.bpp,i=t.depth;if(this.read=e.read,this.write=e.write,this.complete=e.complete,this._imageIndex=0,this._images=[],s){let a=XE.getImagePasses(n,o);for(let c=0;c<a.length;c++)this._images.push({byteWidth:mg(a[c].width,r,i),height:a[c].height,lineIndex:0})}else this._images.push({byteWidth:mg(n,r,i),height:o,lineIndex:0});i===8?this._xComparison=r:i===16?this._xComparison=r*2:this._xComparison=1};Ho.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Ho.prototype._unFilterType1=function(t,e,n){let o=this._xComparison,s=o-1;for(let r=0;r<n;r++){let i=t[1+r],a=r>s?e[r-o]:0;e[r]=i+a}};Ho.prototype._unFilterType2=function(t,e,n){let o=this._lastLine;for(let s=0;s<n;s++){let r=t[1+s],i=o?o[s]:0;e[s]=r+i}};Ho.prototype._unFilterType3=function(t,e,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],c=r?r[i]:0,u=i>s?e[i-o]:0,d=Math.floor((u+c)/2);e[i]=a+d}};Ho.prototype._unFilterType4=function(t,e,n){let o=this._xComparison,s=o-1,r=this._lastLine;for(let i=0;i<n;i++){let a=t[1+i],c=r?r[i]:0,u=i>s?e[i-o]:0,d=i>s&&r?r[i-o]:0,f=VE(u,c,d);e[i]=a+f}};Ho.prototype._reverseFilterLine=function(t){let e=t[0],n,o=this._images[this._imageIndex],s=o.byteWidth;if(e===0)n=t.slice(1,s+1);else switch(n=Buffer.alloc(s),e){case 1:this._unFilterType1(t,n,s);break;case 2:this._unFilterType2(t,n,s);break;case 3:this._unFilterType3(t,n,s);break;case 4:this._unFilterType4(t,n,s);break;default:throw new Error("Unrecognised filter type - "+e)}this.write(n),o.lineIndex++,o.lineIndex>=o.height?(this._lastLine=null,this._imageIndex++,o=this._images[this._imageIndex]):this._lastLine=n,o?this.read(o.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}});var wg=X((ZI,$g)=>{"use strict";var JE=require("util"),yg=Ru(),ZE=Mu(),QE=$g.exports=function(t){yg.call(this);let e=[],n=this;this._filter=new ZE(t,{read:this.read.bind(this),write:function(o){e.push(o)},complete:function(){n.emit("complete",Buffer.concat(e))}}),this._filter.start()};JE.inherits(QE,yg)});var Go=X((QI,bg)=>{"use strict";bg.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 Lu=X((e2,_g)=>{"use strict";var Nu=[];(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;Nu[t]=e}})();var Pu=_g.exports=function(){this._crc=-1};Pu.prototype.write=function(t){for(let e=0;e<t.length;e++)this._crc=Nu[(this._crc^t[e])&255]^this._crc>>>8;return!0};Pu.prototype.crc32=function(){return this._crc^-1};Pu.crc32=function(t){let e=-1;for(let n=0;n<t.length;n++)e=Nu[(e^t[n])&255]^e>>>8;return e^-1}});var Iu=X((t2,xg)=>{"use strict";var wt=Go(),eT=Lu(),_t=xg.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[wt.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[wt.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[wt.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[wt.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[wt.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[wt.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(){}};_t.prototype.start=function(){this.read(wt.PNG_SIGNATURE.length,this._parseSignature.bind(this))};_t.prototype._parseSignature=function(t){let e=wt.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))};_t.prototype._parseChunkBegin=function(t){let e=t.readUInt32BE(0),n=t.readUInt32BE(4),o="";for(let r=4;r<8;r++)o+=String.fromCharCode(t[r]);let s=!!(t[4]&32);if(!this._hasIHDR&&n!==wt.TYPE_IHDR){this.error(new Error("Expected IHDR on beggining"));return}if(this._crc=new eT,this._crc.write(Buffer.from(o)),this._chunks[n])return this._chunks[n](e);if(!s){this.error(new Error("Unsupported critical chunk type "+o));return}this.read(e+4,this._skipChunk.bind(this))};_t.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};_t.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};_t.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))};_t.prototype._handleIHDR=function(t){this.read(t,this._parseIHDR.bind(this))};_t.prototype._parseIHDR=function(t){this._crc.write(t);let e=t.readUInt32BE(0),n=t.readUInt32BE(4),o=t[8],s=t[9],r=t[10],i=t[11],a=t[12];if(o!==8&&o!==4&&o!==2&&o!==1&&o!==16){this.error(new Error("Unsupported bit depth "+o));return}if(!(s in wt.COLORTYPE_TO_BPP_MAP)){this.error(new Error("Unsupported color type"));return}if(r!==0){this.error(new Error("Unsupported compression method"));return}if(i!==0){this.error(new Error("Unsupported filter method"));return}if(a!==0&&a!==1){this.error(new Error("Unsupported interlace method"));return}this._colorType=s;let c=wt.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:e,height:n,depth:o,interlace:!!a,palette:!!(s&wt.COLORTYPE_PALETTE),color:!!(s&wt.COLORTYPE_COLOR),alpha:!!(s&wt.COLORTYPE_ALPHA),bpp:c,colorType:s}),this._handleChunkEnd()};_t.prototype._handlePLTE=function(t){this.read(t,this._parsePLTE.bind(this))};_t.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()};_t.prototype._handleTRNS=function(t){this.simpleTransparency(),this.read(t,this._parseTRNS.bind(this))};_t.prototype._parseTRNS=function(t){if(this._crc.write(t),this._colorType===wt.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===wt.COLORTYPE_GRAYSCALE&&this.transColor([t.readUInt16BE(0)]),this._colorType===wt.COLORTYPE_COLOR&&this.transColor([t.readUInt16BE(0),t.readUInt16BE(2),t.readUInt16BE(4)]),this._handleChunkEnd()};_t.prototype._handleGAMA=function(t){this.read(t,this._parseGAMA.bind(this))};_t.prototype._parseGAMA=function(t){this._crc.write(t),this.gamma(t.readUInt32BE(0)/wt.GAMMA_DIVISION),this._handleChunkEnd()};_t.prototype._handleIDAT=function(t){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-t,this._parseIDAT.bind(this,t))};_t.prototype._parseIDAT=function(t,e){if(this._crc.write(e),this._colorType===wt.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()};_t.prototype._handleIEND=function(t){this.read(t,this._parseIEND.bind(this))};_t.prototype._parseIEND=function(t){this._crc.write(t),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}});var ju=X(kg=>{"use strict";var vg=Au(),tT=[function(){},function(t,e,n,o){if(o===e.length)throw new Error("Ran out of data");let s=e[o];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=255},function(t,e,n,o){if(o+1>=e.length)throw new Error("Ran out of data");let s=e[o];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=e[o+1]},function(t,e,n,o){if(o+2>=e.length)throw new Error("Ran out of data");t[n]=e[o],t[n+1]=e[o+1],t[n+2]=e[o+2],t[n+3]=255},function(t,e,n,o){if(o+3>=e.length)throw new Error("Ran out of data");t[n]=e[o],t[n+1]=e[o+1],t[n+2]=e[o+2],t[n+3]=e[o+3]}],nT=[function(){},function(t,e,n,o){let s=e[0];t[n]=s,t[n+1]=s,t[n+2]=s,t[n+3]=o},function(t,e,n){let o=e[0];t[n]=o,t[n+1]=o,t[n+2]=o,t[n+3]=e[1]},function(t,e,n,o){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=o},function(t,e,n){t[n]=e[0],t[n+1]=e[1],t[n+2]=e[2],t[n+3]=e[3]}];function sT(t,e){let n=[],o=0;function s(){if(o===t.length)throw new Error("Ran out of data");let r=t[o];o++;let i,a,c,u,d,f,p,m;switch(e){default:throw new Error("unrecognised depth");case 16:p=t[o],o++,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;)s();let i=n.slice(0,r);return n=n.slice(r),i},resetAfterLine:function(){n.length=0},end:function(){if(o!==t.length)throw new Error("extra data found")}}}function oT(t,e,n,o,s,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);tT[o](e,s,f,r),r+=o}return r}function rT(t,e,n,o,s,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=s.get(o),p=n(d,u,c);nT[o](e,f,p,r)}s.resetAfterLine()}}kg.dataToBitMap=function(t,e){let n=e.width,o=e.height,s=e.depth,r=e.bpp,i=e.interlace,a;s!==8&&(a=sT(t,s));let c;s<=8?c=Buffer.alloc(n*o*4):c=new Uint16Array(n*o*4);let u=Math.pow(2,s)-1,d=0,f,p;if(i)f=vg.getImagePasses(n,o),p=vg.getInterlaceIterator(n,o);else{let m=0;p=function(){let h=m;return m+=4,h},f=[{width:n,height:o}]}for(let m=0;m<f.length;m++)s===8?d=oT(f[m],c,p,r,t,d):rT(f[m],c,p,r,a,u);if(s===8){if(d!==t.length)throw new Error("extra data found")}else a.end();return c}});var Du=X((s2,Sg)=>{"use strict";function iT(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let c=s[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 aT(t,e,n,o,s){let r=0;for(let i=0;i<o;i++)for(let a=0;a<n;a++){let c=!1;if(s.length===1?s[0]===t[r]&&(c=!0):s[0]===t[r]&&s[1]===t[r+1]&&s[2]===t[r+2]&&(c=!0),c)for(let u=0;u<4;u++)e[r+u]=0;r+=4}}function cT(t,e,n,o,s){let r=255,i=Math.pow(2,s)-1,a=0;for(let c=0;c<o;c++)for(let u=0;u<n;u++){for(let d=0;d<4;d++)e[a+d]=Math.floor(t[a+d]*r/i+.5);a+=4}}Sg.exports=function(t,e,n=!1){let o=e.depth,s=e.width,r=e.height,i=e.colorType,a=e.transColor,c=e.palette,u=t;return i===3?iT(t,u,s,r,c):(a&&aT(t,u,s,r,a),o!==8&&!n&&(o===16&&(u=Buffer.alloc(s*r*4)),cT(t,u,s,r,o))),u}});var Rg=X((o2,Tg)=>{"use strict";var lT=require("util"),qu=require("zlib"),Eg=Ru(),uT=wg(),dT=Iu(),fT=ju(),pT=Du(),Yn=Tg.exports=function(t){Eg.call(this),this._parser=new dT(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()};lT.inherits(Yn,Eg);Yn.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};Yn.prototype._inflateData=function(t){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=qu.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let n=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,o=Math.max(n,qu.Z_MIN_CHUNK);this._inflate=qu.createInflate({chunkSize:o});let s=n,r=this.emit.bind(this,"error");this._inflate.on("error",function(a){s&&r(a)}),this._filter.on("complete",this._complete.bind(this));let i=this._filter.write.bind(this._filter);this._inflate.on("data",function(a){s&&(a.length>s&&(a=a.slice(0,s)),s-=a.length,i(a))}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(t)};Yn.prototype._handleMetaData=function(t){this._metaData=t,this._bitmapInfo=Object.create(t),this._filter=new uT(this._bitmapInfo)};Yn.prototype._handleTransColor=function(t){this._bitmapInfo.transColor=t};Yn.prototype._handlePalette=function(t){this._bitmapInfo.palette=t};Yn.prototype._simpleTransparency=function(){this._metaData.alpha=!0};Yn.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};Yn.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit("error","No Inflate block"))};Yn.prototype._complete=function(t){if(this.errord)return;let e;try{let n=fT.dataToBitMap(t,this._bitmapInfo);e=pT(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(n){this._handleError(n);return}this.emit("parsed",e)}});var Ag=X((r2,Cg)=>{"use strict";var mn=Go();Cg.exports=function(t,e,n,o){let s=[mn.COLORTYPE_COLOR_ALPHA,mn.COLORTYPE_ALPHA].indexOf(o.colorType)!==-1;if(o.colorType===o.inputColorType){let h=(function(){let g=new ArrayBuffer(2);return new DataView(g).setInt16(0,256,!0),new Int16Array(g)[0]!==256})();if(o.bitDepth===8||o.bitDepth===16&&h)return t}let r=o.bitDepth!==16?t:new Uint16Array(t.buffer),i=255,a=mn.COLORTYPE_TO_BPP_MAP[o.inputColorType];a===4&&!o.inputHasAlpha&&(a=3);let c=mn.COLORTYPE_TO_BPP_MAP[o.colorType];o.bitDepth===16&&(i=65535,c*=2);let u=Buffer.alloc(e*n*c),d=0,f=0,p=o.bgColor||{};p.red===void 0&&(p.red=i),p.green===void 0&&(p.green=i),p.blue===void 0&&(p.blue=i);function m(){let h,g,y,w=i;switch(o.inputColorType){case mn.COLORTYPE_COLOR_ALPHA:w=r[d+3],h=r[d],g=r[d+1],y=r[d+2];break;case mn.COLORTYPE_COLOR:h=r[d],g=r[d+1],y=r[d+2];break;case mn.COLORTYPE_ALPHA:w=r[d+1],h=r[d],g=h,y=h;break;case mn.COLORTYPE_GRAYSCALE:h=r[d],g=h,y=h;break;default:throw new Error("input color type:"+o.inputColorType+" is not supported at present")}return o.inputHasAlpha&&(s||(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),y=Math.min(Math.max(Math.round((1-w)*p.blue+w*y),0),i))),{red:h,green:g,blue:y,alpha:w}}for(let h=0;h<n;h++)for(let g=0;g<e;g++){let y=m(r,d);switch(o.colorType){case mn.COLORTYPE_COLOR_ALPHA:case mn.COLORTYPE_COLOR:o.bitDepth===8?(u[f]=y.red,u[f+1]=y.green,u[f+2]=y.blue,s&&(u[f+3]=y.alpha)):(u.writeUInt16BE(y.red,f),u.writeUInt16BE(y.green,f+2),u.writeUInt16BE(y.blue,f+4),s&&u.writeUInt16BE(y.alpha,f+6));break;case mn.COLORTYPE_ALPHA:case mn.COLORTYPE_GRAYSCALE:{let w=(y.red+y.green+y.blue)/3;o.bitDepth===8?(u[f]=w,s&&(u[f+1]=y.alpha)):(u.writeUInt16BE(w,f),s&&u.writeUInt16BE(y.alpha,f+2));break}default:throw new Error("unrecognised color Type "+o.colorType)}d+=a,f+=c}return u}});var Ng=X((i2,Mg)=>{"use strict";var Og=Ou();function hT(t,e,n,o,s){for(let r=0;r<n;r++)o[s+r]=t[e+r]}function mT(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++)o+=Math.abs(t[r]);return o}function gT(t,e,n,o,s,r){for(let i=0;i<n;i++){let a=i>=r?t[e+i-r]:0,c=t[e+i]-a;o[s+i]=c}}function yT(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=t[e+r]-i;s+=Math.abs(a)}return s}function $T(t,e,n,o,s){for(let r=0;r<n;r++){let i=e>0?t[e+r-n]:0,a=t[e+r]-i;o[s+r]=a}}function wT(t,e,n){let o=0,s=e+n;for(let r=e;r<s;r++){let i=e>0?t[r-n]:0,a=t[r]-i;o+=Math.abs(a)}return o}function bT(t,e,n,o,s,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);o[s+i]=u}}function _T(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-n]:0,c=t[e+r]-(i+a>>1);s+=Math.abs(c)}return s}function xT(t,e,n,o,s,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]-Og(a,c,u);o[s+i]=d}}function vT(t,e,n,o){let s=0;for(let r=0;r<n;r++){let i=r>=o?t[e+r-o]:0,a=e>0?t[e+r-n]:0,c=e>0&&r>=o?t[e+r-(n+o)]:0,u=t[e+r]-Og(i,a,c);s+=Math.abs(u)}return s}var kT={0:hT,1:gT,2:$T,3:bT,4:xT},ST={0:mT,1:yT,2:wT,3:_T,4:vT};Mg.exports=function(t,e,n,o,s){let r;if(!("filterType"in o)||o.filterType===-1)r=[0,1,2,3,4];else if(typeof o.filterType=="number")r=[o.filterType];else throw new Error("unrecognised filter types");o.bitDepth===16&&(s*=2);let i=e*s,a=0,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=ST[r[m]](t,c,i,s);h<p&&(d=r[m],p=h)}}u[a]=d,a++,kT[d](t,c,i,u,a,s),a+=i,c+=i}return u}});var Fu=X((a2,Pg)=>{"use strict";var Ct=Go(),ET=Lu(),TT=Ag(),RT=Ng(),CT=require("zlib"),Es=Pg.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||CT.createDeflate,t.bitDepth=t.bitDepth||8,t.colorType=typeof t.colorType=="number"?t.colorType:Ct.COLORTYPE_COLOR_ALPHA,t.inputColorType=typeof t.inputColorType=="number"?t.inputColorType:Ct.COLORTYPE_COLOR_ALPHA,[Ct.COLORTYPE_GRAYSCALE,Ct.COLORTYPE_COLOR,Ct.COLORTYPE_COLOR_ALPHA,Ct.COLORTYPE_ALPHA].indexOf(t.colorType)===-1)throw new Error("option color type:"+t.colorType+" is not supported at present");if([Ct.COLORTYPE_GRAYSCALE,Ct.COLORTYPE_COLOR,Ct.COLORTYPE_COLOR_ALPHA,Ct.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")};Es.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Es.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Es.prototype.filterData=function(t,e,n){let o=TT(t,e,n,this._options),s=Ct.COLORTYPE_TO_BPP_MAP[this._options.colorType];return RT(o,e,n,this._options,s)};Es.prototype._packChunk=function(t,e){let n=e?e.length:0,o=Buffer.alloc(n+12);return o.writeUInt32BE(n,0),o.writeUInt32BE(t,4),e&&e.copy(o,8),o.writeInt32BE(ET.crc32(o.slice(4,o.length-4)),o.length-4),o};Es.prototype.packGAMA=function(t){let e=Buffer.alloc(4);return e.writeUInt32BE(Math.floor(t*Ct.GAMMA_DIVISION),0),this._packChunk(Ct.TYPE_gAMA,e)};Es.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(Ct.TYPE_IHDR,n)};Es.prototype.packIDAT=function(t){return this._packChunk(Ct.TYPE_IDAT,t)};Es.prototype.packIEND=function(){return this._packChunk(Ct.TYPE_IEND,null)}});var Dg=X((c2,jg)=>{"use strict";var AT=require("util"),Lg=require("stream"),OT=Go(),MT=Fu(),Ig=jg.exports=function(t){Lg.call(this);let e=t||{};this._packer=new MT(e),this._deflate=this._packer.createDeflate(),this.readable=!0};AT.inherits(Ig,Lg);Ig.prototype.pack=function(t,e,n,o){this.emit("data",Buffer.from(OT.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(e,n)),o&&this.emit("data",this._packer.packGAMA(o));let s=this._packer.filterData(t,e,n);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(r){this.emit("data",this._packer.packIDAT(r))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(s)}});var Hg=X((Hr,Wg)=>{"use strict";var qg=require("assert").ok,Yo=require("zlib"),NT=require("util"),Fg=require("buffer").kMaxLength;function Ks(t){if(!(this instanceof Ks))return new Ks(t);t&&t.chunkSize<Yo.Z_MIN_CHUNK&&(t.chunkSize=Yo.Z_MIN_CHUNK),Yo.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 PT(t){return new Ks(t)}function Bg(t,e){e&&process.nextTick(e),t._handle&&(t._handle.close(),t._handle=null)}Ks.prototype._processChunk=function(t,e,n){if(typeof n=="function")return Yo.Inflate._processChunk.call(this,t,e,n);let o=this,s=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(o._hadError)return;let y=r-g;if(qg(y>=0,"have should not go down"),y>0){let w=o._buffer.slice(o._offset,o._offset+y);if(o._offset+=y,w.length>i&&(w=w.slice(0,i)),c.push(w),u+=w.length,i-=w.length,i===0)return!1}return(g===0||o._offset>=o._chunkSize)&&(r=o._chunkSize,o._offset=0,o._buffer=Buffer.allocUnsafe(o._chunkSize)),g===0?(a+=s-h,s=h,!0):!1}qg(this._handle,"zlib binding closed");let p;do p=this._handle.writeSync(e,t,a,s,this._buffer,this._offset,r),p=p||this._writeState;while(!this._hadError&&f(p[0],p[1]));if(this._hadError)throw d;if(u>=Fg)throw Bg(this),new RangeError("Cannot create final Buffer. It would be larger than 0x"+Fg.toString(16)+" bytes");let m=Buffer.concat(c,u);return Bg(this),m};NT.inherits(Ks,Yo.Inflate);function LT(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=Yo.Z_FINISH),t._processChunk(e,n)}function Ug(t,e){return LT(new Ks(e),t)}Wg.exports=Hr=Ug;Hr.Inflate=Ks;Hr.createInflate=PT;Hr.inflateSync=Ug});var Bu=X((l2,Yg)=>{"use strict";var Gg=Yg.exports=function(t){this._buffer=t,this._reads=[]};Gg.prototype.read=function(t,e){this._reads.push({length:Math.abs(t),allowLess:t<0,func:e})};Gg.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 Kg=X(zg=>{"use strict";var IT=Bu(),jT=Mu();zg.process=function(t,e){let n=[],o=new IT(t);return new jT(e,{read:o.read.bind(o),write:function(r){n.push(r)},complete:function(){}}).start(),o.process(),Buffer.concat(n)}});var Zg=X((d2,Jg)=>{"use strict";var Xg=!0,Vg=require("zlib"),DT=Hg();Vg.deflateSync||(Xg=!1);var qT=Bu(),FT=Kg(),BT=Iu(),UT=ju(),WT=Du();Jg.exports=function(t,e){if(!Xg)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n;function o(k){n=k}let s;function r(k){s=k}function i(k){s.transColor=k}function a(k){s.palette=k}function c(){s.alpha=!0}let u;function d(k){u=k}let f=[];function p(k){f.push(k)}let m=new qT(t);if(new BT(e,{read:m.read.bind(m),error:o,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 y;if(s.interlace)y=Vg.inflateSync(g);else{let v=((s.width*s.bpp*s.depth+7>>3)+1)*s.height;y=DT(g,{chunkSize:v,maxLength:v})}if(g=null,!y||!y.length)throw new Error("bad png - invalid inflate data response");let w=FT.process(y,s);g=null;let x=UT.dataToBitMap(w,s);w=null;let S=WT(x,s,e.skipRescale);return s.data=S,s.gamma=u||0,s}});var ny=X((f2,ty)=>{"use strict";var Qg=!0,ey=require("zlib");ey.deflateSync||(Qg=!1);var HT=Go(),GT=Fu();ty.exports=function(t,e){if(!Qg)throw new Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let n=e||{},o=new GT(n),s=[];s.push(Buffer.from(HT.PNG_SIGNATURE)),s.push(o.packIHDR(t.width,t.height)),t.gamma&&s.push(o.packGAMA(t.gamma));let r=o.filterData(t.data,t.width,t.height),i=ey.deflateSync(r,o.getDeflateOptions());if(r=null,!i||!i.length)throw new Error("bad png - invalid compressed data response");return s.push(o.packIDAT(i)),s.push(o.packIEND()),Buffer.concat(s)}});var sy=X(Uu=>{"use strict";var YT=Zg(),zT=ny();Uu.read=function(t,e){return YT(t,e||{})};Uu.write=function(t,e){return zT(t,e)}});var iy=X(ry=>{"use strict";var KT=require("util"),oy=require("stream"),XT=Rg(),VT=Dg(),JT=sy(),Dt=ry.PNG=function(t){oy.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 XT(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 VT(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"))};KT.inherits(Dt,oy);Dt.sync=JT;Dt.prototype.pack=function(){return!this.data||!this.data.length?(this.emit("error","No data provided"),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)};Dt.prototype.parse=function(t,e){if(e){let n,o;n=function(s){this.removeListener("error",o),this.data=s,e(null,this)}.bind(this),o=function(s){this.removeListener("parsed",n),e(s,null)}.bind(this),this.once("parsed",n),this.once("error",o)}return this.end(t),this};Dt.prototype.write=function(t){return this._parser.write(t),!0};Dt.prototype.end=function(t){this._parser.end(t)};Dt.prototype._metadata=function(t){this.width=t.width,this.height=t.height,this.emit("metadata",t)};Dt.prototype._gamma=function(t){this.gamma=t};Dt.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit("close")};Dt.bitblt=function(t,e,n,o,s,r,i,a){if(n|=0,o|=0,s|=0,r|=0,i|=0,a|=0,n>t.width||o>t.height||n+s>t.width||o+r>t.height)throw new Error("bitblt reading outside image");if(i>e.width||a>e.height||i+s>e.width||a+r>e.height)throw new Error("bitblt writing outside image");for(let c=0;c<r;c++)t.data.copy(e.data,(a+c)*e.width+i<<2,(o+c)*t.width+n<<2,(o+c)*t.width+n+s<<2)};Dt.prototype.bitblt=function(t,e,n,o,s,r,i){return Dt.bitblt(this,t,e,n,o,s,r,i),this};Dt.adjustGamma=function(t){if(t.gamma){for(let e=0;e<t.height;e++)for(let n=0;n<t.width;n++){let o=t.width*e+n<<2;for(let s=0;s<3;s++){let r=t.data[o+s]/255;r=Math.pow(r,1/2.2/t.gamma),t.data[o+s]=Math.round(r*255)}}t.gamma=0}};Dt.prototype.adjustGamma=function(){Dt.adjustGamma(this)}});var dy={};wx(dy,{default:()=>ly});function ly(t,e,n,o,s,r={}){let{threshold:i=.1,alpha:a=.1,aaColor:c=[255,255,0],diffColor:u=[255,0,0],includeAA:d,diffColorAlt:f,diffMask:p}=r;if(!Wu(t)||!Wu(e)||n&&!Wu(n))throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(t.length!==e.length||n&&n.length!==t.length)throw new Error("Image sizes do not match.");if(t.length!==o*s*4)throw new Error("Image data size does not match width/height.");let m=o*s,h=new Uint32Array(t.buffer,t.byteOffset,m),g=new Uint32Array(e.buffer,e.byteOffset,m),y=!0;for(let de=0;de<m;de++)if(h[de]!==g[de]){y=!1;break}if(y){if(n&&!p)for(let de=0;de<m;de++)cy(t,4*de,a,n);return 0}let w=35215*i*i,[x,S,k]=c,[v,C,q]=u,[D,ee,ue]=f||u,le=0;for(let de=0;de<s;de++)for(let M=0;M<o;M++){let G=de*o+M,te=G*4,ge=h[G]===g[G]?0:uy(t,e,te,te,!1);if(Math.abs(ge)>w){let xe=ay(t,M,de,o,s,h,g)||ay(e,M,de,o,s,g,h);!d&&xe?n&&!p&&Ja(n,te,x,S,k):(n&&(ge<0?Ja(n,te,D,ee,ue):Ja(n,te,v,C,q)),le++)}else n&&!p&&cy(t,te,a,n)}return le}function Wu(t){return ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT===1}function ay(t,e,n,o,s,r,i){let a=Math.max(e-1,0),c=Math.max(n-1,0),u=Math.min(e+1,o-1),d=Math.min(n+1,s-1),f=n*o+e,p=e===a||e===u||n===c||n===d?1:0,m=0,h=0,g=0,y=0,w=0,x=0;for(let S=a;S<=u;S++)for(let k=c;k<=d;k++){if(S===e&&k===n)continue;let v=uy(t,t,f*4,(k*o+S)*4,!0);if(v===0){if(p++,p>2)return!1}else v<m?(m=v,g=S,y=k):v>h&&(h=v,w=S,x=k)}return m===0||h===0?!1:Va(r,g,y,o,s)&&Va(i,g,y,o,s)||Va(r,w,x,o,s)&&Va(i,w,x,o,s)}function Va(t,e,n,o,s){let r=Math.max(e-1,0),i=Math.max(n-1,0),a=Math.min(e+1,o-1),c=Math.min(n+1,s-1),u=t[n*o+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*o+f]),d>2))return!0;return!1}function uy(t,e,n,o,s){let r=t[n],i=t[n+1],a=t[n+2],c=t[n+3],u=e[o],d=e[o+1],f=e[o+2],p=e[o+3],m=r-u,h=i-d,g=a-f,y=c-p;if(!m&&!h&&!g&&!y)return 0;if(c<255||p<255){let v=48+159*(n%2),C=48+159*((n/1.618033988749895|0)%2),q=48+159*((n/2.618033988749895|0)%2);m=(r*c-u*p-v*y)/255,h=(i*c-d*p-C*y)/255,g=(a*c-f*p-q*y)/255}let w=m*.29889531+h*.58662247+g*.11448223;if(s)return w;let x=m*.59597799-h*.2741761-g*.32180189,S=m*.21147017-h*.52261711+g*.31114694,k=.5053*w*w+.299*x*x+.1957*S*S;return w>0?-k:k}function Ja(t,e,n,o,s){t[e+0]=n,t[e+1]=o,t[e+2]=s,t[e+3]=255}function cy(t,e,n,o){let s=255+(t[e]*.29889531+t[e+1]*.58662247+t[e+2]*.11448223-255)*n*t[e+3]/255;Ja(o,e,s,s,s)}var fy=$x(()=>{});var Xs=X((m2,yy)=>{var ds=require("fs"),ZT=require("path"),QT=require("os"),e1="nex-visual-";function hy(t){return ZT.join(QT.tmpdir(),`${e1}${Date.now()}-${t}`)}var Hu=null;function Za(){return Hu||(Hu=iy().PNG),Hu}var Gu=null;function t1(){if(!Gu){let t=(fy(),_x(dy));Gu=t.default||t}return Gu}function Ku(t,e,{threshold:n=.1}={}){let o=Za(),s=t1(),r=o.sync.read(ds.readFileSync(t)),i=o.sync.read(ds.readFileSync(e)),a=Math.max(r.width,i.width),c=Math.max(r.height,i.height),u=py(r,a,c),d=py(i,a,c),f=new o({width:a,height:c}),p=s(u,d,f.data,a,c,{threshold:n,includeAA:!1}),m=a*c,h=(p/m*100).toFixed(1),g=n1(f.data,a,c,3,3),y=hy("diff.png");return ds.writeFileSync(y,o.sync.write(f),{mode:384}),{diffPath:y,diffPercent:parseFloat(h),totalPixels:m,changedPixels:p,regionSummary:g,beforePath:t,afterPath:e,width:a,height:c}}function py(t,e,n){if(t.width===e&&t.height===n)return t.data;let o=Buffer.alloc(e*n*4,0);for(let s=0;s<t.height;s++){let r=s*t.width*4,i=s*e*4;t.data.copy(o,i,r,r+t.width*4)}return o}function n1(t,e,n,o,s){let r=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],i=Math.ceil(e/o),a=Math.ceil(n/s),c=[];for(let u=0;u<s;u++)for(let d=0;d<o;d++){let f=0,p=0,m=d*i,h=u*a,g=Math.min(m+i,e),y=Math.min(h+a,n);for(let w=h;w<y;w++)for(let x=m;x<g;x++){p++;let S=(w*e+x)*4;(t[S]>0||t[S+1]>0)&&f++}if(f>0){let w=(f/p*100).toFixed(1),x=r[u]&&r[u][d]?r[u][d]:`row${u}-col${d}`;c.push({name:x,changedPercent:parseFloat(w),changed:f,total:p})}}return c.sort((u,d)=>d.changedPercent-u.changedPercent),c}var my=[{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 s1(t,{viewports:e=my,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let{browserScreenshot:r}=us(),i=[];for(let a of e){let c=await r(t,{width:a.width,height:n,fullPage:o,timeout:s});i.push({label:a.label,width:a.width,path:c.path,base64:c.base64,media_type:c.media_type})}return i}function gy(t,e=[]){let n=Za(),o=n.sync.read(ds.readFileSync(t));for(let i of e){let a=o1(i.color||"#FF0000");i.type==="box"?(r1(o,i.x||0,i.y||0,i.width||50,i.height||50,a,i.thickness||3),i.label&&zu(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="arrow"?(i1(o,i.x||0,i.y||0,i.toX||i.x+50,i.toY||i.y,a,i.thickness||3),i.label&&zu(o,i.x||0,(i.y||0)-14,i.label,a)):i.type==="circle"&&(a1(o,i.x||0,i.y||0,i.radius||20,a,i.thickness||3),i.label&&zu(o,(i.x||0)-(i.radius||20),(i.y||0)-(i.radius||20)-14,i.label,a))}let s=hy("annotated.png");ds.writeFileSync(s,n.sync.write(o),{mode:384});let r=ds.readFileSync(s).toString("base64");return{path:s,base64:r,media_type:"image/png"}}function o1(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 zn(t,e,n,o){if(e<0||n<0||e>=t.width||n>=t.height)return;let s=(n*t.width+e)*4;t.data[s]=o.r,t.data[s+1]=o.g,t.data[s+2]=o.b,t.data[s+3]=o.a}function r1(t,e,n,o,s,r,i=3){for(let a=0;a<i;a++){for(let c=0;c<o;c++)zn(t,e+c,n+a,r),zn(t,e+c,n+s-1-a,r);for(let c=0;c<s;c++)zn(t,e+a,n+c,r),zn(t,e+o-1-a,n+c,r)}}function Yu(t,e,n,o,s,r,i=3){let a=Math.abs(o-e),c=Math.abs(s-n),u=e<o?1:-1,d=n<s?1:-1,f=a-c,p=e,m=n;for(;;){let h=Math.floor(i/2);for(let y=-h;y<=h;y++)for(let w=-h;w<=h;w++)zn(t,p+y,m+w,r);if(p===o&&m===s)break;let g=2*f;g>-c&&(f-=c,p+=u),g<a&&(f+=a,m+=d)}}function i1(t,e,n,o,s,r,i=3){Yu(t,e,n,o,s,r,i);let a=Math.atan2(s-n,o-e),c=15,u=a+Math.PI*.8,d=a-Math.PI*.8;Yu(t,o,s,Math.round(o+c*Math.cos(u)),Math.round(s+c*Math.sin(u)),r,i),Yu(t,o,s,Math.round(o+c*Math.cos(d)),Math.round(s+c*Math.sin(d)),r,i)}function a1(t,e,n,o,s,r=3){for(let i=0;i<r;i++){let a=o-i;for(let c=0;c<360;c+=.5){let u=c*Math.PI/180,d=Math.round(e+a*Math.cos(u)),f=Math.round(n+a*Math.sin(u));zn(t,d,f,s)}}}function zu(t,e,n,o,s){let i=o.length*6+4,a=12;for(let c=0;c<a;c++)for(let u=0;u<i;u++)zn(t,e+u,n+c,{r:0,g:0,b:0,a:200});for(let c=0;c<i;c++)zn(t,e+c,n+a-1,s),zn(t,e+c,n+a-2,s);for(let c=0;c<o.length;c++){let u=e+2+c*6;for(let d=2;d<9;d++)for(let f=0;f<4;f++)zn(t,u+f,n+d,s)}}async function*c1(t,e,{maxIterations:n=20,hmrDelay:o=1500,width:s=1280,height:r=800,timeout:i=3e4}={}){let{browserScreenshot:a}=us(),c=l1("chokidar"),u=await a(t,{width:s,height:r,timeout:i});if(yield{iteration:0,type:"baseline",path:u.path,base64:u.base64,media_type:u.media_type},!c){yield{iteration:-1,type:"error",message:"chokidar not installed \u2014 watch mode requires it. Install with: npm install chokidar"};return}let d=0,f=!1,p=c.watch(e,{ignoreInitial:!0,ignored:/(node_modules|\.git|dist)/});p.on("change",()=>{f=!0});try{for(;d<n;){await d1(()=>f,3e5),f=!1,d++,await u1(o);let m=await a(t,{width:s,height:r,timeout:i}),h=null;try{h=Ku(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 l1(t){try{return require(t)}catch{return null}}function u1(t){return new Promise(e=>setTimeout(e,t))}function d1(t,e=6e4){return new Promise((n,o)=>{let s=setInterval(()=>{t()&&(clearInterval(s),clearTimeout(r),n())},200),r=setTimeout(()=>{clearInterval(s),o(new Error("Watch timeout \u2014 no file changes detected"))},e)})}function f1(t,{sampleRate:e=4}={}){let o=Za().sync.read(ds.readFileSync(t)),s=new Map;for(let u=0;u<o.height;u+=e)for(let d=0;d<o.width;d+=e){let f=(u*o.width+d)*4,p=o.data[f],m=o.data[f+1],h=o.data[f+2];if(o.data[f+3]<128)continue;let y=Math.round(p/8)*8,w=Math.round(m/8)*8,x=Math.round(h/8)*8,S=`${y},${w},${x}`;s.set(S,(s.get(S)||0)+1)}let r=[...s.entries()].sort((u,d)=>d[1]-u[1]).slice(0,20),i=r.reduce((u,d)=>u+d[1],0),a=r.map(([u,d])=>{let[f,p,m]=u.split(",").map(Number);return{hex:p1(f,p,m),rgb:`rgb(${f}, ${p}, ${m})`,frequency:parseFloat((d/i*100).toFixed(1)),category:h1(f,p,m)}}),c=m1(o);return{colors:a,spacing:c,dimensions:{width:o.width,height:o.height},imagePath:t}}function p1(t,e,n){return"#"+[t,e,n].map(o=>Math.min(255,o).toString(16).padStart(2,"0")).join("")}function h1(t,e,n){let o=(t*299+e*587+n*114)/1e3;return o>240?"white/background":o<30?"black/text":o<80?"dark":t>200&&e<100&&n<100?"red/danger":t<100&&e>150&&n<100?"green/success":t<100&&e<100&&n>200?"blue/primary":t>200&&e>200&&n<100?"yellow/warning":t>200&&e>100&&n<50?"orange/accent":o>200?"light/subtle":"midtone"}function m1(t){let e=[],n=!1,o=0,s=g1(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]-s.r)>20||Math.abs(t.data[u+1]-s.g)>20||Math.abs(t.data[u+2]-s.b)>20){a=!1;break}}if(a&&n)n=!1,o=i;else if(!a&&!n&&(n=!0,o>0)){let c=i-o;c>=4&&c<=200&&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 g1(t){let e=[[0,0],[t.width-1,0],[0,t.height-1],[t.width-1,t.height-1]],n=0,o=0,s=0;for(let[r,i]of e){let a=(i*t.width+r)*4;n+=t.data[a],o+=t.data[a+1],s+=t.data[a+2]}return{r:Math.round(n/4),g:Math.round(o/4),b:Math.round(s/4)}}async function y1(t,e,{width:n,height:o=800,fullPage:s=!1,threshold:r=.1,timeout:i=3e4}={}){let{browserScreenshot:a}=us(),u=Za().sync.read(ds.readFileSync(e)),d=n||u.width,f=o||u.height,p=await a(t,{width:d,height:f,fullPage:s,timeout:i}),m=Ku(e,p.path,{threshold:r}),h=gy(p.path,m.regionSummary.filter(g=>g.changedPercent>1).map((g,y)=>{let S=Math.ceil(m.width/3),k=Math.ceil(m.height/3),v=[["top-left","top-center","top-right"],["middle-left","center","middle-right"],["bottom-left","bottom-center","bottom-right"]],C=0,q=0;for(let D=0;D<3;D++)for(let ee=0;ee<3;ee++)v[D][ee]===g.name&&(C=ee,q=D);return{type:"box",x:C*S+2,y:q*k+2,width:S-4,height:k-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:ds.readFileSync(m.diffPath).toString("base64"),annotatedBase64:h.base64}}yy.exports={pixelDiff:Ku,responsiveSweep:s1,annotateImage:gy,visualWatch:c1,extractDesignTokens:f1,designCompare:y1,DEFAULT_VIEWPORTS:my}});var Qa=X((g2,$y)=>{var{C:et}=He(),Yr="",qt=[],Gr=0,Vs=null;function $1(t){Vs=t}function w1(t,e){Yr=t,qt=[],Gr=0;for(let o of e){Gr++;let s=`t${Gr}`;qt.push({id:s,description:o.description||o.title||o.name||o.task||`Task ${Gr}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let n=qt.map(o=>({...o}));return Vs&&Vs("create",{name:t,tasks:n}),n}function b1(t,e,n){let o=qt.find(s=>s.id===t);return o?(o.status=e,n!==void 0&&(o.result=n),Vs&&Vs("update",{id:t,status:e,result:n}),{...o}):null}function _1(){return{name:Yr,tasks:qt.map(t=>({...t}))}}function x1(){Yr="",qt=[],Gr=0,Vs&&Vs("clear",{})}function v1(){return qt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=qt.find(o=>o.id===e);return n&&n.status==="done"}))}function k1(){if(qt.length===0)return`${et.dim}No active tasks${et.reset}`;let t=[];Yr&&(t.push(` ${et.bold}${et.cyan}Tasks: ${Yr}${et.reset}`),t.push(` ${et.dim}${"\u2500".repeat(40)}${et.reset}`));for(let s of qt){let r,i;switch(s.status){case"done":r="\u2713",i=et.green;break;case"in_progress":r="\u2192",i=et.cyan;break;case"failed":r="\u2717",i=et.red;break;default:r="\xB7",i=et.dim}let a=s.dependsOn.length>0?` ${et.dim}(after: ${s.dependsOn.join(", ")})${et.reset}`:"",c=`[${s.status}]`,u=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(t.push(` ${i}${r}${et.reset} ${et.bold}${s.id}${et.reset} ${u.padEnd(40)} ${i}${c}${et.reset}${a}`),s.result&&s.status==="done"){let d=s.result.length>60?s.result.substring(0,57)+"...":s.result;t.push(` ${et.dim}\u2192 ${d}${et.reset}`)}}let e=qt.filter(s=>s.status==="done").length,n=qt.filter(s=>s.status==="failed").length,o=qt.length;return t.push(` ${et.dim}${"\u2500".repeat(40)}${et.reset}`),t.push(` ${et.dim}${e}/${o} done${n>0?`, ${n} failed`:""}${et.reset}`),t.join(`
|
|
153
|
+
`)}function S1(){return qt.length>0&&qt.some(t=>t.status==="pending"||t.status==="in_progress")}$y.exports={createTasks:w1,updateTask:b1,getTaskList:_1,clearTasks:x1,getReadyTasks:v1,renderTaskList:k1,setOnChange:$1,hasActiveTasks:S1}});var ec=X((y2,by)=>{var zr={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:18,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
|
|
154
154
|
Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
|
|
155
155
|
You excel at sysadmin, frontend, and multi-step coding tasks.
|
|
156
156
|
Prefer action over narration \u2014 read, fix, verify, done.`},"devstral-small":{staleWarn:2e4,staleAbort:6e4,investigationCap:10,postEditCap:8,briefing:`You are devstral-small, a fast and lightweight coding model.
|
|
@@ -163,7 +163,7 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:2e4,staleAbort:6e4,i
|
|
|
163
163
|
Prioritize decisive, targeted edits. Read only what you need, then fix.
|
|
164
164
|
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.
|
|
165
165
|
Trust your reasoning. Use tools thoroughly when the task demands it.
|
|
166
|
-
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}}
|
|
166
|
+
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},wy={staleWarn:6e4,staleAbort:12e4,investigationCap:18,postEditCap:10};function E1(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let r of Object.keys(zr))e.startsWith(r)&&r.length>o&&(n=r,o=r.length);let s=n?{...zr[n]}:{...wy};for(let[r,i]of[["NEX_STALE_WARN_MS","staleWarn"],["NEX_STALE_ABORT_MS","staleAbort"]])if(process.env[r]){let a=parseInt(process.env[r],10);Number.isInteger(a)&&a>=1e3&&a<=3e5&&(s[i]=a)}return s}function T1(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let s of Object.keys(zr))e.startsWith(s)&&s.length>o&&(n=s,o=s.length);return n&&zr[n].briefing||""}by.exports={getModelProfile:E1,getModelBriefing:T1,PROFILES:zr,DEFAULTS:wy}});var Vu=X(($2,Ey)=>{var{callChat:R1}=Xe(),{estimateTokens:Xu}=en(),_y=process.env.NEX_COMPACTION!=="false",xy=6,vy=2e3,ky=3,C1=`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.
|
|
167
167
|
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.
|
|
168
168
|
|
|
169
169
|
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:
|
|
@@ -195,30 +195,30 @@ Format your output as:
|
|
|
195
195
|
|
|
196
196
|
<summary>
|
|
197
197
|
[Sections 1-9 above]
|
|
198
|
-
</summary>`,Js=0;async function A1(t){if(!
|
|
199
|
-
${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return Js++,null}}function O1(){Js=0}function
|
|
198
|
+
</summary>`,Js=0;async function A1(t){if(!_y||t.length<xy||Js>=ky)return null;let e=[{role:"system",content:C1},{role:"user",content:Sy(t)}];try{let o=((await R1(e,[],{temperature:0,maxTokens:vy})).content||"").trim();if(!o)return Js++,null;let s=o.match(/<summary>([\s\S]*?)<\/summary>/);if(s?o=s[1].trim():o=o.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!o)return Js++,null;let r=t.reduce((a,c)=>a+Xu(c.content||"")+(c.tool_calls?Xu(JSON.stringify(c.tool_calls)):0),0),i=Xu(o);return i>=r*.8?(Js++,null):(Js=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
199
|
+
${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return Js++,null}}function O1(){Js=0}function Sy(t){return t.map(e=>{let n=e.role==="tool"?"tool_result":e.role,o=(e.content||"").substring(0,500);if(e.tool_calls){let s=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${n}] ${o}
|
|
200
200
|
tools: ${s}`}return`[${n}] ${o}`}).join(`
|
|
201
201
|
|
|
202
|
-
`)}
|
|
202
|
+
`)}Ey.exports={compactMessages:A1,formatMessagesForSummary:Sy,resetCompactionFailures:O1,COMPACTION_ENABLED:_y,COMPACTION_MIN_MESSAGES:xy,COMPACTION_SUMMARY_BUDGET:vy,MAX_CONSECUTIVE_FAILURES:ky}});var en=X((w2,Iy)=>{var M1=require("path");function Ry(){return Xe().getActiveModel()}var N1={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},P1={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},Zs=new Map,Ty=1e3,Ju=new WeakMap,Qs=null;function L1(){if(Qs!==null)return Qs;try{let t=Ry(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[o,s]of Object.entries(P1))if(n.startsWith(o))return Qs=s,Qs;return Qs=N1[e]||4,Qs}catch{return 4}}function I1(){Qs=null}function eo(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=Zs.get(e);if(n!==void 0)return Zs.delete(e),Zs.set(e,n),n;let o=Math.ceil(t.length/L1());if(Zs.size>=Ty){let s=Ty>>1,r=Zs.keys();for(let i=0;i<s;i++)Zs.delete(r.next().value)}return Zs.set(e,o),o}function j1(t){if(Ju.has(t))return Ju.get(t);let e=JSON.stringify(t);return Ju.set(t,e),e}function to(t){let n=4;if(t.content&&(n+=eo(t.content)),t.tool_calls)for(let o of t.tool_calls){n+=4,n+=eo(o.function?.name||"");let s=o.function?.arguments;typeof s=="string"?n+=eo(s):s&&(n+=eo(JSON.stringify(s)))}return n}function Tn(t){let e=0;for(let n of t)e+=to(n);return e}function D1(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let n=t?t.length:0,o=e.length,s=0;for(let r=n;r<o;r++)s+=to(e[r]);return s}var Zu=new WeakMap;function tc(t){if(!t||t.length===0)return 0;if(Zu.has(t))return Zu.get(t);let e=eo(JSON.stringify(t));return Zu.set(t,e),e}function nc(){return Ry()?.contextWindow||32768}var Ft={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0};function q1(t,e){let n=t.length>0?t[t.length-1]:null,o=e?e.length:0;if(Ft.result&&t.length===Ft.msgCount&&n===Ft.lastMsgRef&&o===Ft.toolCount)return Ft.result;let s,r,i,a;if(Ft.messagesRef===t&&t.length>Ft.msgCount&&Ft.msgCount>=0){s=Ft.messageTokens,r=Ft.systemTokens,i=Ft.conversationTokens,a=Ft.toolResultTokens;for(let m=Ft.msgCount;m<t.length;m++){let h=to(t[m]);s+=h,t[m].role==="system"?r+=h:t[m].role==="tool"?a+=h:i+=h}}else{s=0,r=0,i=0,a=0;for(let m of t){let h=to(m);s+=h,m.role==="system"?r+=h:m.role==="tool"?a+=h:i+=h}}let c=tc(e),u=s+c,d=nc(),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 Ft={msgCount:t.length,lastMsgRef:n,toolCount:o,result:p,messagesRef:t,messageTokens:s,systemTokens:r,conversationTokens:i,toolResultTokens:a},p}var Kr=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,Cy=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,Ay=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Oy={essential:.6,standard:.65,full:Math.min(Kr,.75)};function My(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Kr;try{let{getActiveTier:t}=Ur(),e=t();return Oy[e]??Kr}catch{return Kr}}var F1=200,B1=1e3;function Ny(t,e){if(!t||t.length<=e)return t;let o=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=o)return t;let s=t.split(`
|
|
203
203
|
`);if(s.length<=10){let h=Math.floor(o*.6),g=Math.floor(o*.4),y=t.substring(0,h),w=t.substring(t.length-g);return y+`
|
|
204
204
|
...(${t.length} chars total)...
|
|
205
205
|
`+w}let r=Math.floor(s.length*.4),i=Math.floor(s.length*.4),a=[],c=0,u=Math.floor(o*.4);for(let h=0;h<r&&c<u;h++)if(c+s[h].length+1>u&&s[h].trim().startsWith("```")){a.push(s[h]),c+=s[h].length+1;let g=h+1;for(;g<s.length&&c<u*1.5&&!s[g].trim().startsWith("```");)a.push(s[g]),c+=s[g].length+1,g++;g<s.length&&s[g].trim().startsWith("```")&&(a.push(s[g]),c+=s[g].length+1),h=g}else a.push(s[h]),c+=s[h].length+1;let d=[],f=0,p=Math.floor(o*.4);for(let h=s.length-1;h>=s.length-i&&f<p;h--)if(f+s[h].length+1>p&&s[h].trim().startsWith("```")){d.push(s[h]),f+=s[h].length+1;let g=h-1;for(;g>=0&&f<p*1.5&&!s[g].trim().startsWith("```");)d.push(s[g]),f+=s[g].length+1,g--;g>=0&&s[g].trim().startsWith("```")&&(d.push(s[g]),f+=s[g].length+1),h=g}else d.push(s[h]),f+=s[h].length+1;d.reverse();let m=s.length-a.length-d.length;return a.join(`
|
|
206
206
|
`)+`
|
|
207
207
|
...(${m} lines omitted, ${s.length} total)...
|
|
208
208
|
`+d.join(`
|
|
209
|
-
`)}function Ko(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:B1,o=e==="aggressive"?50:e==="medium"?100:F1;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:
|
|
210
|
-
...(truncated)`),s.tool_calls&&e==="aggressive"&&(s.tool_calls=s.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),s}return t}function
|
|
209
|
+
`)}function Ko(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:B1,o=e==="aggressive"?50:e==="medium"?100:F1;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:Ny(s,o)}:t}if(t.role==="assistant"){let s={...t};return s.content&&s.content.length>n&&(s.content=s.content.substring(0,n)+`
|
|
210
|
+
...(truncated)`),s.tool_calls&&e==="aggressive"&&(s.tool_calls=s.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),s}return t}function Py(t,e,n,o){let s=0;if(t.role==="system")return 100;if(t.role==="user")s+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?s+=30:s+=15}else t.role==="assistant"&&(s+=t.tool_calls?20:10);let r=n>1?e/(n-1):1;if(s+=Math.round(r*30),o&&o.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),a=0;for(let c of o)(i.includes(c)||i.includes(M1.basename(c)))&&a++;s+=Math.min(30,a*10)}return Math.min(100,s)}function Ly(t,e=10){let n=new Set,o=t.slice(-e),s=/(?:\/[\w.-]+)+\.\w+/g;for(let r of o){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(s);a&&a.forEach(c=>n.add(c))}return n}function U1(t,{filesModified:e=new Set,currentPhase:n=null}={}){let o=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");o.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}n&&o.push(`Current phase: ${n}`);let s=t.filter(r=>r.role==="assistant"&&typeof r.content=="string"&&r.content.trim().length>30).slice(-3).map(r=>r.content.trim().slice(0,200).replace(/\n+/g," "));return s.length>0&&o.push(`Recent progress:
|
|
211
211
|
`+s.map(r=>`- ${r}`).join(`
|
|
212
212
|
`)),o.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
|
|
213
213
|
${o.join(`
|
|
214
|
-
`)}`,_pinned:!0,_progressSnapshot:!0}}var zo={msgCount:-1,lastMsgRef:null,result:null};function W1(){zo={msgCount:-1,lastMsgRef:null,result:null},Ft={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function H1(t,e,n={}){let o=t.length>0?t[t.length-1]:null;if(!n.force&&zo.result&&t.length===zo.msgCount&&o===zo.lastMsgRef)return zo.result;let s=n.threshold??
|
|
214
|
+
`)}`,_pinned:!0,_progressSnapshot:!0}}var zo={msgCount:-1,lastMsgRef:null,result:null};function W1(){zo={msgCount:-1,lastMsgRef:null,result:null},Ft={msgCount:-1,lastMsgRef:null,toolCount:-1,result:null,messagesRef:null,messageTokens:0,systemTokens:0,conversationTokens:0,toolResultTokens:0}}async function H1(t,e,n={}){let o=t.length>0?t[t.length-1]:null;if(!n.force&&zo.result&&t.length===zo.msgCount&&o===zo.lastMsgRef)return zo.result;let s=n.threshold??My(),r=n.safetyMargin??Cy,i=n.keepRecent??Ay,a=nc(),c=tc(e),u=Math.floor(a*(s-r)),d=u-c,f=Tn(t);if(f+c<=u){let le={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return zo={msgCount:t.length,lastMsgRef:o,result:le},le}let m=f,h=null,g=0;t.length>0&&t[0].role==="system"&&(h=t[0],g=1);let y=Math.max(g,t.length-i),w=t.slice(g,y),x=t.slice(y),S=w.map(le=>Ko(le,"light")),k=Ts(h,S,x),v=Tn(k);if(v+c<=u)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-v};if(S=w.map(le=>Ko(le,"medium")),k=Ts(h,S,x),v=Tn(k),v+c<=u)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-v};if(S=w.map(le=>Ko(le,"aggressive")),k=Ts(h,S,x),v=Tn(k),v+c<=u)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-v};let C=process.env.NEX_SKIP_COMPACTOR==="1",q=w.filter(le=>le._pinned),D=w.filter(le=>!le._compacted&&!le._pinned);if(!C&&D.length>=6)try{let{compactMessages:le}=Vu(),de=await le(D);if(de){let M=w.filter(xe=>xe._compacted&&!xe._pinned),G=[...q,...M,de.message],te=Ts(h,G,x),ge=Tn(te);if(ge+c<=u)return{messages:te,compressed:!0,compacted:!0,tokensRemoved:m-ge};w=G}}catch(le){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",le.message)}let ee=Ly([...S,...x]),ue=S.map((le,de)=>({msg:le,score:le._pinned?1/0:Py(le,de,S.length,ee),tokens:to(le)}));for(;ue.length>0&&v>d;){let le=-1;for(let de=0;de<ue.length;de++)ue[de].score!==1/0&&(le===-1||ue[de].score<ue[le].score)&&(le=de);if(le===-1)break;v-=ue[le].tokens,ue.splice(le,1)}return S=ue.map(le=>le.msg),k=Ts(h,S,x),v=Tn(k),{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-v}}function Ts(t,e,n){let o=[];return t&&o.push(t),o.push(...e,...n),o}function G1(t,e){if(!t)return"";if(eo(t)<=e)return t;let o=e*4,s=t.split(`
|
|
215
215
|
`),r=Math.floor(o*.6),i=Math.floor(o*.4),a="",c=0;for(let m of s){if(a.length+m.length+1>r)break;a+=(a?`
|
|
216
216
|
`:"")+m,c++}let u="",d=0;for(let m=s.length-1;m>=c;m--){let h=s[m]+(u?`
|
|
217
217
|
`:"")+u;if(h.length>i)break;u=h,d++}let p=`
|
|
218
218
|
|
|
219
219
|
... (${s.length-c-d} lines omitted, ${s.length} total) ...
|
|
220
220
|
|
|
221
|
-
`;return a+p+u}var Y1=6;function z1(t,e,n=!1){let o=nc(),s=tc(e),r=Math.floor(o*(n?.35:.5))-s,i=Tn(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:Y1,f=Math.max(u,t.length-d),p=t.slice(u,f),m=t.slice(f),h=p.map(v=>Ko(v,"aggressive"));n&&(m=m.map(v=>Ko(v,"aggressive")));let g=Ts(c,h,m),y=Tn(g);for(;h.length>0&&y>r;){let v=h.shift();y-=to(v)}n&&y>r&&(m=m.filter(C=>C.role==="user").slice(-1),g=Ts(c,[],m),y=Tn(g)),g=Ts(c,h,m);let w=t.filter(v=>v.role==="user"),x=v=>{let C=typeof v.content=="string"?v.content:"";return C.startsWith("[SYSTEM WARNING]")||C.startsWith("[SYSTEM:")||C.startsWith("BLOCKED:")},S=w.find(v=>!x(v)),k=[...w].reverse().find(v=>!x(v));if(S&&!g.find(v=>v===S)){let v=g.findIndex(q=>q.role==="system"),C=v>=0?v+1:0;g.splice(C,0,S)}return k&&k!==S&&!g.find(v=>v===k)&&g.push(k),{messages:g,tokensRemoved:i-Tn(g)}}
|
|
221
|
+
`;return a+p+u}var Y1=6;function z1(t,e,n=!1){let o=nc(),s=tc(e),r=Math.floor(o*(n?.35:.5))-s,i=Tn(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:Y1,f=Math.max(u,t.length-d),p=t.slice(u,f),m=t.slice(f),h=p.map(v=>Ko(v,"aggressive"));n&&(m=m.map(v=>Ko(v,"aggressive")));let g=Ts(c,h,m),y=Tn(g);for(;h.length>0&&y>r;){let v=h.shift();y-=to(v)}n&&y>r&&(m=m.filter(C=>C.role==="user").slice(-1),g=Ts(c,[],m),y=Tn(g)),g=Ts(c,h,m);let w=t.filter(v=>v.role==="user"),x=v=>{let C=typeof v.content=="string"?v.content:"";return C.startsWith("[SYSTEM WARNING]")||C.startsWith("[SYSTEM:")||C.startsWith("BLOCKED:")},S=w.find(v=>!x(v)),k=[...w].reverse().find(v=>!x(v));if(S&&!g.find(v=>v===S)){let v=g.findIndex(q=>q.role==="system"),C=v>=0?v+1:0;g.splice(C,0,S)}return k&&k!==S&&!g.find(v=>v===k)&&g.push(k),{messages:g,tokensRemoved:i-Tn(g)}}Iy.exports={estimateTokens:eo,estimateMessageTokens:to,estimateMessagesTokens:Tn,estimateDeltaTokens:D1,estimateToolsTokens:tc,serializeMessage:j1,getContextWindow:nc,getUsage:q1,compressMessage:Ko,compressToolResult:Ny,scoreMessageRelevance:Py,extractActiveFiles:Ly,buildProgressSnapshot:U1,fitToContext:H1,forceCompress:z1,truncateFileContent:G1,invalidateTokenRatioCache:I1,invalidateFitToContextCache:W1,getEffectiveCompressionThreshold:My,COMPRESSION_THRESHOLD:Kr,TIER_COMPRESSION_THRESHOLDS:Oy,SAFETY_MARGIN:Cy,KEEP_RECENT:Ay}});var Vo=X((b2,jy)=>{var{fork:K1}=require("child_process"),X1=require("path"),V1=X1.join(__dirname,"background-worker.js"),no=new Map,Xo=new Map;function J1(){return`bg-${Date.now()}-${Math.random().toString(36).slice(2,6)}`}function Z1(t){let e=J1(),n=K1(V1,[],{silent:!0,env:process.env,cwd:process.cwd()});return n.send({jobId:e,agentDef:t}),n.on("message",o=>{o.type==="result"?Qu(e,t,o.payload):o.type==="error"&&Qu(e,t,{task:t.task,status:"failed",result:`Background agent error: ${o.error}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}),n.on("exit",(o,s)=>{if(no.has(e)){let r=s?`killed (${s})`:`exit code ${o}`;Qu(e,t,{task:t.task,status:"failed",result:`Background agent terminated unexpectedly: ${r}`,toolsUsed:[],tokensUsed:{input:0,output:0}})}}),no.set(e,{process:n,agentDef:t,startedAt:Date.now()}),e}function Qu(t,e,n){no.delete(t),Xo.set(t,{jobId:t,agentDef:e,result:n,finishedAt:Date.now()})}function Q1(){if(Xo.size===0)return[];let t=[...Xo.values()];return Xo.clear(),t}function eR(){return no.size>0||Xo.size>0}function tR(){let t=no.size;return t===0?"":`${t} bg agent${t===1?"":"s"} running`}function nR(){for(let[t,e]of no){try{e.process.kill("SIGTERM")}catch{}no.delete(t)}Xo.clear()}jy.exports={createJob:Z1,getCompletedJobs:Q1,getPendingJobSummary:tR,hasPendingOrCompletedJobs:eR,cancelAllJobs:nR}});var ac=X((x2,o$)=>{var{callStream:sR,getActiveProviderName:oc,getActiveModelId:Dy,getConfiguredProviders:oR,getProvider:qy,getActiveProvider:Fy,parseModelSpec:By}=Xe(),{parseToolArgs:Uy}=Uo(),{filterToolsForModel:rR,getModelTier:sc}=Ur(),{getModelBriefing:iR}=ec(),{trackUsage:Wy,estimateTokens:Hy}=xs(),{MultiProgress:aR,C:_2}=He();function Gy(t){return!t||typeof t!="string"?0:typeof Hy=="function"?Hy(t):Math.ceil(t.length/4)}var Ky=15,cR=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),Yy=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Xy=8,lR=2,rc=new Map,Vy=600*1e3;function uR(t,e){let n=rc.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<Vy?!1:(rc.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Xr(t){rc.delete(t)}function ed(){rc.clear()}function td(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 Jy(t){let e=td(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Zy(t,e,n){let o;for(let s=0;s<=Yy;s++)try{return await sR(t,e,n)}catch(r){o=r;let i=td(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(s<Yy&&Jy(r)){let c=i==="rate_limit"?Math.min(2e3*Math.pow(2,s),15e3):Math.min(500*Math.pow(2,s),4e3);await new Promise(u=>setTimeout(u,c).unref());continue}throw r}throw o}var zy=new Set(["ask_user","task_list"]);function Qy(t){return t>=2?new Set([...zy,"spawn_agents"]):zy}var dR=new Set(["write_file","edit_file","patch_file"]),e$={explore:{allowedTools:new Set(["bash","read_file","list_directory","glob","grep","search_files","web_fetch","web_search"]),systemSuffix:"You are an exploration agent. Read and search code only. Do NOT modify any files."},review:{allowedTools:new Set(["read_file","list_directory","glob","grep","search_files"]),systemSuffix:'You are a code review agent. Read code and report findings only. Do NOT make changes. Output findings first, ordered by severity, using this format: "Finding: <title> | Severity: <high|medium|low> | File: <path[:line]> | Why: <impact>". After findings, add one short "Residual risk:" line. If there are no findings, say "No material findings" and still mention the main residual risk/test gap.'},implement:{allowedTools:null,systemSuffix:""}},fR=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,pR=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function t$(t){return pR.test(t)?"full":fR.test(t)?"essential":t.length>300?"full":"standard"}function n$(t){let e=oR(),n=oc(),o=[...e].sort((s,r)=>(s.name===n?-1:1)-(r.name===n?-1:1));for(let s of o)for(let r of s.models)if(sc(r.id,s.name)===t)return{provider:s.name,model:r.id};return null}var hR={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function ic(t){if(t.model){let{provider:s,model:r}=By(t.model),i=s?qy(s):Fy(),a=s||oc();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=sc(r,a);return{provider:a,model:r,tier:c}}}let e=t$(t.task),n=hR[e];if(n){let{provider:s,model:r}=By(n),i=s?qy(s):Fy(),a=s||oc();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=sc(r,a);return{provider:a,model:r,tier:c}}}let o=n$(e);if(o){let s=sc(o.model,o.provider);return{provider:o.provider,model:o.model,tier:s}}return{provider:null,model:null,tier:null}}async function s$(t,e={},n=0){let o=n===0?Ky:Xy,s=Math.min(t.max_iterations||10,o),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},c=new Set,u=new Map,d=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
|
|
222
222
|
|
|
223
223
|
TASK: ${t.task}
|
|
224
224
|
${t.context?`
|
|
@@ -244,30 +244,30 @@ TOOL STRATEGY:
|
|
|
244
244
|
ERROR RECOVERY:
|
|
245
245
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
246
246
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
247
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`,f=t.type&&
|
|
247
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`,f=t.type&&e$[t.type],p=f&&f.systemSuffix?`
|
|
248
248
|
|
|
249
|
-
${f.systemSuffix}`:"",m=ic(t),h=m.provider,g=m.model,y=m.tier,w=iR(g||
|
|
249
|
+
${f.systemSuffix}`:"",m=ic(t),h=m.provider,g=m.model,y=m.tier,w=iR(g||Dy()),S=[{role:"system",content:(w?`## Model Briefing
|
|
250
250
|
${w}
|
|
251
251
|
|
|
252
252
|
---
|
|
253
253
|
|
|
254
|
-
`:"")+d+p}];S.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:k,executeTool:v}=Sn(),C=
|
|
255
|
-
`)}let D={};h&&(D.provider=h),g&&(D.model=g);let ee=new Set;try{for(let le=0;le<s;le++){let de=await
|
|
256
|
-
...(truncated)`:R,tool_call_id:P}}).catch(O=>(W&&(Xr(W),c.delete(W)),{role:"tool",content:`ERROR: ${O.message}`,tool_call_id:P}))}),Ne=await Promise.all(xe);if(S.push(...Ne),le>=7&&S.length>12)try{let{compressMessage:Ae}=en(),ke=S.length-6;for(let E=1;E<ke;E++)S[E]._subAgentCompressed||(S[E]={...Ae(S[E],"light"),_subAgentCompressed:!0})}catch{}for(let Ae=0;Ae<G.length;Ae++){let ke=G[Ae];if(ke.function.name==="bash_exec"){let E=
|
|
254
|
+
`:"")+d+p}];S.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:k,executeTool:v}=Sn(),C=Qy(n),q=rR(k.filter(ue=>!C.has(ue.function.name)),y);if(f&&f.allowedTools&&(q=q.filter(ue=>f.allowedTools.has(ue.function.name))),g&&!t._skipLog){let ue=y?` (${y})`:"";process.stderr.write(` [sub-agent: ${h}:${g}${ue}]
|
|
255
|
+
`)}let D={};h&&(D.provider=h),g&&(D.model=g);let ee=new Set;try{for(let le=0;le<s;le++){let de=await Zy(S,q,D);if(!de||typeof de!="object")throw new Error("Empty or invalid response from provider");{let Ae=h||oc(),ke=g||Dy();if(de.usage){let E=de.usage.prompt_tokens||0,P=de.usage.completion_tokens||0;a.input+=E,a.output+=P,Wy(Ae,ke,E,P)}else{let E=de.content||"",P=S.map(O=>typeof O.content=="string"?O.content:Array.isArray(O.content)?O.content.map(R=>typeof R=="string"?R:R.text||"").join(""):"").join(" "),W=Gy(P),oe=Gy(E);a.input+=W,a.output+=oe,a._estimated=!0,Wy(Ae,ke,W,oe)}}let M=de.content||"",G=de.tool_calls,te={role:"assistant",content:M||""};if(G&&G.length>0&&(te.tool_calls=G),S.push(te),!G||G.length===0){for(let Ae of c)Xr(Ae);return{task:t.task,status:"done",result:M||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}let ge=new Set,xe=G.map(Ae=>{let ke=Ae.function.name,E=Uy(Ae.function.arguments),P=Ae.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!E)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${ke}`,tool_call_id:P});if(["edit_file","patch_file"].includes(ke)&&E.path){if(ee.has(E.path)||ge.has(E.path))return Promise.resolve({role:"tool",content:`BLOCKED: "${E.path}" was already edited \u2014 re-read the changed section first (read_file with line_start/line_end) before making another edit. The file content has changed and your previous read is stale.`,tool_call_id:P});ge.add(E.path)}let W=null;if(dR.has(ke)&&E.path){let O=require("path"),R=O.isAbsolute(E.path)?E.path:O.resolve(process.cwd(),E.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let Q=O.relative(process.cwd(),R);if(t._readOnlyFiles.some(U=>Q===U||Q.startsWith(U+"/")||R===U||R.startsWith(U+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${E.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:P})}if(c.has(R)||!uR(R,r))return Promise.resolve({role:"tool",content:`ERROR: File '${E.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:P});c.add(R),W=R}return i.push(ke),e.onUpdate&&e.onUpdate({type:"tool_call",tool:ke,agentId:r}),(ke==="spawn_agents"?nd(E,n+1):v(ke,E,{autoConfirm:!0,silent:!0})).then(O=>{W&&(Xr(W),c.delete(W));let R=String(O??"");return E&&E.path&&(["edit_file","patch_file","write_file"].includes(ke)&&R.startsWith("Edited:")?ee.add(E.path):ke==="read_file"&&!R.startsWith("ERROR")&&ee.delete(E.path)),{role:"tool",content:R.length>2e4?R.substring(0,2e4)+`
|
|
256
|
+
...(truncated)`:R,tool_call_id:P}}).catch(O=>(W&&(Xr(W),c.delete(W)),{role:"tool",content:`ERROR: ${O.message}`,tool_call_id:P}))}),Ne=await Promise.all(xe);if(S.push(...Ne),le>=7&&S.length>12)try{let{compressMessage:Ae}=en(),ke=S.length-6;for(let E=1;E<ke;E++)S[E]._subAgentCompressed||(S[E]={...Ae(S[E],"light"),_subAgentCompressed:!0})}catch{}for(let Ae=0;Ae<G.length;Ae++){let ke=G[Ae];if(ke.function.name==="bash_exec"){let E=Uy(ke.function.arguments);if((Ne[Ae]?.content||"").startsWith("ERROR")&&E&&E.command){let W=E.command.replace(/\s+/g," ").trim().slice(0,100);u.set(W,(u.get(W)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${le+1}/${s}`)}for(let le of c)Xr(le);let ue=[...u.entries()].filter(([,le])=>le>=3).sort((le,de)=>de[1]-le[1]).slice(0,3).map(([le,de])=>`"${le}" (failed ${de}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:ue,result:S[S.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}catch(ue){for(let le of c)Xr(le);return{task:t.task,status:"failed",result:`Error: ${ue.message}`,toolsUsed:i,tokensUsed:a,modelSpec:h&&g?`${h}:${g}`:null}}}async function nd(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?cR:lR,o=e===0?Ky:Xy,s=(t.agents||[]).slice(0,n);if(s.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=s.map(d=>ic(d)),c=s.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 aR(c);u.start();try{let d=s.map((g,y)=>{let w=a[y],x=Math.min(g.max_iterations||o,o),S=w.model?{...g,model:`${w.provider}:${w.model}`,_skipLog:!0,max_iterations:x}:{...g,_skipLog:!0,max_iterations:x};return s$(S,{onUpdate:()=>{}},e).then(k=>(u.update(y,k.status==="failed"?"error":"done"),k)).catch(k=>(u.update(y,"error"),{task:g.task,status:"failed",result:`Error: ${k.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),f=await Promise.all(d);u.stop(),ed();let p=["Sub-agent results:",""],m=0,h=0;for(let g=0;g<f.length;g++){let y=f[g],w=y.status==="done"?"\u2713":y.status==="truncated"?"\u26A0":"\u2717",x=y.modelSpec?` [${y.modelSpec}]`:"";p.push(`${w} Agent ${g+1}${x}: ${y.task}`),p.push(` Status: ${y.status}`),p.push(` Tools used: ${y.toolsUsed.length>0?y.toolsUsed.join(", "):"none"}`),p.push(` Result: ${y.result}`),y.repeatedFailures&&y.repeatedFailures.length>0&&p.push(` Repeated failures: ${y.repeatedFailures.join("; ")}`),p.push(""),m+=y.tokensUsed.input,h+=y.tokensUsed.output}return p.push(`Total sub-agent tokens: ${m} input + ${h} output`),p.join(`
|
|
257
257
|
`)}catch(d){return u.stop(),ed(),`ERROR: Sub-agent execution failed: ${d.message}`}}async function mR(t){let{createJob:e}=Vo(),n=(t.agents||[]).filter(i=>i.background),o=(t.agents||[]).filter(i=>!i.background),s=n.map(i=>{let a=ic(i),c=a.model?{...i,model:`${a.provider}:${a.model}`,_skipLog:!0}:{...i,_skipLog:!0};return e(c)}),r=[];if(s.length>0&&r.push(`Background agents started: [${s.join(", ")}]
|
|
258
258
|
`+n.map((i,a)=>` ${s[a]}: ${i.task}`).join(`
|
|
259
259
|
`)+`
|
|
260
260
|
Results will be injected into the conversation when each agent completes.`),o.length>0){let i=await nd({agents:o});r.push(i)}return r.join(`
|
|
261
261
|
|
|
262
|
-
`)||"No agents specified."}
|
|
263
|
-
`);for(let r of s){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=o[2]}return{frontmatter:e,body:n}}function
|
|
264
|
-
`);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let c of cc(a))e[c]=(e[c]||0)+3}for(let i of cc(o||t))e[i]=(e[i]||0)+1;return e}function ad(){let t=lc();if(!pt.existsSync(t))return{documents:{}};try{return JSON.parse(pt.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function cd(t){
|
|
262
|
+
`)||"No agents specified."}o$.exports={runSubAgent:s$,executeSpawnAgents:nd,executeSpawnAgentsBackground:mR,clearAllLocks:ed,classifyTask:t$,pickModelForTier:n$,resolveSubAgentModel:ic,classifyError:td,isRetryableError:Jy,callWithRetry:Zy,getExcludedTools:Qy,LOCK_TIMEOUT_MS:Vy,SUB_AGENT_TYPES:e$}});var Zr=X((v2,$$)=>{var pt=require("fs"),fs=require("path"),{atomicWrite:r$,withFileLockSync:i$}=os(),gR=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 Zo(){let t=fs.join(process.cwd(),".nex","brain");return pt.existsSync(t)||pt.mkdirSync(t,{recursive:!0}),t}function lc(){return fs.join(Zo(),".brain-index.json")}function rd(){return fs.join(Zo(),".embeddings.json")}function Vr(){let t=fs.join(process.cwd(),".nex","brain");if(!pt.existsSync(t))return[];try{return pt.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let n=fs.join(t,e),o=pt.statSync(n);return{name:e.replace(/\.md$/,""),path:n,size:o.size,modified:new Date(o.mtimeMs)}}).sort((e,n)=>n.modified-e.modified)}catch{return[]}}function Jr(t){let e={},n=t,o=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(o){let s=o[1].split(`
|
|
263
|
+
`);for(let r of s){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=o[2]}return{frontmatter:e,body:n}}function a$(t){let e=fs.join(Zo(),`${t}.md`);if(!pt.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=pt.readFileSync(e,"utf-8"),{frontmatter:o,body:s}=Jr(n);return{name:t,content:n,body:s,frontmatter:o}}function yR(t,e){let n=fs.join(Zo(),`${t}.md`);r$(n,e),bR(t,e),$R()}function $R(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=rd();pt.existsSync(t)&&setImmediate(async()=>{try{await h$()}catch{}})}function wR(t){let e=fs.join(Zo(),`${t}.md`);return pt.existsSync(e)?(pt.unlinkSync(e),_R(t),!0):!1}function cc(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!gR.has(e))}function id(t){let e={},{frontmatter:n,body:o}=Jr(t),s=Array.isArray(n.tags)?n.tags:[];for(let i of s){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(o||t).split(`
|
|
264
|
+
`);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let c of cc(a))e[c]=(e[c]||0)+3}for(let i of cc(o||t))e[i]=(e[i]||0)+1;return e}function ad(){let t=lc();if(!pt.existsSync(t))return{documents:{}};try{return JSON.parse(pt.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function cd(t){r$(lc(),JSON.stringify(t,null,2))}function bR(t,e){i$(lc(),()=>{let n=ad(),{frontmatter:o}=Jr(e),s=Array.isArray(o.tags)?o.tags:[];n.documents[t]={keywords:id(e),tags:s,modified:new Date().toISOString()},cd(n)})}function _R(t){i$(lc(),()=>{let e=ad();delete e.documents[t],cd(e)})}function od(){let t=Vr(),e={documents:{}};for(let n of t){let o=pt.readFileSync(n.path,"utf-8"),{frontmatter:s}=Jr(o),r=Array.isArray(s.tags)?s.tags:[];e.documents[n.name]={keywords:id(o),tags:r,modified:n.modified.toISOString()}}return cd(e),e}function c$(){let t=ad(),e=Vr();for(let n of e){let o=t.documents[n.name];if(!o||new Date(o.modified)<n.modified)return od()}for(let n of Object.keys(t.documents))if(!e.some(o=>o.name===n))return od();return t}function l$(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=cc(t);if(s.length===0)return[];let r=c$(),i=[];for(let[a,c]of Object.entries(r.documents)){let u=0;for(let d of s){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>=o&&i.push({name:a,score:u})}return i.sort((a,c)=>c.score-a.score),i.slice(0,n)}var u$=process.env.NEX_EMBED_MODEL||"nomic-embed-text",sd=400,xR=50;async function d$(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),n=require("https"),o=new URL(`${t}/api/tags`),s=o.protocol==="https:"?n:e;return((await new Promise((a,c)=>{let u=s.get(o.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(u$.split(":")[0]))}catch{return!1}}async function ld(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",n=require("http"),o=require("https"),s=new URL(`${e}/api/embeddings`),r=s.protocol==="https:"?o:n,i=JSON.stringify({model:u$,prompt:t});return new Promise((a,c)=>{let u=r.request(s,{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 f$(t,e){if(!t||!e||t.length!==e.length)return 0;let n=0,o=0,s=0;for(let i=0;i<t.length;i++)n+=t[i]*e[i],o+=t[i]*t[i],s+=e[i]*e[i];let r=Math.sqrt(o)*Math.sqrt(s);return r===0?0:n/r}function p$(t){let e=t.split(/\s+/),n=[],o=0;for(;o<e.length;){let s=e.slice(o,o+sd).join(" ");if(n.push({text:s,offset:o}),o+sd>=e.length)break;o+=sd-xR}return n}async function h$(){let t=Vr(),e={documents:{}},n=rd();if(pt.existsSync(n))try{e=JSON.parse(pt.readFileSync(n,"utf-8"))}catch{}for(let o of t){let s=e.documents[o.name];if(s&&new Date(s.modified)>=o.modified)continue;let r=pt.readFileSync(o.path,"utf-8"),i=p$(r),a=[];for(let c of i){let u=await ld(c.text);a.push({text:c.text,embedding:u,offset:c.offset})}e.documents[o.name]={chunks:a,modified:o.modified.toISOString()}}for(let o of Object.keys(e.documents))t.some(s=>s.name===o)||delete e.documents[o];return pt.writeFileSync(n,JSON.stringify(e),"utf-8"),e}async function m$(t,e={}){let{topK:n=3,minSimilarity:o=.3}=e,s=rd();if(!pt.existsSync(s))return[];let r;try{r=JSON.parse(pt.readFileSync(s,"utf-8"))}catch{return[]}let i=await ld(t),a=[];for(let[c,u]of Object.entries(r.documents||{})){let d=0,f="";for(let p of u.chunks||[]){let m=f$(i,p.embedding);m>d&&(d=m,f=p.text)}d>=o&&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:o=60,topK:s=3}=n,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,s)}async function y$(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=l$(t,{topK:n,minScore:o}),r=s;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await d$()){let a=await m$(t,{topK:n});r=g$(s,a,{topK:n})}}catch{}return r.map(i=>{let a=a$(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 Jo={queryKey:null,result:null,ts:0},vR=3e5;async function kR(t){if(!t||!t.trim())return"";let e=fs.join(process.cwd(),".nex","brain");if(!pt.existsSync(e)||Vr().length===0)return"";let o=t.trim().toLowerCase().slice(0,200);if(Jo.result!==null&&Jo.queryKey===o&&Date.now()-Jo.ts<vR)return Jo.result;let s;try{s=await y$(t,{topK:3})}catch{return""}if(!s||s.length===0)return"";let r;try{r=en().estimateTokens}catch{r=d=>Math.ceil(d.length/4)}let i=25e3,a=[],c=0;for(let d of s){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))+`
|
|
265
265
|
...(truncated)`}let m=typeof d.score=="number"?d.score.toFixed(2):String(d.score);if(a.push(`--- ${d.name} (relevance: ${m}) ---
|
|
266
266
|
${f}`),c+=r(f),c>=i)break}if(a.length===0)return Jo={queryKey:o,result:"",ts:Date.now()},"";let u=`KNOWLEDGE BASE (auto-selected):
|
|
267
267
|
|
|
268
268
|
${a.join(`
|
|
269
269
|
|
|
270
|
-
`)}`;return Jo={queryKey:o,result:u,ts:Date.now()},u}
|
|
270
|
+
`)}`;return Jo={queryKey:o,result:u,ts:Date.now()},u}$$.exports={getBrainDir:Zo,listDocuments:Vr,readDocument:a$,writeDocument:yR,removeDocument:wR,buildIndex:od,getIndex:c$,query:y$,getBrainContext:kR,isEmbeddingAvailable:d$,generateEmbedding:ld,buildEmbeddingIndex:h$,semanticQuery:m$,cosineSimilarity:f$,_keywordQuery:l$,_extractKeywords:id,_chunkText:p$,parseFrontmatter:Jr,tokenize:cc,_fuseResults:g$}});var Rn=X((k2,A$)=>{var nt=require("fs"),tn=require("path"),SR=require("os"),{atomicWrite:uc,withFileLockSync:w$}=os(),Qr=["user","feedback","project","reference"],ER=50;function so(){return tn.join(process.cwd(),".nex","memory")}function Qo(){return tn.join(so(),"memory.json")}function b$(){return tn.join(so(),"MEMORY.md")}function TR(){return tn.join(process.cwd(),"NEX.md")}function _$(){return tn.join(SR.homedir(),".nex","NEX.md")}function dc(){let t=so();nt.existsSync(t)||nt.mkdirSync(t,{recursive:!0})}function x$(t){let e=tn.join(so(),t);return nt.existsSync(e)||nt.mkdirSync(e,{recursive:!0}),e}function ei(){let t=Qo();if(!nt.existsSync(t))return{};try{return JSON.parse(nt.readFileSync(t,"utf-8"))}catch{return{}}}function v$(t){dc(),uc(Qo(),JSON.stringify(t,null,2))}function k$(){let t=Qo();if(!nt.existsSync(t))return;let e=ei(),n=Object.keys(e);if(n.length===0){try{nt.renameSync(t,t+".bak")}catch{}return}for(let o of n){let s=e[o],r=s.value||String(s),i=o.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=x$("project"),c=tn.join(a,`${i}.md`),u=r.split(`
|
|
271
271
|
`)[0].slice(0,100),d=`---
|
|
272
272
|
name: ${o}
|
|
273
273
|
description: ${u}
|
|
@@ -275,7 +275,7 @@ type: project
|
|
|
275
275
|
---
|
|
276
276
|
|
|
277
277
|
${r}
|
|
278
|
-
`;uc(c,d)}fc();try{nt.renameSync(t,t+".bak")}catch{}}function RR(t,e,n,o){if(!Qr.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Qr.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!n||typeof n!="string"||n.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!s)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=
|
|
278
|
+
`;uc(c,d)}fc();try{nt.renameSync(t,t+".bak")}catch{}}function RR(t,e,n,o){if(!Qr.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Qr.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!n||typeof n!="string"||n.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!s)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=x$(t),i=tn.join(r,`${s}.md`);if(nt.existsSync(i))try{if(ud(nt.readFileSync(i,"utf-8")).body.slice(0,200)===n.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=o||n.split(`
|
|
279
279
|
`)[0].slice(0,100),c=`---
|
|
280
280
|
name: ${e}
|
|
281
281
|
description: ${a}
|
|
@@ -283,11 +283,11 @@ type: ${t}
|
|
|
283
283
|
---
|
|
284
284
|
|
|
285
285
|
${n}
|
|
286
|
-
`;return uc(i,c),fc(),{ok:!0,path:i,updated:!0}}function CR(t,e){if(!Qr.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=tn.join(so(),t,`${n}.md`);if(!nt.existsSync(o))return!1;try{return nt.unlinkSync(o),fc(),!0}catch{return!1}}function ud(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let n=e[1],o=(e[2]||"").trim(),s=r=>{let i=n.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:s("name"),description:s("description"),type:s("type"),body:o}}function
|
|
286
|
+
`;return uc(i,c),fc(),{ok:!0,path:i,updated:!0}}function CR(t,e){if(!Qr.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=tn.join(so(),t,`${n}.md`);if(!nt.existsSync(o))return!1;try{return nt.unlinkSync(o),fc(),!0}catch{return!1}}function ud(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let n=e[1],o=(e[2]||"").trim(),s=r=>{let i=n.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:s("name"),description:s("description"),type:s("type"),body:o}}function S$(){let t=[],e=so();for(let n of Qr){let o=tn.join(e,n);if(!nt.existsSync(o))continue;let s;try{s=nt.readdirSync(o).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of s){let i=tn.join(o,r);try{let a=nt.readFileSync(i,"utf-8"),c=ud(a);t.push({type:n,name:c.name||tn.basename(r,".md"),description:c.description,filePath:i})}catch{}}}return t}function fc(){let t=S$(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=ER+2)break;let o=`${n.type}/${tn.basename(n.filePath)}`;e.push(`- [${n.name}](${o}) \u2014 ${n.description||"(no description)"}`)}dc(),uc(b$(),e.join(`
|
|
287
287
|
`)+`
|
|
288
|
-
`)}function
|
|
289
|
-
${e}`);let n=
|
|
290
|
-
${n}`);let o="",s=
|
|
288
|
+
`)}function E$(){let t=b$();if(!nt.existsSync(t))return"";try{return nt.readFileSync(t,"utf-8").trim()}catch{return""}}function AR(t,e){dc(),w$(Qo(),()=>{let n=ei();n[t]={value:e,updatedAt:new Date().toISOString()},v$(n)})}function OR(t){let e=ei();return e[t]?e[t].value:null}function MR(t){return dc(),w$(Qo(),()=>{let e=ei();return t in e?(delete e[t],v$(e),!0):!1})}function T$(){let t=ei();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function R$(){let t=_$();if(!nt.existsSync(t))return"";try{return nt.readFileSync(t,"utf-8").trim()}catch{return""}}function C$(){let t=TR();if(!nt.existsSync(t))return"";try{return nt.readFileSync(t,"utf-8").trim()}catch{return""}}function NR(){k$();let t=[],e=R$();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
289
|
+
${e}`);let n=C$();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
290
|
+
${n}`);let o="",s=E$();if(s)o=s;else{let f=T$();f.length>0&&(o=`PROJECT MEMORY:
|
|
291
291
|
${f.map(m=>` ${m.key}: ${m.value}`).join(`
|
|
292
292
|
`)}`)}let r=t.join(`
|
|
293
293
|
|
|
@@ -296,9 +296,9 @@ ${f.map(m=>` ${m.key}: ${m.value}`).join(`
|
|
|
296
296
|
`}o=p.trimEnd()+`
|
|
297
297
|
[Memory index truncated \u2014 use delete_memory to prune old entries]`}else o.length>u&&(o="");let d=[...t];return o&&d.push(o),d.length>0&&d.push(i),d.join(`
|
|
298
298
|
|
|
299
|
-
`)}
|
|
300
|
-
`;ti.appendFileSync(
|
|
301
|
-
`).filter(c=>c.trim());for(let c of a)try{let u=JSON.parse(c);if(t.tool&&u.tool!==t.tool)continue;o.push(u)}catch{}if(t.date)break}return o}function LR(t=1){let e=
|
|
299
|
+
`)}A$.exports={saveMemory:RR,deleteMemory:CR,scanMemories:S$,rebuildIndex:fc,loadMemoryIndex:E$,remember:AR,recall:OR,forget:MR,listMemories:T$,loadGlobalInstructions:R$,loadProjectInstructions:C$,getMemoryContext:NR,_getMemoryDir:so,_getMemoryFile:Qo,_getGlobalNexMdPath:_$,_parseMemoryFile:ud,_migrateIfNeeded:k$,VALID_TYPES:Qr}});var pd=X((S2,L$)=>{var ti=require("fs"),dd=require("path"),fd=process.env.NEX_AUDIT!=="false",oo=null;function O$(){return oo||(oo=dd.join(process.cwd(),".nex","audit"),ti.existsSync(oo)||ti.mkdirSync(oo,{recursive:!0}),oo)}function M$(){let t=new Date().toISOString().split("T")[0];return dd.join(O$(),`${t}.jsonl`)}function PR(t){if(fd)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:N$(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)+`
|
|
300
|
+
`;ti.appendFileSync(M$(),n,"utf-8")}catch{}}function N$(t){if(!t||typeof t!="object")return{};let e={};for(let[n,o]of Object.entries(t))/key|token|password|secret|credential/i.test(n)?e[n]="***":typeof o=="string"&&o.length>500?e[n]=o.substring(0,500)+`... (${o.length} chars)`:e[n]=o;return e}function P$(t={}){let e=O$(),n=t.days||1,o=[];for(let s=0;s<n;s++){let r=t.date||new Date(Date.now()-s*864e5).toISOString().split("T")[0],i=dd.join(e,`${r}.jsonl`);if(!ti.existsSync(i))continue;let a=ti.readFileSync(i,"utf-8").split(`
|
|
301
|
+
`).filter(c=>c.trim());for(let c of a)try{let u=JSON.parse(c);if(t.tool&&u.tool!==t.tool)continue;o.push(u)}catch{}if(t.date)break}return o}function LR(t=1){let e=P$({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let n={},o=0,s=0;for(let r of e)n[r.tool]=(n[r.tool]||0)+1,o+=r.duration||0,r.success&&s++;return{totalCalls:e.length,byTool:n,avgDuration:Math.round(o/e.length),successRate:s/e.length}}function IR(t){fd=t}function jR(){return fd}function DR(){oo=null}L$.exports={logToolExecution:PR,sanitizeArgs:N$,readAuditLog:P$,getAuditSummary:LR,setAuditEnabled:IR,isAuditEnabled:jR,getAuditLogPath:M$,_reset:DR}});var e0=X((T2,Q$)=>{var ht=require("fs").promises,An=require("fs"),he=require("path"),at=require("util").promisify(require("child_process").exec),ro=require("util").promisify(require("child_process").execFile),{spawnSync:qR}=require("child_process"),hd=require("axios"),{isForbidden:FR,isSSHForbidden:BR,isDangerous:UR,isCritical:I$,isBashPathForbidden:WR,confirm:Cn}=It(),{showDiff:pc,showNewFile:HR,showEditDiff:E2,confirmFileChange:ni}=Kh(),{C:we,Spinner:GR,getToolSpinnerText:YR}=He(),{ToolProgress:hc}=qs(),{isGitRepo:md,getCurrentBranch:j$,getStatus:zR,getDiff:KR}=vs(),{recordChange:mc}=rs(),{fuzzyFindText:D$,findMostSimilar:ai}=Rm(),{runDiagnostics:si}=qm(),{findFileInIndex:XR,getFileIndex:q$,searchContentIndex:VR,scorePathMatch:F$,refreshIndex:JR,isIndexValid:ZR}=Hn(),{resolveProfile:gn,sshExec:Bt,scpUpload:QR,scpDownload:B$}=cs(),{resolveDeployConfig:eC,loadDeployConfigs:tC}=Su(),{getEditMode:U$}=Ur(),nC=/^(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/,sC=/^ssh\s/,oC=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function nn(t){return ht.access(t).then(()=>!0).catch(()=>!1)}var gc=null,W$=0,rC=12e4;function iC(){let t=Date.now();if(gc&&t-W$<rC)return gc;let e=he.dirname(process.cwd());try{let n=An.readdirSync(e,{withFileTypes:!0}),o=he.basename(process.cwd()),s=n.filter(r=>r.isDirectory()&&r.name!==o&&!r.name.startsWith(".")).map(r=>r.name).sort();return gc=s.length>0?s:null,W$=t,gc}catch{return null}}function gd(t){if(t&&he.resolve(t)!==process.cwd())return"";let e=iC();if(!e)return"";let n=he.dirname(process.cwd());return`
|
|
302
302
|
Hint: no matches in current project. Sibling directories in ${n}/:
|
|
303
303
|
${e.join(", ")}
|
|
304
304
|
You can search there with: grep pattern --path ${n}/<dir>`}async function yc(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=St(e);if(n&&await nn(n))return{fixedPath:n,message:`(auto-fixed path: ${t} \u2192 ${e})`};let o=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],s=he.extname(t);if(!s)for(let i of o){let a=St(t+i);if(a&&await nn(a))return{fixedPath:a,message:`(auto-fixed: added ${i} extension)`}}if(s){let i=t.replace(/\.[^.]+$/,"");for(let a of o){if(a===s)continue;let c=St(i+a);if(c&&await nn(c))return{fixedPath:c,message:`(auto-fixed: ${s} \u2192 ${a})`}}}let r=he.basename(t);if(r&&r.length>2)try{let i=XR(r).map(a=>St(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${he.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
@@ -307,14 +307,14 @@ ${i.map(c=>he.relative(process.cwd(),c)).map(c=>` - ${c}`).join(`
|
|
|
307
307
|
${c.map(d=>he.relative(process.cwd(),d)).map(d=>` - ${d}`).join(`
|
|
308
308
|
`)}`}}catch{}try{let{smartSearch:i}=Hn(),a=i(t,{limit:5,minScore:15});if(a.length>0){let c=St(a[0].file);if(a[0].score>=200||a.length===1&&a[0].score>=50)return{fixedPath:c,message:`(auto-fixed: smart matched ${t} \u2192 ${he.relative(process.cwd(),c)})`};if(a.length>=2&&a[0].score>=80&&a[0].score>=a[1].score*1.5)return{fixedPath:c,message:`(auto-fixed: best match ${t} \u2192 ${he.relative(process.cwd(),c)})`};if(a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
309
309
|
${a.map(d=>he.relative(process.cwd(),St(d.file))).map(d=>` - ${d}`).join(`
|
|
310
|
-
`)}`}}}catch{}return{fixedPath:null,message:""}}function aC(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
|
|
310
|
+
`)}`}}}catch{}return{fixedPath:null,message:""}}function aC(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 z$(t){if(!t||typeof t!="string")return null;let e=t.trim();if(!e||/[()[\]{}|^$\\]/.test(e))return null;let n=e.replace(/\*\*/g," ").replace(/[*?]/g," ").replace(/[:=><!]+/g," ").replace(/\s+/g," ").trim();if(!n)return null;let o=n.split(/[\/\s,]+/).map(s=>s.trim()).filter(Boolean).filter(s=>s!=="."&&s!=="..").filter(s=>!/^\.[a-z0-9]+$/i.test(s)).filter(s=>s.length>=3);return o.length===0?null:(o.sort((s,r)=>r.length-s.length),o[0])}async function K$(t,e){let n=z$(t);if(!n)return new Map;try{let o=await VR(n,void 0,e||process.cwd()),s=new Map;for(let r of o){let a=r.name.toLowerCase()===n.toLowerCase()?140:90;s.set(r.file,(s.get(r.file)||0)+a)}return s}catch{return new Map}}function H$(t,e){if(!t)return"";let n=e||process.cwd(),o=he.isAbsolute(t)?t:he.resolve(n,t),s=he.relative(n,o);return s&&!s.startsWith("..")&&!he.isAbsolute(s)?s:he.relative(process.cwd(),o)}function oi(t,e){let n=(t||"").trim();return n?e==="files_with_matches"||e==="count"?n.split(`
|
|
311
311
|
`).filter(o=>o.trim()):n.split(`
|
|
312
|
-
`).filter(o=>o.trim()):[]}function
|
|
312
|
+
`).filter(o=>o.trim()):[]}function X$(t,{query:e,basePath:n,definitionScores:o=new Map,mtimeByPath:s=new Map}={}){let r=z$(e);return[...t].sort((i,a)=>{let c=H$(i,n),u=H$(a,n),d=0,f=0;if(r&&(d+=F$(c,r),f+=F$(u,r)),d+=o.get(c)||0,f+=o.get(u)||0,d!==f)return f-d;let p=s.get(i)||0,m=s.get(a)||0;return p!==m?m-p:c.localeCompare(u)})}async function yd(t,{query:e,basePath:n,outputMode:o}={}){if(!Array.isArray(t)||t.length<=1)return t;let s=new Map,r=[];for(let u of t){if(!u)continue;let d=u;(o==="count"||o!=="files_with_matches")&&(d=u.split(":")[0]),s.has(d)||(s.set(d,[]),r.push(d)),s.get(d).push(u)}let i=await K$(e,n),a=X$(r,{query:e,basePath:n,definitionScores:i}),c=[];for(let u of a)c.push(...s.get(u)||[]);return c}function V$(t,e){let n=[];if(/command not found|: not found|not recognized/i.test(t)){let o=e.match(/^(\S+)/),s=o?o[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(s)?n.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(s)?n.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):n.push(`HINT: "${s}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let o=t.match(/Cannot find module '([^']+)'/),s=o?o[1]:"";s&&!s.startsWith(".")&&!s.startsWith("/")?n.push(`HINT: Missing npm package "${s}". Run: npm install ${s}`):n.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&n.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let o=t.match(/port (\d+)|:(\d+)/),s=o?o[1]||o[2]:"";n.push(`HINT: Port ${s||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&n.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&n.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&n.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&n.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let o=t.match(/curl:\s*\((\d+)\)/),s=o?parseInt(o[1],10):null;s===6||/Could not resolve host/i.test(t)?n.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):s===7||/Failed to connect|Connection refused/i.test(t)?n.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):s===22||/HTTP error/i.test(t)?n.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):s===28||/timed out/i.test(t)?n.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(s===35||/SSL.*error/i.test(t))&&n.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let o=t.match(/port (\d+)/),s=o?o[1]:"";n.push(`HINT: SSH remote port forwarding failed for port ${s}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${s}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&n.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&n.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&n.push("HINT: The working directory was deleted during this session \u2014 bash cannot execute commands in a non-existent cwd. Previous rm/delete commands succeeded. Use list_directory or glob to verify the state instead of retrying bash."),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&n.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),n.length===0?t:t+`
|
|
313
313
|
|
|
314
314
|
`+n.join(`
|
|
315
|
-
`)}function V$(t,e,n){let o=ai(t,e);if(!o)return null;let s=Math.max(2,Math.ceil(e.length*.03));return o.distance>s?null:{autoFixed:!0,matchText:o.text,content:t.split(o.text).join(n),distance:o.distance,line:o.line}}var H$=!1,io=null;function cC(){io&&(io(),io=null)}var _d=null;function lC(t){_d=t}async function $d(){if(!H$){H$=!0;try{let{stdout:t}=await it("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await it('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await it("git stash pop",{cwd:process.cwd(),timeout:1e4}),await it("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var uC=[/\.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 dC(){let t=process.cwd();try{return An.realpathSync(t)}catch{return he.resolve(t)}}function fC(t,e){let n=he.relative(e,t);return n===""||!n.startsWith("..")&&!he.isAbsolute(n)}function pC(t){if(An.existsSync(t))return An.realpathSync(t);let e=he.dirname(t);for(;e&&e!==he.dirname(e);){if(An.existsSync(e)){let n=An.realpathSync(e),o=he.relative(e,t);return he.resolve(n,o)}e=he.dirname(e)}return t}function St(t){let e=he.isAbsolute(t)?he.resolve(t):he.resolve(process.cwd(),t);for(let o of uC)if(o.test(e))return null;let n=pC(e);return fC(n,dC())?n:null}function Be(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function J$(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function hC(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function mC(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function wd(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function gC(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function ri(t,e="user"){return J$(t)?null:`ERROR: ${e} contains unsafe characters`}function bd(t,e="service"){return hC(t)?null:`ERROR: ${e} contains unsafe characters`}var yC=[{type:"function",function:{name:"bash",description:`Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. Example: use bash for "npm install" or "git status", but NOT for "cat config.json" (use read_file instead) or "grep -r 'error' src/" (use grep tool instead). AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.`,parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. ALWAYS read a file before editing it to ensure exact content matching \u2014 edit_file requires the EXACT text including whitespace and newlines. Example: read_file path=src/app.js line_start=10 line_end=20. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Concrete example: read_file(path='src/app.js', line_start=10, line_end=20) reads lines 10-20 of src/app.js. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding. IMPORTANT: If you need more than 350 lines, specify line_start and line_end explicitly \u2014 omitting them will truncate the output.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. Example: use write_file for creating a new config file like .env.example, but NOT for changing one line in an existing file (use edit_file instead). For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. ALWAYS call read_file first to get the exact content \u2014 edit_file requires the EXACT text including whitespace, indentation, and newlines. Example: edit_file(path='src/config.js', old_text='debug: false', new_text='debug: true'). IMPORTANT: old_text must match byte-for-byte \u2014 even a single space or newline difference will cause failure. If the edit fails with 'old_text not found', re-read that region with line_start/line_end then retry. For multiple replacements in one file, prefer patch_file (atomic). For new files, use write_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. Example: use list_directory to see the overall layout of the src/ directory, but NOT for finding all .js files (use glob instead). For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. Example: use search_files for finding all occurrences of 'error' in .js files, but NOT for finding all .js files (use glob instead). For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern by name or extension. Returns paths sorted by modification time. ALWAYS use this to locate files BEFORE reading them \u2014 never guess file paths. Example: glob(pattern='src/**/*.test.js') finds all test files in src directory. DO NOT use for content search (e.g. finding 'error' in files) \u2014 use grep tool instead. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to get the exact path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file CONTENTS with regex \u2014 use this when you need to find text inside files. Example: grep(pattern='callStream') finds files containing the text 'callStream'. Do NOT use glob for this \u2014 glob finds files by NAME pattern, grep searches file CONTENTS. Use output_mode='files_with_matches' for just file paths, output_mode='content' (default) for matching lines. Optionally use include to filter by file type (e.g. '*.js') but OMIT it when first searching \u2014 code may live in .html, .vue, .py or other unexpected file types. Supports context lines, offset pagination, and multiline patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Example: when changing 3 different variables in the same function, use patch_file with an array of 3 { old_text, new_text } objects instead of 3 separate edit_file calls. This ensures either all changes are applied or none are, preventing partial edits. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"visual_review",description:"Screenshot a URL, analyze the visual result, and return structured feedback about layout, design, and usability issues. Use this to visually inspect web pages, check CSS changes, or verify UI fixes. Returns the screenshot path + analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot and analyze"},focus:{type:"string",description:"What to focus on: layout, colors, typography, spacing, responsiveness, accessibility, or a custom description (e.g. 'check the navbar alignment')"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"},full_page:{type:"boolean",description:"Capture full scrollable page (default: false)"},compare_with:{type:"string",description:"Path to a previous screenshot to compare against (optional). Enables before/after analysis."}},required:["url"]}}},{type:"function",function:{name:"clipboard_image",description:"Grab the current image from the system clipboard (macOS). Returns the screenshot path for visual analysis. Use when the user says 'clipboard', 'pasteboard', or wants to analyze a copied screenshot.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"visual_diff",description:"Compare two screenshots pixel-by-pixel and compute a visual diff. Returns the percentage of changed pixels and which screen regions (top-left, center, bottom-right, etc.) were affected. Use after making CSS/HTML changes to quantify what changed. Example: take a before screenshot, make changes, take an after screenshot, then visual_diff both paths.",parameters:{type:"object",properties:{before:{type:"string",description:"Path to the 'before' screenshot (PNG)"},after:{type:"string",description:"Path to the 'after' screenshot (PNG)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1). Lower = more sensitive."}},required:["before","after"]}}},{type:"function",function:{name:"responsive_sweep",description:"Screenshot a URL at 5 viewport widths (320, 768, 1024, 1440, 1920) and return all screenshots for breakpoint analysis. Quickly identifies responsive layout issues across mobile, tablet, and desktop. Returns images for visual analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot at each viewport"},viewports:{type:"array",items:{type:"object",properties:{width:{type:"number"},label:{type:"string"}}},description:"Custom viewport list (default: 320/768/1024/1440/1920)"},full_page:{type:"boolean",description:"Capture full scrollable page at each viewport (default: false)"}},required:["url"]}}},{type:"function",function:{name:"visual_annotate",description:"Draw annotations (red boxes, arrows, circles) directly on a screenshot to mark problem areas. Returns the annotated image. Use instead of describing locations verbally \u2014 visual markers are unambiguous.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to the screenshot (PNG) to annotate"},annotations:{type:"array",items:{type:"object",properties:{type:{type:"string",description:"box, arrow, or circle"},x:{type:"number",description:"X position (px)"},y:{type:"number",description:"Y position (px)"},width:{type:"number",description:"Width for box (px)"},height:{type:"number",description:"Height for box (px)"},toX:{type:"number",description:"Arrow end X (px)"},toY:{type:"number",description:"Arrow end Y (px)"},radius:{type:"number",description:"Circle radius (px)"},label:{type:"string",description:"Text label for the annotation"},color:{type:"string",description:"Hex color (default: #FF0000)"}},required:["type","x","y"]},description:"List of annotations to draw"}},required:["image","annotations"]}}},{type:"function",function:{name:"visual_watch",description:"Hot-reload visual feedback loop: watches source files for changes, waits for HMR to settle, takes a new screenshot, diffs it against the previous one, and reports what changed. Runs up to N iterations (default: 10). Requires a running dev server (Vite, Next, etc.) and chokidar. Use for autonomous visual polish loops.",parameters:{type:"object",properties:{url:{type:"string",description:"Dev server URL to screenshot (e.g. http://localhost:5173)"},watch:{type:"array",items:{type:"string"},description:"File paths or directories to watch for changes (e.g. ['src/components', 'src/styles'])"},max_iterations:{type:"number",description:"Max number of change\u2192screenshot\u2192diff cycles (default: 10)"},hmr_delay:{type:"number",description:"Milliseconds to wait after file change for HMR to settle (default: 1500)"}},required:["url","watch"]}}},{type:"function",function:{name:"design_tokens",description:"Extract design tokens from a screenshot: dominant colors (with hex/rgb/frequency/category), detected vertical spacing values, and image dimensions. Use to audit visual consistency, compare against a design system, or reverse-engineer CSS variables from a rendered page.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to screenshot (PNG) to analyze"},sample_rate:{type:"number",description:"Pixel sampling interval \u2014 lower = more accurate but slower (default: 4)"}},required:["image"]}}},{type:"function",function:{name:"design_compare",description:"Compare a live web page against a reference design (Figma export, mockup PNG). Screenshots the URL at the reference image's dimensions, computes pixel-level diff, and returns annotated images highlighting deviations. Use to verify implementation matches the design spec.",parameters:{type:"object",properties:{url:{type:"string",description:"Live URL to compare against the reference"},reference:{type:"string",description:"Path to reference design image (PNG)"},width:{type:"number",description:"Override viewport width (default: match reference image width)"},height:{type:"number",description:"Override viewport height (default: 800)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1)"}},required:["url","reference"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'},background:{type:"boolean",description:"Run this agent non-blocking in the background. The main session continues immediately; results are injected as [BACKGROUND AGENT COMPLETED] user messages when the agent finishes. Use for tasks that can run in parallel to your main work."}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl) that live on almalinux9. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/deploy/app). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt (package_action: check|list|install|remove|update|upgrade); user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "my-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "my-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function ii(t,{server:e,context:n}={}){let o=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,s=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(s&&(r+=` --context ${s}`),r+=` ${t}`,o){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${o} "${i}"`}return r}async function G$(t,e,n={}){switch(t){case"bash":{let o=e.command,s=FR(o);if(s){let f=aC(o);return`BLOCKED: Command matches forbidden pattern: ${s}${f?`
|
|
315
|
+
`)}function J$(t,e,n){let o=ai(t,e);if(!o)return null;let s=Math.max(2,Math.ceil(e.length*.03));return o.distance>s?null:{autoFixed:!0,matchText:o.text,content:t.split(o.text).join(n),distance:o.distance,line:o.line}}var G$=!1,io=null;function cC(){io&&(io(),io=null)}var _d=null;function lC(t){_d=t}async function $d(){if(!G$){G$=!0;try{let{stdout:t}=await at("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await at('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await at("git stash pop",{cwd:process.cwd(),timeout:1e4}),await at("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var uC=[/\.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 dC(){let t=process.cwd();try{return An.realpathSync(t)}catch{return he.resolve(t)}}function fC(t,e){let n=he.relative(e,t);return n===""||!n.startsWith("..")&&!he.isAbsolute(n)}function pC(t){if(An.existsSync(t))return An.realpathSync(t);let e=he.dirname(t);for(;e&&e!==he.dirname(e);){if(An.existsSync(e)){let n=An.realpathSync(e),o=he.relative(e,t);return he.resolve(n,o)}e=he.dirname(e)}return t}function St(t){let e=he.isAbsolute(t)?he.resolve(t):he.resolve(process.cwd(),t);for(let o of uC)if(o.test(e))return null;let n=pC(e);return fC(n,dC())?n:null}function Be(t){return`'${String(t).replace(/'/g,"'\\''")}'`}function Z$(t){return typeof t=="string"&&/^[a-z_][a-z0-9_-]{0,31}\$?$/i.test(t)}function hC(t){return typeof t=="string"&&/^[a-zA-Z0-9@_.:-]+(?:\.service)?$/.test(t)}function mC(t){return typeof t=="string"&&/^[a-zA-Z0-9+_.:@/-]+$/.test(t)}function wd(t){return typeof t=="string"&&/^\d{1,5}(?:\/(?:tcp|udp))?$/i.test(t)}function gC(t){return typeof t=="string"&&/^(?:SIG[A-Z0-9]+|[A-Z0-9]+|\d{1,2})$/.test(t)}function ri(t,e="user"){return Z$(t)?null:`ERROR: ${e} contains unsafe characters`}function bd(t,e="service"){return hC(t)?null:`ERROR: ${e} contains unsafe characters`}var yC=[{type:"function",function:{name:"bash",description:`Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. Example: use bash for "npm install" or "git status", but NOT for "cat config.json" (use read_file instead) or "grep -r 'error' src/" (use grep tool instead). AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.`,parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. ALWAYS read a file before editing it to ensure exact content matching \u2014 edit_file requires the EXACT text including whitespace and newlines. Example: read_file path=src/app.js line_start=10 line_end=20. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Concrete example: read_file(path='src/app.js', line_start=10, line_end=20) reads lines 10-20 of src/app.js. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding. IMPORTANT: If you need more than 350 lines, specify line_start and line_end explicitly \u2014 omitting them will truncate the output.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. Example: use write_file for creating a new config file like .env.example, but NOT for changing one line in an existing file (use edit_file instead). For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. ALWAYS call read_file first to get the exact content \u2014 edit_file requires the EXACT text including whitespace, indentation, and newlines. Example: edit_file(path='src/config.js', old_text='debug: false', new_text='debug: true'). IMPORTANT: old_text must match byte-for-byte \u2014 even a single space or newline difference will cause failure. If the edit fails with 'old_text not found', re-read that region with line_start/line_end then retry. For multiple replacements in one file, prefer patch_file (atomic). For new files, use write_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. Example: use list_directory to see the overall layout of the src/ directory, but NOT for finding all .js files (use glob instead). For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. Example: use search_files for finding all occurrences of 'error' in .js files, but NOT for finding all .js files (use glob instead). For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern by name or extension. Returns paths sorted by modification time. ALWAYS use this to locate files BEFORE reading them \u2014 never guess file paths. Example: glob(pattern='src/**/*.test.js') finds all test files in src directory. DO NOT use for content search (e.g. finding 'error' in files) \u2014 use grep tool instead. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to get the exact path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file CONTENTS with regex \u2014 use this when you need to find text inside files. Example: grep(pattern='callStream') finds files containing the text 'callStream'. Do NOT use glob for this \u2014 glob finds files by NAME pattern, grep searches file CONTENTS. Use output_mode='files_with_matches' for just file paths, output_mode='content' (default) for matching lines. Optionally use include to filter by file type (e.g. '*.js') but OMIT it when first searching \u2014 code may live in .html, .vue, .py or other unexpected file types. Supports context lines, offset pagination, and multiline patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Example: when changing 3 different variables in the same function, use patch_file with an array of 3 { old_text, new_text } objects instead of 3 separate edit_file calls. This ensures either all changes are applied or none are, preventing partial edits. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"visual_review",description:"Screenshot a URL, analyze the visual result, and return structured feedback about layout, design, and usability issues. Use this to visually inspect web pages, check CSS changes, or verify UI fixes. Returns the screenshot path + analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot and analyze"},focus:{type:"string",description:"What to focus on: layout, colors, typography, spacing, responsiveness, accessibility, or a custom description (e.g. 'check the navbar alignment')"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"},full_page:{type:"boolean",description:"Capture full scrollable page (default: false)"},compare_with:{type:"string",description:"Path to a previous screenshot to compare against (optional). Enables before/after analysis."}},required:["url"]}}},{type:"function",function:{name:"clipboard_image",description:"Grab the current image from the system clipboard (macOS). Returns the screenshot path for visual analysis. Use when the user says 'clipboard', 'pasteboard', or wants to analyze a copied screenshot.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"visual_diff",description:"Compare two screenshots pixel-by-pixel and compute a visual diff. Returns the percentage of changed pixels and which screen regions (top-left, center, bottom-right, etc.) were affected. Use after making CSS/HTML changes to quantify what changed. Example: take a before screenshot, make changes, take an after screenshot, then visual_diff both paths.",parameters:{type:"object",properties:{before:{type:"string",description:"Path to the 'before' screenshot (PNG)"},after:{type:"string",description:"Path to the 'after' screenshot (PNG)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1). Lower = more sensitive."}},required:["before","after"]}}},{type:"function",function:{name:"responsive_sweep",description:"Screenshot a URL at 5 viewport widths (320, 768, 1024, 1440, 1920) and return all screenshots for breakpoint analysis. Quickly identifies responsive layout issues across mobile, tablet, and desktop. Returns images for visual analysis.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot at each viewport"},viewports:{type:"array",items:{type:"object",properties:{width:{type:"number"},label:{type:"string"}}},description:"Custom viewport list (default: 320/768/1024/1440/1920)"},full_page:{type:"boolean",description:"Capture full scrollable page at each viewport (default: false)"}},required:["url"]}}},{type:"function",function:{name:"visual_annotate",description:"Draw annotations (red boxes, arrows, circles) directly on a screenshot to mark problem areas. Returns the annotated image. Use instead of describing locations verbally \u2014 visual markers are unambiguous.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to the screenshot (PNG) to annotate"},annotations:{type:"array",items:{type:"object",properties:{type:{type:"string",description:"box, arrow, or circle"},x:{type:"number",description:"X position (px)"},y:{type:"number",description:"Y position (px)"},width:{type:"number",description:"Width for box (px)"},height:{type:"number",description:"Height for box (px)"},toX:{type:"number",description:"Arrow end X (px)"},toY:{type:"number",description:"Arrow end Y (px)"},radius:{type:"number",description:"Circle radius (px)"},label:{type:"string",description:"Text label for the annotation"},color:{type:"string",description:"Hex color (default: #FF0000)"}},required:["type","x","y"]},description:"List of annotations to draw"}},required:["image","annotations"]}}},{type:"function",function:{name:"visual_watch",description:"Hot-reload visual feedback loop: watches source files for changes, waits for HMR to settle, takes a new screenshot, diffs it against the previous one, and reports what changed. Runs up to N iterations (default: 10). Requires a running dev server (Vite, Next, etc.) and chokidar. Use for autonomous visual polish loops.",parameters:{type:"object",properties:{url:{type:"string",description:"Dev server URL to screenshot (e.g. http://localhost:5173)"},watch:{type:"array",items:{type:"string"},description:"File paths or directories to watch for changes (e.g. ['src/components', 'src/styles'])"},max_iterations:{type:"number",description:"Max number of change\u2192screenshot\u2192diff cycles (default: 10)"},hmr_delay:{type:"number",description:"Milliseconds to wait after file change for HMR to settle (default: 1500)"}},required:["url","watch"]}}},{type:"function",function:{name:"design_tokens",description:"Extract design tokens from a screenshot: dominant colors (with hex/rgb/frequency/category), detected vertical spacing values, and image dimensions. Use to audit visual consistency, compare against a design system, or reverse-engineer CSS variables from a rendered page.",parameters:{type:"object",properties:{image:{type:"string",description:"Path to screenshot (PNG) to analyze"},sample_rate:{type:"number",description:"Pixel sampling interval \u2014 lower = more accurate but slower (default: 4)"}},required:["image"]}}},{type:"function",function:{name:"design_compare",description:"Compare a live web page against a reference design (Figma export, mockup PNG). Screenshots the URL at the reference image's dimensions, computes pixel-level diff, and returns annotated images highlighting deviations. Use to verify implementation matches the design spec.",parameters:{type:"object",properties:{url:{type:"string",description:"Live URL to compare against the reference"},reference:{type:"string",description:"Path to reference design image (PNG)"},width:{type:"number",description:"Override viewport width (default: match reference image width)"},height:{type:"number",description:"Override viewport height (default: 800)"},threshold:{type:"number",description:"Color distance threshold 0-1 (default: 0.1)"}},required:["url","reference"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'},background:{type:"boolean",description:"Run this agent non-blocking in the background. The main session continues immediately; results are injected as [BACKGROUND AGENT COMPLETED] user messages when the agent finishes. Use for tasks that can run in parallel to your main work."}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl) that live on almalinux9. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/deploy/app). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt (package_action: check|list|install|remove|update|upgrade); user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "my-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "my-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function ii(t,{server:e,context:n}={}){let o=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,s=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(s&&(r+=` --context ${s}`),r+=` ${t}`,o){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${o} "${i}"`}return r}async function Y$(t,e,n={}){switch(t){case"bash":{let o=e.command,s=FR(o);if(s){let f=aC(o);return`BLOCKED: Command matches forbidden pattern: ${s}${f?`
|
|
316
316
|
HINT: ${f}`:""}`}let r=WR(o);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
|
|
317
|
-
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?
|
|
317
|
+
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?I$(o):UR(o)){let f=I$(o)?"\u26D4":"\u26A0";if(!await Cn(` ${f} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),An.accessSync(a)}catch{a=require("os").homedir(),n.silent||console.log(`${we.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${we.reset}`)}let c=sC.test(o.trim())&&!oC.test(o.trim());if(nC.test(o.trim())||c){n.silent||console.log(`${we.dim} \u25B6 interactive: ${o}${we.reset}`);let f=qR("sh",["-c",o],{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}=qs(),d=n.silent?null:new u("bash",`$ ${o.substring(0,72)}`);d&&d.start();try{let{stdout:f,stderr:p}=await at(o,{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=V$(p,o);return`EXIT ${f.code||1}
|
|
318
318
|
${m}`}}case"read_file":{let o=new hc("read_file","Reading file...");o.start();try{let s=St(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await nn(s)){let ee=await yc(e.path);if(ee.fixedPath)s=ee.fixedPath,console.log(`${we.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${he.relative(process.cwd(),s)}${we.reset}`),o.update({message:"Resolved path",detail:he.relative(process.cwd(),s)});else return`ERROR: File not found: ${e.path}${ee.message?`
|
|
319
319
|
`+ee.message:""}`}let i=he.relative(process.cwd(),s);o.update({message:"Scanning",detail:i});let a=Buffer.alloc(8192),c=await An.promises.open(s,"r"),{bytesRead:u}=await c.read(a,0,8192,0);await c.close();for(let ee=0;ee<u;ee++)if(a[ee]===0)return`ERROR: ${s} is a binary file (not readable as text)`;let d=await ht.readFile(s,"utf-8");if(!d&&(await ht.stat(s)).size>0)return`WARNING: ${s} is empty or unreadable`;let f=d.split(`
|
|
320
320
|
`),p=await ht.stat(s),m=f.length,h=350,g=!e.line_start&&!e.line_end,y=g&&m>h,w=(e.line_start||1)-1,x=y?h:e.line_end||f.length,S=w+1,k=x;o.update({count:Math.max(0,x-w),total:m,detail:`${i} lines ${S}-${k}`,message:y?"Reading excerpt":"Reading"});let v=y?`showing lines 1-${h} of ${m}`:e.line_start||e.line_end?`lines ${w+1}-${x} of ${m}`:`${m} lines`,C=`File: ${i} (${v}, ${p.size} bytes)`,q=f.slice(w,x).map((ee,ue)=>`${w+ue+1}: ${ee}`).join(`
|
|
@@ -326,9 +326,9 @@ ${m}`}}case"read_file":{let o=new hc("read_file","Reading file...");o.start();tr
|
|
|
326
326
|
${q}${D}`}finally{o.stop()}}case"write_file":{let o=new hc("write_file","Preparing write...");o.start();try{await $d();let s=St(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let r=await nn(s),i=null,a=String(e.content||"").split(`
|
|
327
327
|
`).length;if(o.update({count:a,detail:`${he.relative(process.cwd(),s)} ${a} lines`,message:r?"Overwriting":"Creating"}),n.autoConfirm)r&&(i=await ht.readFile(s,"utf-8"));else if(r){i=await ht.readFile(s,"utf-8");let p=await si(s,e.content);if(pc(s,i,e.content,{annotations:p}),!await ni("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let p=await si(s,e.content);if(HR(s,e.content,{annotations:p}),!await ni("Create"))return"CANCELLED: User declined to create file."}let c=he.dirname(s);await nn(c)||await ht.mkdir(c,{recursive:!0}),o.update({message:"Writing",detail:`${he.relative(process.cwd(),s)} ${a} lines`}),await ht.writeFile(s,e.content,"utf-8");let d=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||e.content.startsWith("#!");d&&(o.update({message:"Chmod",detail:he.relative(process.cwd(),s)}),await ht.chmod(s,493)),mc("write_file",s,i,e.content);let f=d?" [chmod +x applied]":"";return`Written: ${s} (${e.content.length} chars)${f}`}finally{o.stop()}}case"edit_file":{let o=new hc("edit_file","Preparing edit...");o.start();try{await $d();let s=St(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await nn(s)){let f=await yc(e.path);if(f.fixedPath)s=f.fixedPath,console.log(`${we.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${he.relative(process.cwd(),s)}${we.reset}`);else return`ERROR: File not found: ${e.path}${f.message?`
|
|
328
328
|
`+f.message:""}`}o.update({message:"Loading",detail:he.relative(process.cwd(),s)});let i=await ht.readFile(s,"utf-8"),a=e.old_text,c=!1,u=!1;if(!i.includes(e.old_text)){o.update({message:"Matching target",detail:`${he.relative(process.cwd(),s)} ${String(e.old_text||"").trim().split(`
|
|
329
|
-
`)[0].slice(0,40)}`});let{getActiveModelId:f,getActiveProviderName:p}=Xe();if(
|
|
329
|
+
`)[0].slice(0,40)}`});let{getActiveModelId:f,getActiveProviderName:p}=Xe();if(U$(f(),p())==="strict"){let g=ai(i,e.old_text);return g?`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)
|
|
330
330
|
Most similar text (line ${g.line}, distance ${g.distance}):
|
|
331
|
-
${g.text}`:`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)`}let h=
|
|
331
|
+
${g.text}`:`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)`}let h=D$(i,e.old_text);if(h)a=h,c=!0,o.update({message:"Matched target",detail:`${he.relative(process.cwd(),s)} whitespace-normalized`}),console.log(`${we.dim} \u2713 fuzzy whitespace match applied${we.reset}`);else{let g=J$(i,e.old_text,e.new_text);if(g){if(!n.autoConfirm){let k=await si(s,g.content);if(pc(s,i,g.content,{annotations:k}),!await ni(`Apply (auto-fix, line ${g.line}, distance ${g.distance})`))return"CANCELLED: User declined to apply edit."}await ht.writeFile(s,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||g.content.startsWith("#!"))&&await ht.chmod(s,493),mc("edit_file",s,i,g.content);let S=g.matchText.length>80?g.matchText.substring(0,77)+"...":g.matchText;return console.log(`${we.dim} \u2713 auto-fixed edit: line ${g.line}, distance ${g.distance}${we.reset}`),`Edited: ${s} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${S}")`}let y=ai(i,e.old_text);if(y){let S=i.split(`
|
|
332
332
|
`),k=Math.max(0,y.line-6),v=Math.min(S.length,y.line+10),C=S.slice(k,v).map((D,ee)=>`${k+ee+1}: ${D}`).join(`
|
|
333
333
|
`),q=`line_start=${Math.max(1,y.line-5)} line_end=${Math.min(S.length,y.line+15)}`;return`ERROR: old_text not found in ${s} (most similar at line ${y.line}, distance ${y.distance})
|
|
334
334
|
|
|
@@ -342,16 +342,16 @@ Recovery: use grep -n to locate the text, then re-read that section with line_st
|
|
|
342
342
|
`)[0].slice(0,40)}`});let f=i.split(a).join(e.new_text),p=await si(s,f);if(pc(s,i,f,{annotations:p}),!await ni(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let d=i.split(a).join(e.new_text);return o.update({message:"Applying edit",detail:`${he.relative(process.cwd(),s)} ${String(e.new_text||"").trim().split(`
|
|
343
343
|
`)[0].slice(0,40)}`}),await ht.writeFile(s,d,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||d.startsWith("#!"))&&(o.update({message:"Chmod",detail:he.relative(process.cwd(),s)}),await ht.chmod(s,493)),mc("edit_file",s,i,d),c?`Edited: ${s} (fuzzy match)`:`Edited: ${s}`}finally{o.stop()}}case"list_directory":{let o=St(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await nn(o)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=St(u),f=await nn(d);if(d&&f)o=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 ht.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(he.join(u,m.name),d+1,f+" ")}};return await c(o,1,""),a.join(`
|
|
344
344
|
`)||"(empty)"}case"search_files":{let o=St(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=["-rn","-H"];e.file_pattern&&s.push(`--include=${e.file_pattern}`),s.push(e.pattern,o);try{let{stdout:r}=await ro("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=oi(r).slice(0,50);return(await yd(i,{query:e.pattern,basePath:o})).join(`
|
|
345
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?St(e.path):s,i=e.pattern,a=v=>{let C=v.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${C}$`)},c=a(i),u=i.split("/").pop(),d=a(u),{ToolProgress:f}=qs(),p=new f("glob","Finding files...");p.start();let m=
|
|
345
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?St(e.path):s,i=e.pattern,a=v=>{let C=v.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${C}$`)},c=a(i),u=i.split("/").pop(),d=a(u),{ToolProgress:f}=qs(),p=new f("glob","Finding files...");p.start();let m=q$();ZR(r)||(await JR(r),m=q$());let h=m.filter(v=>c.test(v)||d.test(he.basename(v))).map(v=>he.join(r,v));if(h.length===0)return p.stop(),"(no matches)"+gd(e.path);let g=await Promise.all(h.slice(0,210).map(async v=>{try{let C=await ht.stat(v);return{path:v,mtime:C.mtimeMs}}catch{return{path:v,mtime:0}}})),y=new Map(g.map(v=>[v.path,v.mtime])),w=await K$(i,r),x=X$(g.map(v=>v.path),{query:i,basePath:r,definitionScores:w,mtimeByPath:y}),S=h.length>200,k=x.slice(0,200).join(`
|
|
346
346
|
`);return p.update({count:h.length,detail:e.pattern}),p.stop(),S?`${k}
|
|
347
347
|
|
|
348
348
|
\u26A0 Results truncated at 200. Use a more specific pattern.`:k}case"grep":{let o=e.path?St(e.path):process.cwd();if(e.staged){let{getDiff:c}=vs(),u=await c(!0);if(!u.trim())return"(no staged changes)";let d=new Set,f=u.split(`
|
|
349
349
|
`);for(let y of f)if(y.startsWith("diff --git")){let w=y.match(/diff --git a\/(.+) b\/(.+)/);w&&d.add(w[2])}let p=["-rn","-E","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&p.push("-i"),e.include&&p.push(`--include=${e.include}`),e.type&&p.push(`--include=*.${e.type}`),e.context?p.push("-C",String(e.context)):(e.before_context&&p.push("-B",String(e.before_context)),e.after_context&&p.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?p.push("-l"):e.output_mode==="count"&&p.push("-c"),p.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:m}=qs(),h=new m("grep","Searching staged content...");h.start();let g=[];for(let y of d)try{let w=he.join(process.cwd(),y);if(await nn(w)){let x=[...p];x.push(e.pattern,w);let{stdout:S}=await ro("grep",x,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let k=oi(S,e.output_mode);g=g.concat(k)}else g=g.concat(oi(S))}}catch{}return g=await yd(g,{query:e.pattern,basePath:process.cwd(),outputMode:e.output_mode}),h.update({count:g.length,detail:"in staged files"}),h.stop(),g.join(`
|
|
350
350
|
`).trim()||"(no matches in staged files)"}let s=["-rn","-E","-H"];e.ignore_case&&s.push("-i"),e.include&&s.push(`--include=${e.include}`),e.type&&s.push(`--include=*.${e.type}`);let r=20;e.context?s.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&s.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&s.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?s.push("-l"):e.output_mode==="count"&&s.push("-c"),s.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),s.push(e.pattern,o);let{ToolProgress:i}=qs(),a=new i("grep","Searching...");a.start();try{let{stdout:c}=await ro("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),u;e.output_mode==="files_with_matches"||e.output_mode==="count"?u=oi(c,e.output_mode):u=oi(c);let d=e.offset||0,f=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return u=await yd(u,{query:e.pattern,basePath:o,outputMode:e.output_mode}),u=u.slice(d,d+f),a.update({count:u.length,detail:`in ${o}`}),a.stop(),u.join(`
|
|
351
351
|
`).trim()||"(no matches)"+gd(e.path)}catch(c){if(a.stop(),c.code===2){let u=(c.stderr||c.message||"").toString().trim();return u.includes("No such file or directory")?`ERROR: Directory not found: ${o}`:u.includes("Invalid")||u.includes("Unmatched")||u.includes("unterminated")||u.includes("unclosed")||u.includes("parse error")||u.includes("brackets")||u.includes("not balanced")?`ERROR: Invalid regex pattern: ${e.pattern}`:`ERROR: grep failed: ${u.slice(0,200)||"exit code 2"}`}return"(no matches)"+gd(e.path)}}case"patch_file":{let o=new hc("patch_file","Preparing patches...");o.start();try{await $d();let s=St(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await nn(s)){let x=await yc(e.path);if(x.fixedPath)s=x.fixedPath,console.log(`${we.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${he.relative(process.cwd(),s)}${we.reset}`);else return`ERROR: File not found: ${e.path}${x.message?`
|
|
352
|
-
`+x.message:""}`}let i=e.patches;if(!Array.isArray(i)||i.length===0)return"ERROR: No patches provided";o.update({count:0,total:i.length,detail:`${he.relative(process.cwd(),s)} ${i.length} patches`,message:"Validating patches"});let a=await ht.readFile(s,"utf-8"),{getActiveModelId:c,getActiveProviderName:u}=Xe(),d=
|
|
352
|
+
`+x.message:""}`}let i=e.patches;if(!Array.isArray(i)||i.length===0)return"ERROR: No patches provided";o.update({count:0,total:i.length,detail:`${he.relative(process.cwd(),s)} ${i.length} patches`,message:"Validating patches"});let a=await ht.readFile(s,"utf-8"),{getActiveModelId:c,getActiveProviderName:u}=Xe(),d=U$(c(),u()),f=[],p=!1,m=!1;for(let x=0;x<i.length;x++){o.update({count:x+1,total:i.length,detail:`${he.relative(process.cwd(),s)} patch ${x+1}/${i.length}`,message:"Matching patches"});let{old_text:S,new_text:k}=i[x];if(a.includes(S))f.push({old_text:S,new_text:k});else if(d==="strict"){let v=ai(a,S);return v?`ERROR: Patch ${x+1} old_text not found in ${s} (strict mode \u2014 exact match required)
|
|
353
353
|
Most similar text (line ${v.line}, distance ${v.distance}):
|
|
354
|
-
${v.text}`:`ERROR: Patch ${x+1} old_text not found in ${s} (strict mode \u2014 exact match required)`}else{let v=
|
|
354
|
+
${v.text}`:`ERROR: Patch ${x+1} old_text not found in ${s} (strict mode \u2014 exact match required)`}else{let v=D$(a,S);if(v)f.push({old_text:v,new_text:k}),p=!0;else{let C=ai(a,S);if(C){let q=Math.max(3,Math.ceil(S.length*.05));if(C.distance<=q)f.push({old_text:C.text,new_text:k}),m=!0;else return`ERROR: Patch ${x+1} old_text not found in ${s}
|
|
355
355
|
Most similar text (line ${C.line}, distance ${C.distance}):
|
|
356
356
|
${C.text}`}else return`ERROR: Patch ${x+1} old_text not found in ${s}`}}}let h=a;for(let{old_text:x,new_text:S}of f)h=h.split(x).join(S);if(!n.autoConfirm){o.update({message:"Previewing patch set",count:f.length,total:i.length,detail:`${he.relative(process.cwd(),s)} ${f.length} matched`});let x=await si(s,h);if(pc(s,a,h,{annotations:x}),!await ni(p?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}o.update({message:"Applying patches",count:f.length,total:i.length,detail:`${he.relative(process.cwd(),s)} ${f.length} matched`}),await ht.writeFile(s,h,"utf-8");let g=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||h.startsWith("#!");g&&(o.update({message:"Chmod",detail:he.relative(process.cwd(),s)}),await ht.chmod(s,493)),mc("patch_file",s,a,h);let y=m?" (auto-fixed)":p?" (fuzzy match)":"",w=g?" [chmod +x applied]":"";return`Patched: ${s} (${i.length} replacements)${y}${w}`}finally{o.stop()}}case"web_fetch":{let o=e.url,s=e.max_length||1e4;try{let i=new URL(o).hostname;if(/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|169\.254\.|0\.|localhost$|\[::1?\]|\[fd|fc)/i.test(i))return"ERROR: Fetching private/internal addresses is not allowed.";let a=await hd.get(o,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof a.data=="string"?a.data:JSON.stringify(a.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,s)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${o}: ${r.message}`}}case"web_search":{let o=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let s=await hd.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=s.data?.choices?.[0]?.message?.content||"",i=s.data?.citations||[],a=`[Perplexity grounded search]
|
|
357
357
|
|
|
@@ -454,7 +454,7 @@ ${r}
|
|
|
454
454
|
${s.map((c,u)=>` ${u+1}. ${c}`).join(`
|
|
455
455
|
`)}
|
|
456
456
|
`:"";console.log(`
|
|
457
|
-
${we.cyan}${we.bold} ? ${o}${we.reset}${a}`),i.question(`${we.cyan} > ${we.reset}`,c=>{io=null,i.close(),r(c.trim()||"(no response)")})})}case"git_status":{if(!await md())return"ERROR: Not a git repository";let o=await
|
|
457
|
+
${we.cyan}${we.bold} ? ${o}${we.reset}${a}`),i.question(`${we.cyan} > ${we.reset}`,c=>{io=null,i.close(),r(c.trim()||"(no response)")})})}case"git_status":{if(!await md())return"ERROR: Not a git repository";let o=await j$()||"(detached)",s=await zR();if(s.length===0)return`Branch: ${o}
|
|
458
458
|
Clean working tree (no changes)`;let r=[`Branch: ${o}`,`Changed files (${s.length}):`];for(let i of s){let a=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${a}: ${i.file}`)}return r.join(`
|
|
459
459
|
`)}case"git_diff":{if(!await md())return"ERROR: Not a git repository";let o;if(e.file){let s=["diff"];e.staged&&s.push("--cached"),s.push("--",e.file);try{o=execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{o=""}}else o=await KR(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await md())return"ERROR: Not a git repository";let s=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&s.push("--",e.file);try{return execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:o,updateTask:s,getTaskList:r,renderTaskList:i,hasActiveTasks:a}=Qa(),{getActiveTaskProgress:c}=He(),u=c();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let d=o(e.name,e.tasks);return u||console.log(`
|
|
460
460
|
`+i()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
@@ -466,17 +466,17 @@ Clean working tree (no changes)`;let r=[`Branch: ${o}`,`Changed files (${s.lengt
|
|
|
466
466
|
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";if(!/^\d+$/.test(String(e.run_id)))return"ERROR: run_id must be numeric";try{if(e.log){let{stdout:i}=await ro("gh",["run","view",String(e.run_id),"--log"],{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
|
|
467
467
|
...(truncated)`:"")}let{stdout:o}=await ro("gh",["run","view",String(e.run_id),"--json","status,conclusion,name,headBranch,createdAt,updatedAt,jobs"],{cwd:process.cwd(),timeout:3e4}),s=JSON.parse(o),r=[`Run: ${s.name} [${e.run_id}]`,`Branch: ${s.headBranch} Status: ${s.conclusion||s.status}`,`Started: ${s.createdAt} Finished: ${s.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of s.jobs||[]){let a=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${a} ${i.name} (${i.conclusion||i.status})`);for(let c of i.steps||[]){if(c.conclusion==="failure"||c.conclusion==="skipped")continue;let u=c.conclusion==="success"?" \u2713":c.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${c.name}`)}}return r.join(`
|
|
468
468
|
`)}catch(o){return`ERROR: ${(o.stderr||o.message||"").toString().split(`
|
|
469
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";if(!/^[\w./-]+$/.test(e.workflow))return"ERROR: invalid workflow name";let{confirm:o}=It(),s=e.branch||await
|
|
469
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";if(!/^[\w./-]+$/.test(e.workflow))return"ERROR: invalid workflow name";let{confirm:o}=It(),s=e.branch||await j$()||"main";if(!/^[\w./-]+$/.test(s))return"ERROR: invalid branch name";let r=["workflow","run",e.workflow,"--ref",s];if(e.inputs)for(let[a,c]of Object.entries(e.inputs)){if(!/^[\w-]+$/.test(a))return`ERROR: invalid input key: ${a}`;r.push("-f",`${a}=${c}`)}if(console.log(`
|
|
470
470
|
${we.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${s}${we.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await ro("gh",r,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${s}". Check status with gh_run_list.`}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
471
|
-
`)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",s=e.label?`-l ${e.label}`:"",r=ii(`get pods ${o} ${s} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await
|
|
472
|
-
`)[0];return a.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${a}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let o=e.namespace||"default",s=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${s}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=ii(r,e);try{let{stdout:a,stderr:c}=await
|
|
471
|
+
`)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",s=e.label?`-l ${e.label}`:"",r=ii(`get pods ${o} ${s} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await at(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
|
|
472
|
+
`)[0];return a.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${a}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let o=e.namespace||"default",s=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${s}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=ii(r,e);try{let{stdout:a,stderr:c}=await at(i,{timeout:6e4,maxBuffer:5242880}),u=(a||c||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
|
|
473
473
|
...(truncated)`:"")}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
474
474
|
`)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let o=e.namespace||"default";if(console.log(`
|
|
475
|
-
${we.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${we.reset}`),console.log(`${we.dim} Command: ${e.command}${we.reset}`),!await Cn(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${o}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=ii(r,e);try{let{stdout:a,stderr:c}=await
|
|
475
|
+
${we.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${we.reset}`),console.log(`${we.dim} Command: ${e.command}${we.reset}`),!await Cn(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${o}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=ii(r,e);try{let{stdout:a,stderr:c}=await at(i,{timeout:6e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
476
476
|
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let o=!!e.dry_run;if(!o){let i=e.file;if(console.log(`
|
|
477
|
-
${we.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${we.reset}`),!await Cn(" Apply to cluster?"))return"CANCELLED: User declined."}let s=`apply -f ${e.file}`;e.namespace&&(s+=` -n ${e.namespace}`),o&&(s+=" --dry-run=client");let r=ii(s,e);try{let{stdout:i,stderr:a}=await
|
|
477
|
+
${we.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${we.reset}`),!await Cn(" Apply to cluster?"))return"CANCELLED: User declined."}let s=`apply -f ${e.file}`;e.namespace&&(s+=` -n ${e.namespace}`),o&&(s+=" --dry-run=client");let r=ii(s,e);try{let{stdout:i,stderr:a}=await at(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
|
|
478
478
|
`)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let o=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let a=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
|
|
479
|
-
${we.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${o})${we.reset}`),!await Cn(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,i=ii(r,e);try{let{stdout:a,stderr:c}=await
|
|
479
|
+
${we.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${o})${we.reset}`),!await Cn(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,i=ii(r,e);try{let{stdout:a,stderr:c}=await at(i,{timeout:12e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
480
480
|
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:o,readDocument:s}=Zr(),{name:r,content:i,mode:a}=e;if(a==="create"&&s(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(a==="append"){let c=s(r),u=c.content?c.content+`
|
|
481
481
|
|
|
482
482
|
`+i:i;return o(r,u),`Appended to brain document: ${r}.md`}return o(r,i),`${a==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let o;try{o=gn(e.server)}catch(C){return`ERROR: ${C.message}`}let s=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=BR(s);if(a)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(s)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
|
|
@@ -500,29 +500,29 @@ ${p||m||"(no output)"}`}let h=/\bgrep\b/.test(s),g=m;h&&(g=g.split(`
|
|
|
500
500
|
`));let x=4,S=g.split(`
|
|
501
501
|
`),k=[],v=0;for(;v<S.length;){let C=v+1;for(;C<S.length&&S[C]===S[v];)C++;let q=C-v;if(k.push(S[v]),q>x)k.push(`... (${q-1} identical lines omitted)`);else for(let D=1;D<q;D++)k.push(S[v]);v=C}return k.join(`
|
|
502
502
|
`)||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let o;try{o=gn(e.server)}catch(i){return`ERROR: ${i.message}`}let s=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
503
|
-
${we.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${we.reset}`),!await Cn(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await QR(o,e.local_path,e.remote_path);try{cs().clearRemoteIndex()}catch{}return i}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let o;try{o=gn(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await
|
|
503
|
+
${we.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${we.reset}`),!await Cn(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{let i=await QR(o,e.local_path,e.remote_path);try{cs().clearRemoteIndex()}catch{}return i}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let o;try{o=gn(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await B$(o,e.remote_path,e.local_path)}catch(s){if(/no such file|not found/i.test(s.message))try{let{remoteAutoFixPath:r}=cs(),i=e.remote_path.split("/").slice(0,-1).join("/")||"/",a=await r(o,i,e.remote_path);if(a.fixedPath){console.log(`${we.dim} \u2713 remote auto-fix: ${e.remote_path} \u2192 ${a.fixedPath}${we.reset}`);let c=await B$(o,a.fixedPath,e.local_path);return`${a.message}
|
|
504
504
|
${c}`}if(a.message)return`ERROR: ${s.message}
|
|
505
505
|
|
|
506
506
|
${a.message}`}catch{}return`ERROR: ${s.message}`}}case"remote_agent":{let o=require("path").join(process.cwd(),".nex","servers.json"),s=null;try{s=JSON.parse(require("fs").readFileSync(o,"utf-8"))[e.server]||null}catch{}let r=s?`${s.user||"root"}@${s.host}`:e.server,i=s?.key?["-i",s.key]:[],a=(e.project_path||s?.home||"~").replace(/[^a-zA-Z0-9_/~.-]/g,""),c=(e.model||"").replace(/[^a-zA-Z0-9_:.-]/g,""),d=['TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt) && chmod 600 "$TMPFILE"',`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${a}" 2>/dev/null || true`,c?`nex-code --prompt-file "$TMPFILE" --auto --model "${c}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:f}=require("child_process"),p=f("ssh",[...i,"-o","StrictHostKeyChecking=yes","-o","ConnectTimeout=10",r,`bash -c '${d}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(p.error)return`ERROR: SSH connection failed: ${p.error.message}`;let m=(p.stdout||"")+(p.stderr||"");return p.status!==0?`Remote nex-code exited with code ${p.status}.
|
|
507
507
|
${m.slice(-2e3)}`:m.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let o=bd(e.service);if(o)return o;let s=["status","start","stop","restart","reload","enable","disable"];if(!s.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${s.join(", ")}`;let r=!e.server||e.server==="local"||e.server==="localhost",i=e.action==="status",a=null;if(!r)try{a=gn(e.server)}catch(d){return`ERROR: ${d.message}`}if(!i){let d=r?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
|
|
508
|
-
${we.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${d}${we.reset}`),!await Cn(" Execute?"))return"CANCELLED: User declined service action."}let c=e.service.includes(".")?e.service:`${e.service}.service`,u=`systemctl ${e.action} ${Be(c)}`;if(r){let f=e.action!=="status"?`sudo ${u}`:u;try{let{stdout:p,stderr:m}=await
|
|
508
|
+
${we.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${d}${we.reset}`),!await Cn(" Execute?"))return"CANCELLED: User declined service action."}let c=e.service.includes(".")?e.service:`${e.service}.service`,u=`systemctl ${e.action} ${Be(c)}`;if(r){let f=e.action!=="status"?`sudo ${u}`:u;try{let{stdout:p,stderr:m}=await at(f,{timeout:15e3});return(p||m||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(p){let m=(p.stderr||p.message||"").toString().trim();return/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${p.code||1}
|
|
509
509
|
${m}`}}else{let{stdout:d,stderr:f,exitCode:p,error:m}=await Bt(a,u,{timeout:15e3,sudo:!0}),h=[d,f].filter(Boolean).join(`
|
|
510
510
|
`).trim();return p!==0?/not found|loaded.*not-found/i.test(h)?`ERROR: Service "${e.service}" not found on ${a.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${p}
|
|
511
|
-
${m||h||"(no output)"}`:h||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=bd(e.service);if(o)return o;let s=!e.server||e.server==="local"||e.server==="localhost",r=e.lines||50,i=e.service.includes(".")?e.service:`${e.service}.service`,a=e.since?`--since ${Be(e.since)}`:"",c=e.follow?"-f":"",u=`journalctl -u ${Be(i)} -n ${r} ${a} ${c} --no-pager`.trim().replace(/\s+/g," ");if(s)try{let{stdout:y,stderr:w}=await
|
|
511
|
+
${m||h||"(no output)"}`:h||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=bd(e.service);if(o)return o;let s=!e.server||e.server==="local"||e.server==="localhost",r=e.lines||50,i=e.service.includes(".")?e.service:`${e.service}.service`,a=e.since?`--since ${Be(e.since)}`:"",c=e.follow?"-f":"",u=`journalctl -u ${Be(i)} -n ${r} ${a} ${c} --no-pager`.trim().replace(/\s+/g," ");if(s)try{let{stdout:y,stderr:w}=await at(u,{timeout:15e3});return(y||w||"(no log output)").trim()}catch(y){return`EXIT ${y.code||1}
|
|
512
512
|
${(y.stderr||y.message||"").toString().trim()}`}let d;try{d=gn(e.server)}catch(y){return`ERROR: ${y.message}`}let{stdout:f,stderr:p,exitCode:m,error:h}=await Bt(d,u,{timeout:2e4}),g=[f,p].filter(Boolean).join(`
|
|
513
513
|
`).trim();return m!==0?`EXIT ${m}
|
|
514
|
-
${h||g||"(no output)"}`:g||"(no log output)"}case"container_list":{let o=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(o)try{let{stdout:p,stderr:m}=await
|
|
514
|
+
${h||g||"(no output)"}`:g||"(no log output)"}case"container_list":{let o=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(o)try{let{stdout:p,stderr:m}=await at(r,{timeout:1e4});return(p||m||"(no containers)").trim()}catch(p){return`EXIT ${p.code||1}
|
|
515
515
|
${(p.stderr||p.message||"").toString().trim()}`}let i;try{i=gn(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:a,stderr:c,exitCode:u,error:d}=await Bt(i,r,{timeout:15e3}),f=[a,c].filter(Boolean).join(`
|
|
516
516
|
`).trim();return u!==0?`EXIT ${u}
|
|
517
|
-
${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let o=!e.server||e.server==="local"||e.server==="localhost",s=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${s} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(o)try{let{stdout:m,stderr:h}=await
|
|
517
|
+
${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let o=!e.server||e.server==="local"||e.server==="localhost",s=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${s} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(o)try{let{stdout:m,stderr:h}=await at(i,{timeout:15e3});return(m||h||"(no log output)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
518
518
|
${(m.stderr||m.message||"").toString().trim()}`}let a;try{a=gn(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:u,exitCode:d,error:f}=await Bt(a,i,{timeout:2e4}),p=[c,u].filter(Boolean).join(`
|
|
519
519
|
`).trim();return d!==0?`EXIT ${d}
|
|
520
520
|
${f||p}`:p||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let o=!e.server||e.server==="local"||e.server==="localhost",s=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!n.autoConfirm&&!s.test(e.command.trim())){let h=o?"local":e.server;if(console.log(`
|
|
521
|
-
${we.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${we.reset}`),!await Cn(" Execute?"))return"CANCELLED: User declined."}let i=(e.container||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(!i)return"ERROR: Invalid container name";let a=`docker exec ${i} sh -c ${JSON.stringify(e.command)}`;if(o)try{let{stdout:h,stderr:g}=await
|
|
521
|
+
${we.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${we.reset}`),!await Cn(" Execute?"))return"CANCELLED: User declined."}let i=(e.container||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(!i)return"ERROR: Invalid container name";let a=`docker exec ${i} sh -c ${JSON.stringify(e.command)}`;if(o)try{let{stdout:h,stderr:g}=await at(a,{timeout:3e4});return(h||g||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
522
522
|
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=gn(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:u,stderr:d,exitCode:f,error:p}=await Bt(c,a,{timeout:35e3}),m=[u,d].filter(Boolean).join(`
|
|
523
523
|
`).trim();return f!==0?`EXIT ${f}
|
|
524
524
|
${p||m}`:m||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let o=["start","stop","restart","remove","inspect"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let s=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!n.autoConfirm){let h=s?"local":e.server;if(console.log(`
|
|
525
|
-
${we.yellow} \u26A0 docker ${e.action} ${e.container} on ${h}${we.reset}`),!await Cn(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,a=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(s)try{let{stdout:h,stderr:g}=await
|
|
525
|
+
${we.yellow} \u26A0 docker ${e.action} ${e.container} on ${h}${we.reset}`),!await Cn(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,a=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(s)try{let{stdout:h,stderr:g}=await at(a,{timeout:3e4});return(h||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(h){return`EXIT ${h.code||1}
|
|
526
526
|
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=gn(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:u,stderr:d,exitCode:f,error:p}=await Bt(c,a,{timeout:35e3}),m=[u,d].filter(Boolean).join(`
|
|
527
527
|
`).trim();return f!==0?`EXIT ${f}
|
|
528
528
|
${p||m}`:m||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...eC(e.config),...e},delete e.config,delete e._name}catch(d){return`ERROR: ${d.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let o=e.method||"rsync";if(o==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let s;try{s=gn(e.server)}catch(d){return`ERROR: ${d.message}`}let r=s.user?`${s.user}@${s.host}`:s.host;if(!e.dry_run&&!n.autoConfirm){if(o==="git"){let f=e.branch?` (branch: ${e.branch})`:"";console.log(`
|
|
@@ -531,7 +531,7 @@ ${we.yellow} \u26A0 Deploy [rsync]: ${f} \u2192 ${r}:${e.remote_path}${we.reset
|
|
|
531
531
|
${p}${e.deploy_script?`
|
|
532
532
|
${e.deploy_script}`:""}`;let{stdout:m,stderr:h,exitCode:g,error:y}=await Bt(s,p,{timeout:12e4});if(i=[m,h].filter(Boolean).join(`
|
|
533
533
|
`).trim(),g!==0)return`ERROR (git pull, exit ${g}):
|
|
534
|
-
${y||i}`}else{let d=s.key?`-e "ssh -i ${s.key.replace(/^~/,require("os").homedir())}${s.port&&Number(s.port)!==22?` -p ${s.port}`:""}"`:s.port&&Number(s.port)!==22?`-e "ssh -p ${s.port}"`:"",f=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),p=e.dry_run?"--dry-run":"",m=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,h=`rsync -avz --delete ${p} ${f} ${d} ${m} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:y}=await
|
|
534
|
+
${y||i}`}else{let d=s.key?`-e "ssh -i ${s.key.replace(/^~/,require("os").homedir())}${s.port&&Number(s.port)!==22?` -p ${s.port}`:""}"`:s.port&&Number(s.port)!==22?`-e "ssh -p ${s.port}"`:"",f=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),p=e.dry_run?"--dry-run":"",m=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,h=`rsync -avz --delete ${p} ${f} ${d} ${m} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:y}=await at(h,{timeout:12e4});i=(g||y||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
|
|
535
535
|
${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:d,stderr:f,exitCode:p,error:m}=await Bt(s,e.deploy_script,{timeout:12e4}),h=[d,f].filter(Boolean).join(`
|
|
536
536
|
`).trim();if(p!==0)return`${o==="git"?"git pull":"rsync"} OK
|
|
537
537
|
|
|
@@ -556,8 +556,8 @@ ${r.join(`
|
|
|
556
556
|
`)}`}case"frontend_recon":{let o=process.cwd(),s=(e.type||"").toLowerCase(),r=[],i=async(k,v=120)=>{try{let C=he.isAbsolute(k)?k:he.join(o,k),D=(await ht.readFile(C,"utf8")).split(`
|
|
557
557
|
`),ee=D.slice(0,v).join(`
|
|
558
558
|
`);return D.length>v?ee+`
|
|
559
|
-
... (${D.length-v} more lines \u2014 use read_file for full content)`:ee}catch{return null}},c=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(k=>`-not -path "*/${k}/*"`).join(" "),u=async k=>{try{let{stdout:v}=await
|
|
560
|
-
`).filter(Boolean)}catch{return[]}},d=async(k,v)=>{try{let{stdout:C}=await
|
|
559
|
+
... (${D.length-v} more lines \u2014 use read_file for full content)`:ee}catch{return null}},c=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(k=>`-not -path "*/${k}/*"`).join(" "),u=async k=>{try{let{stdout:v}=await at(`find "${o}" -type f -name "${k}" ${c} 2>/dev/null | head -10`,{timeout:8e3});return v.trim().split(`
|
|
560
|
+
`).filter(Boolean)}catch{return[]}},d=async(k,v)=>{try{let{stdout:C}=await at(`grep -rl "${k}" "${o}" --include="${v}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return C.trim().split(`
|
|
561
561
|
`).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
|
|
562
562
|
`);let f=[...await u("tailwind.config.js"),...await u("tailwind.config.ts"),...await u("tailwind.config.mjs")];if(f.length>0){let k=await i(f[0],80);k&&r.push(`### Tailwind config (${he.relative(o,f[0])})
|
|
563
563
|
\`\`\`js
|
|
@@ -575,7 +575,7 @@ ${v}
|
|
|
575
575
|
${C}
|
|
576
576
|
\`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
|
|
577
577
|
## STEP 3: Reference Component (same type)
|
|
578
|
-
`);let y=[];if(s){for(let k of["*.html","*.vue","*.jsx","*.tsx"])if(y=await d(s,k),y.length>0)break}if(y.length===0)try{let{stdout:k}=await
|
|
578
|
+
`);let y=[];if(s){for(let k of["*.html","*.vue","*.jsx","*.tsx"])if(y=await d(s,k),y.length>0)break}if(y.length===0)try{let{stdout:k}=await at(`find "${o}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});y=k.trim().split(`
|
|
579
579
|
`).filter(Boolean)}catch{y=[]}if(y.length>0){let k=y[0],v=await i(k,150);v?r.push(`### Reference: ${he.relative(o,k)}
|
|
580
580
|
\`\`\`html
|
|
581
581
|
${v}
|
|
@@ -586,7 +586,7 @@ ${v}
|
|
|
586
586
|
\u26A0 Use ONLY the frameworks listed above. Do NOT mix (e.g. no fetch() when HTMX is used for the same action).`)):r.push("(framework not detected \u2014 check package.json or script tags manually)"),r.push(`
|
|
587
587
|
---
|
|
588
588
|
\u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
|
|
589
|
-
`)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let o=!e.server||e.server==="local"||e.server==="localhost",s;if(!o)try{s=gn(e.server)}catch(c){return`ERROR: ${c.message}`}let r=async(c,u=3e4)=>{if(o)try{let{stdout:d,stderr:f}=await
|
|
589
|
+
`)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let o=!e.server||e.server==="local"||e.server==="localhost",s;if(!o)try{s=gn(e.server)}catch(c){return`ERROR: ${c.message}`}let r=async(c,u=3e4)=>{if(o)try{let{stdout:d,stderr:f}=await at(c,{timeout:u});return{out:(d||f||"").trim(),exitCode:0}}catch(d){return{out:(d.stderr||d.message||"").toString().trim(),exitCode:d.code||1}}else{let{stdout:d,stderr:f,exitCode:p,error:m}=await Bt(s,c,{timeout:u}),h=[d,f].filter(Boolean).join(`
|
|
590
590
|
`).trim();return{out:m&&p!==0&&!d.trim()?(m+`
|
|
591
591
|
`+h).trim():h,exitCode:p}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!n.autoConfirm){let c=o?"local":e.server;if(!await Cn(`sysadmin [${e.action}] on ${c} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let c=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:u,exitCode:d}=await r(c,45e3);return u||`EXIT ${d}
|
|
592
592
|
(no output)`}case"disk_usage":{let c=e.path||"/",u=Be(c),d=`df -h ${u}; echo '--- Top subdirs ---'; du -d1 -x -h ${u} 2>/dev/null | sort -rh | head -20`,{out:f,exitCode:p}=await r(d,3e4);return p!==0?`EXIT ${p}
|
|
@@ -595,7 +595,7 @@ ${f}`:f}case"network_status":{let c="ss -tlnp 2>/dev/null || netstat -tlnp 2>/de
|
|
|
595
595
|
${u}`:u}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:c}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),u=c.includes("dnf")?"dnf":c.includes("apt")?"apt":null;if(!u)return"ERROR: No supported package manager found (dnf/apt)";let d=e.packages||[];if(!d.every(mC))return"ERROR: package names contain unsafe characters";let f=d.map(Be).join(" "),p;switch(e.package_action){case"list":p=u==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let g=u==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:y}=await r(g,6e4);return y||"(no output from package check)"}case"install":if(!f)return"ERROR: packages required for install";p=u==="dnf"?`dnf install -y ${f}`:`apt-get install -y ${f}`;break;case"remove":if(!f)return"ERROR: packages required for remove";p=u==="dnf"?`dnf remove -y ${f}`:`apt-get remove -y ${f}`;break;case"update":if(!f)return"ERROR: packages required for update (use upgrade for full system upgrade)";p=u==="dnf"?`dnf update -y ${f}`:`apt-get install -y --only-upgrade ${f}`;break;case"upgrade":p=u==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:m,exitCode:h}=await r(p,12e4);return h!==0?`EXIT ${h}
|
|
596
596
|
${m}`:m||`${e.package_action} OK`}case"user_manage":{if(!e.user_action)return"ERROR: user_action is required for action=user_manage";switch(e.user_action){case"list":{let c=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:u,exitCode:d}=await r(c,1e4);return d!==0?`EXIT ${d}
|
|
597
597
|
${u}`:u||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let c=ri(e.user);if(c)return c;let u=Be(e.user),d=`id ${u} && echo '--- Groups ---' && groups ${u} && echo '--- Last login ---' && lastlog -u ${u} 2>/dev/null`,{out:f,exitCode:p}=await r(d,1e4);return p!==0?`EXIT ${p}
|
|
598
|
-
${f}`:f}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let c=ri(e.user);if(c)return c;if(!(e.groups||[]).every(
|
|
598
|
+
${f}`:f}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let c=ri(e.user);if(c)return c;if(!(e.groups||[]).every(Z$))return"ERROR: groups contain unsafe characters";let u=(e.groups||[]).map(h=>`-G ${Be(h)}`).join(" "),d=Be(e.user),f=`useradd -m ${u} ${d} && echo "User ${e.user} created"`,{out:p,exitCode:m}=await r(f,15e3);return m!==0?`EXIT ${m}
|
|
599
599
|
${p}`:p}case"delete":{if(!e.user)return"ERROR: user is required for user_action=delete";let c=ri(e.user);if(c)return c;let d=`userdel -r ${Be(e.user)} && echo "User ${e.user} deleted"`,{out:f,exitCode:p}=await r(d,15e3);return p!==0?`EXIT ${p}
|
|
600
600
|
${f}`:f}case"add_ssh_key":{if(!e.user)return"ERROR: user is required for user_action=add_ssh_key";if(!e.ssh_key)return"ERROR: ssh_key is required for user_action=add_ssh_key";let c=ri(e.user);if(c)return c;let d=`${`/home/${e.user}`}/.ssh`,f=`${d}/authorized_keys`,p=Be(e.user),m=`mkdir -p ${Be(d)} && chmod 700 ${Be(d)} && printf '%s
|
|
601
601
|
' ${Be(e.ssh_key)} >> ${Be(f)} && chmod 600 ${Be(f)} && chown -R ${Be(`${e.user}:${e.user}`)} ${Be(d)} && echo "SSH key added for ${e.user}"`,{out:h,exitCode:g}=await r(m,15e3);return g!==0?`EXIT ${g}
|
|
@@ -632,7 +632,7 @@ ${d}`:d||"(empty log)"}case"find_large":{let c=e.path||"/",u=e.limit||20,d=e.min
|
|
|
632
632
|
${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)";if(e.service_name){let m=bd(e.service_name,"service_name");if(m)return m}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}
|
|
633
633
|
${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";if(!gC(c))return"ERROR: signal contains unsafe characters";let u;if(e.pid){if(!/^\d+$/.test(String(e.pid)))return"ERROR: pid must be numeric";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}"`}else u=`pgrep -a ${Be(e.process_name)} 2>/dev/null | head -5 && pkill -${c} ${Be(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}
|
|
634
634
|
${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}
|
|
635
|
-
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=Rn(),s=o(e.type,e.name,e.content,e.description);return s.ok?s.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${s.path}`:`ERROR: ${s.error}`}case"delete_memory":{let{deleteMemory:o}=Rn();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=Pa(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function $C(t,e,n={}){let{emit:o}=Pa(),{logToolExecution:s}=pd(),r=Date.now(),i=n.silent?null:YR(t,e);if(!i){let c=await
|
|
635
|
+
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=Rn(),s=o(e.type,e.name,e.content,e.description);return s.ok?s.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${s.path}`:`ERROR: ${s.error}`}case"delete_memory":{let{deleteMemory:o}=Rn();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=Pa(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function $C(t,e,n={}){let{emit:o}=Pa(),{logToolExecution:s}=pd(),r=Date.now(),i=n.silent?null:YR(t,e);if(!i){let c=await Y$(t,e,n);return s({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:c}),c}let a=new GR(i);a.start();try{let c=await Y$(t,e,n);return a.stop(),s({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:c}),c}catch(c){throw a.stop(),s({tool:t,args:e,result:c.message,duration:Date.now()-r,success:!1}),c}}Q$.exports={TOOL_DEFINITIONS:yC,executeTool:$C,resolvePath:St,autoFixPath:yc,autoFixEdit:J$,enrichBashError:V$,cancelPendingAskUser:cC,setAskUserHandler:lC,fileExists:nn}});var Sn=X((R2,t0)=>{t0.exports=e0()});var vd=X((A2,s0)=>{var{loadServerProfiles:er,resolveProfile:C2,sshExec:wC}=cs(),bC=/\.(?:png|jpe?g|gif|webp|bmp|svg|ico|pdf|mp4|webm|mov)(?:[?#].*)?$/i,_C=/\b(bug|issue|problem|broken|failing|fails|error|wrong|regression|debug|investigate|why|slow|fix|delete|deleted|deleting|removed|reappears?|returns?|comes?\s+back|webui|production|prod|server|fehler|kaputt|lösche|loesch|gelösch|geloesch|zurück|zurueck|taucht?\s+wieder\s+auf)\b/i,xC=/https?:\/\/[^\s)]+/gi;function vC(t){if(typeof t!="string")return[];let e=new Set,n=[];for(let o of t.match(xC)||[]){let s=o.replace(/[.,;!?]+$/g,"");e.has(s)||(e.add(s),n.push(s))}return n}function kC(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return null}let o=n.split(".");for(let[s,r]of Object.entries(e))if(o.includes(s.toLowerCase()))return{matchedName:s,matchedProfile:r,hostname:n};for(let[s,r]of Object.entries(e))if(String(r.host||"").toLowerCase()===n)return{matchedName:s,matchedProfile:r,hostname:n};return{matchedName:null,matchedProfile:null,hostname:n}}function n0(t,e=er()){if(typeof t!="string"||!_C.test(t))return null;let n=vC(t).filter(o=>!bC.test(o));if(n.length===0)return null;for(let o of n){let s=kC(o,e);if(s)return{url:o,hostname:s.hostname,matchedName:s.matchedName,matchedProfile:s.matchedProfile,shouldPreferBrowser:!0,shouldPreferSsh:!!(s.matchedName&&s.matchedProfile)}}return null}var xd={almalinux9:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all. Open port: firewall-cmd --permanent --add-port=PORT/tcp && firewall-cmd --reload.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent | audit2why. Fix context: restorecon -Rv /path.","Nginx config: /etc/nginx/. Test: nginx -t. Reload: systemctl reload nginx.","Process list: ps aux. Ports: ss -tuln.","Python: python3. Pip: pip3. Virtualenv: python3 -m venv."],almalinux8:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent."],ubuntu:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw. Status: ufw status. Allow port: ufw allow PORT/tcp.","SELinux NOT active by default (AppArmor instead). Check: aa-status."],debian:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw or iptables."],macos:["Package manager: Homebrew (brew). Install: brew install <pkg>. Update: brew update && brew upgrade.","Service manager: launchctl (NOT systemctl). Start: brew services start <name>. List: brew services list.",`No systemd. No journalctl. Use: log show --predicate 'process == "nginx"' --last 1h instead.`,"Firewall: macOS built-in (pfctl or System Settings). Check: pfctl -s rules.","Process list: ps aux. Ports: lsof -i -n -P | grep LISTEN."]};function SC(){let t=er();if(Object.keys(t).length===0)return null;let n=["## Remote Servers (.nex/servers.json)"];n.push(""),n.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[s,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,a=r.port&&Number(r.port)!==22?`:${r.port}`:"",c=r.os?` \u2014 OS: ${r.os}`:"",u=r.sudo?", sudo available":"";n.push(`- **${s}**: ${i}${a}${c}${u}`)}let o=new Set;for(let s of Object.values(t))s.os&&xd[s.os]&&o.add(s.os);if(o.size>0){n.push("");for(let s of o){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[s]||s;n.push(`### ${r} Notes`);for(let i of xd[s])n.push(`- ${i}`)}}return n.join(`
|
|
636
636
|
`)}function EC(t){let e=er();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function TC(){return Object.keys(er())}function RC(){let t=require("fs"),n=require("path").join(process.cwd(),"NEX.md"),o="";try{o=t.readFileSync(n,"utf-8")}catch{}let s=er(),r=Object.keys(s);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],a=o.toLowerCase();if(!i.some(p=>a.includes(p)))return null;let u=r.map(p=>{let m=s[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(`
|
|
637
637
|
`),d=r.map(p=>s[p].log_path).filter(Boolean),f=d.length>0?`
|
|
638
638
|
- Server log paths: ${d.join(", ")}`:"";return`# Deployment Context (Auto-detected)
|
|
@@ -663,36 +663,36 @@ ${u}
|
|
|
663
663
|
- CRITICAL: When the user pastes a server error message (error logs), this is NEVER a "simple question" to answer from training knowledge. You MUST ssh_exec to verify if the error is still occurring BEFORE writing any explanation. Do NOT explain from memory \u2014 investigate first, always.
|
|
664
664
|
- 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.
|
|
665
665
|
- 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.
|
|
666
|
-
- 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 AC(t){let e=er(),n=
|
|
667
|
-
`+i.trim()}catch{return null}}
|
|
666
|
+
- 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 AC(t){let e=er(),n=n0(t,e);if(!n?.matchedProfile||!n?.matchedName)return null;let{matchedProfile:o,matchedName:s}=n,r=["ss -tlnp 2>/dev/null | awk 'NR>1{print $4}' | grep -oE ':[0-9]+$' | sort -u | head -8","echo '---services---'","ps aux 2>/dev/null | grep -E '(node |python3 |gunicorn|uvicorn|ruby |java )' | grep -v grep | awk '{print $11, $12, $13}' | head -6","echo '---data---'","find /home -maxdepth 5 -name 'data' -type d 2>/dev/null | head -6"].join("; ");try{let{stdout:i}=await wC(o,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=o.user?`${o.user}@${o.host}`:o.host;return`[Server context for "${s}" (${a}) \u2014 probed at task start]
|
|
667
|
+
`+i.trim()}catch{return null}}s0.exports={getServerContext:SC,getDeploymentContextBlock:RC,hasServerOS:EC,getProfileNames:TC,probeUrlServer:AC,detectRuntimeDebugTarget:n0,OS_HINTS:xd}});var _c=X((O2,i0)=>{var Ut=require("fs").promises,wc=require("fs"),ct=require("path"),$c=require("util").promisify(require("child_process").exec),{C:tr}=He(),{getMergeConflicts:r0}=vs(),{getServerContext:OC}=vd(),{refreshIndex:MC,getFileIndex:NC,buildContentIndex:PC,summarizeModuleHubs:LC}=Hn(),IC=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]),jC=[{file:"tsconfig.json",label:"TypeScript"},{file:"jest.config.js",label:"Jest"},{file:"jest.config.cjs",label:"Jest"},{file:"jest.config.mjs",label:"Jest"},{file:"vitest.config.js",label:"Vitest"},{file:"vitest.config.ts",label:"Vitest"},{file:"vite.config.js",label:"Vite"},{file:"vite.config.ts",label:"Vite"},{file:"next.config.js",label:"Next.js"},{file:"next.config.mjs",label:"Next.js"},{file:"tailwind.config.js",label:"Tailwind"},{file:"tailwind.config.ts",label:"Tailwind"},{file:"docker-compose.yml",label:"Docker Compose"},{file:"docker-compose.yaml",label:"Docker Compose"},{file:".github/workflows",label:"GitHub Actions"}];function DC(t,e=6){let n=new Map;for(let o of t){let s=o.includes("/")?o.split("/")[0]:"(root)";!s||s.startsWith(".")||n.set(s,(n.get(s)||0)+1)}return[...n.entries()].sort((o,s)=>s[1]-o[1]||o[0].localeCompare(s[0])).slice(0,e).map(([o,s])=>`${o} (${s})`)}function qC(t){let e=new Set(t),n=new Set;for(let o of jC)(e.has(o.file)||[...e].some(s=>s.startsWith(`${o.file}/`)))&&n.add(o.label);return e.has("package.json")&&n.add("Node.js"),[...e].some(o=>/^tests?\//.test(o)||/\.test\./.test(o)||/\.spec\./.test(o))&&n.add("Tests"),[...e].some(o=>o.startsWith("vscode/"))&&n.add("VS Code Extension"),[...n]}function FC(t){let e=["package.json","cli/index.js","src/index.ts","src/index.js","index.ts","index.js","bin/nex-code.js","dist/nex-code.js","README.md"],n=[];for(let o of e)if(t.includes(o)&&n.push(o),n.length>=5)break;return n}function BC(t,e=6){let n=t.filter(r=>/^tests?\//.test(r)||/\.test\./.test(r)||/\.spec\./.test(r));if(n.length===0)return[];let o=t.filter(r=>!/^tests?\//.test(r)&&!/\.test\./.test(r)&&!/\.spec\./.test(r)&&/\.(js|jsx|ts|tsx|py|go|rs|java)$/.test(r)),s=[];for(let r of o){let i=ct.basename(r).replace(/\.[^.]+$/,"");if(i.length<3)continue;let a=n.filter(c=>c.includes(i));if(a.length>0&&s.push(`${r} -> ${a.slice(0,2).join(", ")}`),s.length>=e)break}return s}function UC(t){return!t||!t.workspaces?[]:Array.isArray(t.workspaces)?t.workspaces:Array.isArray(t.workspaces.packages)?t.workspaces.packages:[]}async function WC(t){try{await MC(t);let e=NC();if(!e||e.length===0)return"";let n=qC(e),o=DC(e),s=FC(e),r=e.filter(f=>/^tests?\//.test(f)||/\.test\./.test(f)||/\.spec\./.test(f)).length,i=BC(e),a=[];try{let f=ct.join(t,"package.json");if(wc.existsSync(f)){let p=JSON.parse(wc.readFileSync(f,"utf-8"));a=UC(p)}}catch{}let c="",u="";try{let f=await PC(t),p=Object.entries(f.files||{}).map(([m,h])=>({file:m,defs:Array.isArray(h.defs)?h.defs.length:0})).filter(m=>m.defs>0).sort((m,h)=>h.defs-m.defs||m.file.localeCompare(h.file)).slice(0,4).map(m=>`${m.file} (${m.defs} defs)`);p.length>0&&(c=`CODE HOTSPOTS: ${p.join(", ")}`)}catch{}try{let f=await LC(t,4);f.length>0&&(u=`MODULE HUBS: ${f.join(", ")}`)}catch{}let d=[`REPO MAP: ${e.length} indexed files${n.length?` | stack: ${n.join(", ")}`:""}`];return o.length>0&&d.push(`WORK AREAS: ${o.join(", ")}`),s.length>0&&d.push(`LIKELY ENTRY POINTS: ${s.join(", ")}`),a.length>0&&d.push(`WORKSPACES: ${a.join(", ")}`),r>0&&d.push(`TEST FOOTPRINT: ${r} test files detected`),i.length>0&&d.push(`TEST MAP: ${i.join(" | ")}`),c&&d.push(c),u&&d.push(u),d.push("RETRIEVAL RULE: Prefer the smallest verified path set first \u2014 identify likely files, then read only the exact symbols/sections you need before editing."),d.join(`
|
|
668
668
|
`)}catch{return""}}function HC(t){try{return wc.readFileSync(t,"utf-8").split(`
|
|
669
|
-
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function GC(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 YC(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=
|
|
670
|
-
`)}var kd=new Map,sr=new Map,bc=null,
|
|
669
|
+
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function GC(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 YC(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=ct.join(t,".gitignore"),r=[...o,...HC(s)],i=0,a=[ct.basename(t)+"/"];function c(u,d,f){if(f>e||i>=n)return;let p;try{p=wc.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=>!(IC.has(h.name)||h.name.startsWith(".")&&h.name!==".env.example"||GC(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],y=h===m.length-1,w=y?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",x=d+(y?" ":"\u2502 "),S=g.isDirectory()?g.name+"/":g.name;a.push(`${d}${w}${S}`),i++,g.isDirectory()&&c(ct.join(u,g.name),x,f+1)}}return c(t,"",1),a.join(`
|
|
670
|
+
`)}var kd=new Map,sr=new Map,bc=null,o0=3e4,nr={result:null,expiry:0,cwd:null};async function Kn(t){try{return await t()}catch{return null}}async function zC(){if(!bc||Date.now()>bc)return!1;let t=[ct.join(process.cwd(),"package.json"),ct.join(process.cwd(),"README.md"),ct.join(process.cwd(),".gitignore")];for(let e of t)try{let n=await Ut.stat(e),o=sr.get(e);if(!o||n.mtimeMs!==o)return!1}catch{if(sr.has(e))return!1}try{let e=ct.join(process.cwd(),".git","HEAD"),n=await Ut.stat(e),o=sr.get(e);if(!o||n.mtimeMs!==o)return!1}catch{}return!0}async function KC(){let t=[ct.join(process.cwd(),"package.json"),ct.join(process.cwd(),"README.md"),ct.join(process.cwd(),".gitignore"),ct.join(process.cwd(),".git","HEAD"),ct.join(process.cwd(),"CLAUDE.md"),ct.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let n=await Ut.stat(e);sr.set(e,n.mtimeMs)}catch{sr.delete(e)}}async function XC(t){let e="fileContext",n=kd.get(e),o=!1;if(n&&await zC()&&(o=!0),!o){let u=[],d=ct.join(t,"package.json");if(await Kn(()=>Ut.access(d).then(()=>!0).catch(()=>!1)))try{let v=await Ut.readFile(d,"utf-8"),C=JSON.parse(v),q={name:C.name,version:C.version};C.scripts&&(q.scripts=Object.keys(C.scripts).slice(0,15)),C.dependencies&&(q.deps=Object.keys(C.dependencies).length),C.devDependencies&&(q.devDeps=Object.keys(C.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(q)}`)}catch{}let p=ct.join(t,"README.md");if(await Kn(()=>Ut.access(p).then(()=>!0).catch(()=>!1))){let C=(await Ut.readFile(p,"utf-8")).split(`
|
|
671
671
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
672
672
|
${C.join(`
|
|
673
|
-
`)}`)}let h=
|
|
674
|
-
${v.trim()}`)}let y=
|
|
675
|
-
${v.trim()}`)}let x=
|
|
673
|
+
`)}`)}let h=ct.join(t,".gitignore");if(await Kn(()=>Ut.access(h).then(()=>!0).catch(()=>!1))){let v=await Ut.readFile(h,"utf-8");u.push(`GITIGNORE:
|
|
674
|
+
${v.trim()}`)}let y=ct.join(t,"CLAUDE.md");if(await Kn(()=>Ut.access(y).then(()=>!0).catch(()=>!1))){let v=await Ut.readFile(y,"utf-8");v.trim()&&u.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
|
|
675
|
+
${v.trim()}`)}let x=ct.join(t,".nex","CLAUDE.md");if(await Kn(()=>Ut.access(x).then(()=>!0).catch(()=>!1))){let v=await Ut.readFile(x,"utf-8");v.trim()&&u.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
|
|
676
676
|
${v.trim()}`)}let k=await WC(t);k&&u.push(k),n=u.join(`
|
|
677
677
|
|
|
678
|
-
`),kd.set(e,n),bc=Date.now()+
|
|
678
|
+
`),kd.set(e,n),bc=Date.now()+o0,await KC()}let s=[n],r,i,a,c;if(nr.result&&Date.now()<nr.expiry&&nr.cwd===t?{branch:r,status:i,log:a,conflicts:c}=nr.result:([r,i,a,c]=await Promise.all([Kn(async()=>{let{stdout:u}=await $c("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Kn(async()=>{let{stdout:u}=await $c("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Kn(async()=>{let{stdout:u}=await $c("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),r0()]),nr={result:{branch:r,status:i,log:a,conflicts:c},expiry:Date.now()+o0,cwd:t}),r&&s.push(`GIT BRANCH: ${r}`),i&&s.push(`GIT STATUS:
|
|
679
679
|
${i}`),a&&s.push(`RECENT COMMITS:
|
|
680
680
|
${a}`),c&&c.length>0){let u=c.map(d=>` ${d.file}`).join(`
|
|
681
681
|
`);s.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
682
682
|
${u}`)}try{let u=OC();u&&s.push(u)}catch{}return s.join(`
|
|
683
683
|
|
|
684
|
-
`)}async function VC(t){let e=at.join(t,"package.json"),n="";if(await Kn(()=>Ut.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Ut.readFile(e,"utf-8"),a=JSON.parse(i);n=`${a.name||"?"} v${a.version||"?"}`}catch{}let[s,r]=await Promise.all([Kn(async()=>{let{stdout:i}=await $c("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),o0()]);if(r&&r.length>0){console.log(`${tr.red} \u26A0 ${r.length} unresolved merge conflict(s):${tr.reset}`);for(let i of r)console.log(`${tr.red} ${i.file}${tr.reset}`);console.log(`${tr.yellow} \u2192 Resolve conflicts before starting tasks${tr.reset}`)}console.log()}r0.exports={gatherProjectContext:XC,printContext:VC,generateFileTree:YC,_clearContextCache:()=>{kd.clear(),sr.clear(),bc=null,nr={result:null,expiry:0,cwd:null}}}});var Mn=X((O2,c0)=>{var On=require("fs"),xc=require("path"),{atomicWrite:JC}=os();function li(){return xc.join(process.cwd(),".nex","sessions")}function Sd(){let t=li();On.existsSync(t)||On.mkdirSync(t,{recursive:!0,mode:448})}function Ed(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return xc.join(li(),`${e}.json`)}function Td(t,e,n={}){Sd();let o=Ed(t),s={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return JC(o,JSON.stringify(s,null,2)),{path:o,name:t}}function i0(t){let e=Ed(t);if(!On.existsSync(e))return null;try{return JSON.parse(On.readFileSync(e,"utf-8"))}catch{return null}}function a0(){Sd();let t=li(),e=On.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(On.readFileSync(xc.join(t,o),"utf-8"));n.push({name:s.name||o.replace(".json",""),createdAt:s.createdAt,updatedAt:s.updatedAt,messageCount:s.messageCount||0,model:s.model,provider:s.provider,score:s.score!=null?s.score:null,scoreGrade:s.scoreGrade||null})}catch{}return n.sort((o,s)=>(s.updatedAt||"").localeCompare(o.updatedAt||""))}function ZC(t){let e=Ed(t);return On.existsSync(e)?(On.unlinkSync(e),!0):!1}function QC(){let t=a0();return t.length===0?null:i0(t[0].name)}var ao=null,ps=null,ci=null;function eA(t,e={}){t.length!==0&&(ao&&clearTimeout(ao),ps=t,ci=e||{},ao=setTimeout(()=>{ps&&ps.length>0&&Td("_autosave",ps,ci),ao=null,ps=null,ci=null},5e3))}function tA(){ao&&(clearTimeout(ao),ao=null),ps&&ps.length>0&&(Td("_autosave",ps,ci),ps=null,ci=null)}function nA(){Sd();let t=li(),e=On.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,o=new Date(n.getTime()-720*60*60*1e3),s=0;for(let r of e){let i=xc.join(t,r);try{let a=On.statSync(i);new Date(a.mtime)<o&&(On.unlinkSync(i),s++)}catch{}}return s}c0.exports={saveSession:Td,loadSession:i0,listSessions:a0,deleteSession:ZC,getLastSession:QC,autoSave:eA,flushAutoSave:tA,clearOldSessions:nA,_getSessionsDir:li}});var vc=X((M2,g0)=>{"use strict";var ui=require("fs"),l0=require("path");function u0(t){let e=[];return t.forEach((n,o)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_use"&&e.push({name:s.name||"",input:s.input||{},index:o,id:s.id||null})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(s=>{let r=s.function?.name||s.name||"",i={};try{i=typeof s.function?.arguments=="string"?JSON.parse(s.function.arguments):s.function?.arguments||s.input||{}}catch{}e.push({name:r,input:i,index:o,id:s.id||null})}))}),e}function sA(t){let e=new Set;return t.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&e.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_result"&&o.tool_use_id&&typeof o.content=="string"&&o.content.startsWith("BLOCKED:")&&e.add(o.tool_use_id)})}),e}function d0(t){let e=[];return t.forEach((n,o)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{if(s&&s.type==="tool_result"){let r=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(s.content||"");e.push({content:r,index:o})}}),n.role==="tool"){let s=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:s,index:o})}}),e}function f0(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let o=n.content.filter(s=>s&&(s.type==="text"||typeof s=="string")).map(s=>typeof s=="string"?s:s.text||"").join("").trim();if(o)return o}}}return""}function p0(t,e){let n=[];for(let o=t.length-1;o>=0&&n.length<e;o--){let s=t[o];if(s.role!=="assistant")continue;let r="";typeof s.content=="string"?r=s.content.trim():Array.isArray(s.content)&&(r=s.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function h0(t){let e=new Map;for(let n of t){let o;try{o=JSON.stringify(n.input)}catch{o=String(n.input)}let s=`${n.name}|${o}`;e.set(s,(e.get(s)||0)+1)}return e}function m0(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,n=[],o=u0(t),s=d0(t),r=o.length,i=sA(t),a=o.filter(E=>!E.id||!i.has(E.id));t.some(E=>E.role==="user"&&typeof E.content=="string"&&E.content.startsWith("[SYSTEM WARNING]")&&(E.content.includes("edited")||E.content.includes("bash command")||E.content.includes("grep pattern")||E.content.includes("re-read")||E.content.includes("already in your context")))&&(e-=2,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let u=o.find(E=>{let P=E.input?.command||E.input?.cmd||"";return/\bsed\s+-n\b/.test(P)});if(u){let E=(u.input?.command||u.input?.cmd||"").slice(0,80);s.some(W=>W.content.includes("BLOCKED: sed -n is forbidden")||W.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${E}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${E}`))}o.find(E=>{if(E.name!=="grep"&&E.name!=="bash"&&E.name!=="ssh_exec")return!1;let P=E.input?.command||E.input?.cmd||"",W=E.input?.pattern||"",oe=`${P} ${W}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(oe)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(oe)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let f=t.some(E=>E.role==="assistant"),p=f0(t),h=p0(t,3).some(E=>E.length>100&&!/^[^.!]{0,40}\?$/.test(E));if(f&&!h&&(p.length<80||/^[^.!]{0,40}\?$/.test(p))){e-=2;let E=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: ${E}`)}r>40?(e-=1.5,n.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,n.push(`High tool call count: ${r} (>25 threshold)`)),t.some(E=>{let P=typeof E.content=="string"?E.content:Array.isArray(E.content)?E.content.map(W=>typeof W=="string"?W:W.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(P)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let w=h0(a),x=0,S="";for(let[E,P]of w)P>x&&(x=P,S=E);if(x>=3){let[E]=S.split("|");e-=1,n.push(`Same tool call repeated ${x}\xD7 (tool: ${E})`)}let k=!1,v=t.findIndex(E=>E.role==="user"&&typeof E.content=="string"&&E.content.includes("[SYSTEM STOP]")&&E.content.includes('"valid":true'));v>=0&&o.filter(P=>P.index>v).length>0&&(k=!0),k&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let C=o.filter(E=>E.name==="ssh_exec");if(C.length>=8){let E=0,P=1;for(let W=1;W<C.length;W++)C[W].index<=C[W-1].index+2?P++:(E=Math.max(E,P),P=1);E=Math.max(E,P),E>=8&&(e-=.5,n.push(`SSH reconnect storm: ${E} 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 q=new Map;for(let E of a)if(E.name==="read_file"&&E.input?.path){let P=E.input.path;q.has(P)||q.set(P,{count:0,ranges:[]});let W=q.get(P);if(W.count++,E.input.line_start!=null){let oe=E.input.line_start||1,O=E.input.line_end||oe+350;W.ranges.push([oe,O])}}function D(E,P,W){for(let[oe,O]of W){let R=Math.max(E,oe),Q=Math.min(P,O);if(Q>R){let N=Q-R,U=P-E||1;if(N/U>=.7)return!0}}return!1}let ee=0,ue="";for(let[E,P]of q){if(P.count<3)continue;if(P.ranges.length===P.count){let O=!1,R=[];for(let[Q,N]of P.ranges){if(R.length>0&&D(Q,N,R)){O=!0;break}R.push([Q,N])}if(!O)continue}if(P.count-P.ranges.length<=2&&P.ranges.length>=1){let O=!1,R=[];for(let[Q,N]of P.ranges){if(R.length>0&&D(Q,N,R)){O=!0;break}R.push([Q,N])}if(!O)continue}P.count>ee&&(ee=P.count,ue=E)}if(ee>=3){e-=1;let E=ue.split("/").slice(-2).join("/");n.push(`read_file loop: "${E}" read ${ee}\xD7 (file already in context)`)}let le=0,de="";for(let[E,P]of q){if(P.ranges.length<4)continue;let W=[],oe=!1;for(let[O,R]of P.ranges){if(W.length>0&&D(O,R,W)){oe=!0;break}W.push([O,R])}!oe&&P.ranges.length>le&&(le=P.ranges.length,de=E)}if(le>=4){e-=.5;let E=de.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${E}" read in ${le} sequential sections \u2014 use grep instead`)}let M=new Map;for(let E of a)if(E.name==="grep"&&E.input?.path&&E.input?.pattern){let P=E.input.path;M.has(P)||M.set(P,new Set),M.get(P).add(E.input.pattern)}let G=0,te="";for(let[E,P]of M)E.split("/").pop().includes(".")&&P.size>G&&(G=P.size,te=E);if(G>=3){e-=.75;let E=te.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${E}" searched ${G}\xD7 with different patterns (file already in context)`)}{let E=new Set,P=new Set,W=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let O of o){if(O.name==="write_file"&&O.input?.path){let R=O.input.path.split("/").pop(),Q=O.input.path.includes("/tests/");W.test(R)&&!Q&&E.add(O.input.path)}if((O.name==="bash"||O.name==="ssh_exec")&&O.input?.command){let R=O.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(R)for(let Q of R){let N=Q.split(/\s+/),U=N[N.length-1];for(let F of E)(F.endsWith(U)||U.endsWith(F.split("/").pop()))&&P.add(F)}}}let oe=P.size;if(oe>=1){let O=Math.min(oe*.25,.5);e-=O;let R=[...P].map(Q=>Q.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${R} \u2014 write inline logic or use tests/ instead`)}}let ge=s.filter(E=>E.content.startsWith("EXIT")).length;ge>=10?(e-=1,n.push(`Bash exit-error storm: ${ge} tool results started with EXIT (repeated failing commands)`)):ge>=5&&(e-=.5,n.push(`Repeated bash errors: ${ge} tool results with non-zero exit code`));for(let E of t){if(E.role!=="assistant")continue;let P="";if(typeof E.content=="string"?P=E.content:Array.isArray(E.content)&&(P=E.content.filter(U=>U&&(U.type==="text"||typeof U=="string")).map(U=>typeof U=="string"?U:U.text||"").join("")),P.length<=5e3)continue;let W=P.split(/(?<=\. )/).filter(U=>U.trim().length>0);if(W.length<6)continue;let oe=new Map;for(let U=0;U<=W.length-3;U++){let F=W.slice(U,U+3).join("").trim();F.length>30&&oe.set(F,(oe.get(F)||0)+1)}let O=0,R="";for(let[U,F]of oe)F>O&&(O=F,R=U);if(O<3)continue;let N=R.length*O/P.length;if(N>=.4||O>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${O}\xD7 same paragraph, ${Math.round(N*100)}% repeated)`);break}}{let E=new Set(["read_file","list_directory","search_files","glob","grep"]),P=t.some(oe=>Array.isArray(oe.tool_calls)?oe.tool_calls.some(O=>E.has(O.function?.name)):Array.isArray(oe.content)?oe.content.some(O=>O.type==="tool_use"&&E.has(O.name)):!1);t.some(oe=>oe.role==="assistant"&&typeof oe.content=="string"&&(oe.content.includes("## Steps")||oe.content.includes("/plan approve")))&&!P&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let xe=s.filter(E=>E.content.startsWith("BLOCKED:")&&!E.content.includes("BLOCKED: sed -n")&&!E.content.includes("SSH paused")&&!E.content.includes("SSH temporarily paused"));if(xe.length>0){let E=Math.min(xe.length*.5,1.5);e-=E,n.push(`${xe.length} tool call${xe.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Ne=t.filter(E=>{let P=typeof E.content=="string"?E.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(P)}).length;if(Ne>0){let E=Math.min(Ne*1,2);e-=E,n.push(`Super-nuclear context wipe fired ${Ne}\xD7 (context collapse \u2014 task too large or read loops)`)}{let E=!1,P=!1,W=!1;for(let O of o){if(O.name!=="bash")continue;let R=(O.input?.command||O.input?.cmd||"").trim();!(/cat\s*>/.test(R)||/<</.test(R))&&/\bcat\s+\S/.test(R)&&(E=!0),/^\s*ls(\s|$)/.test(R)&&!/npm|yarn|pnpm|make|git\b/.test(R)&&(P=!0),/\bfind\s+\S/.test(R)&&!/git\b|npm\b|-exec\b/.test(R)&&(W=!0)}let oe=[E,P,W].filter(Boolean).length;if(oe>0){let O=Math.min(oe*.25,.75);e-=O;let R=[];E&&R.push("cat (use read_file)"),P&&R.push("ls (use list_directory)"),W&&R.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${R.join(", ")}`)}}{let E=o.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"))),P=o.some(R=>(R.name==="write_file"||R.name==="Write")&&R.input?.path&&R.input.path.endsWith("package.json")),W=o.filter(R=>(R.name==="bash"||R.name==="Bash")&&R.input?.command).map(R=>R.input.command),oe=W.some(R=>/pip\s+install|python\s+-m\s+venv/.test(R)),O=W.some(R=>/npm\s+install/.test(R));E&&!oe?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):P&&!O&&o.some(Q=>(Q.name==="write_file"||Q.name==="Write")&&Q.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(Q.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(f){let E=t.find(R=>R.role==="assistant"),P="";E&&(typeof E.content=="string"?P=E.content:Array.isArray(E.content)&&(P=E.content.filter(R=>R&&(R.type==="text"||typeof R=="string")).map(R=>typeof R=="string"?R:R.text||"").join("")));let W=P.slice(0,400),oe=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,O=W.split(`
|
|
684
|
+
`)}async function VC(t){let e=ct.join(t,"package.json"),n="";if(await Kn(()=>Ut.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Ut.readFile(e,"utf-8"),a=JSON.parse(i);n=`${a.name||"?"} v${a.version||"?"}`}catch{}let[s,r]=await Promise.all([Kn(async()=>{let{stdout:i}=await $c("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),r0()]);if(r&&r.length>0){console.log(`${tr.red} \u26A0 ${r.length} unresolved merge conflict(s):${tr.reset}`);for(let i of r)console.log(`${tr.red} ${i.file}${tr.reset}`);console.log(`${tr.yellow} \u2192 Resolve conflicts before starting tasks${tr.reset}`)}console.log()}i0.exports={gatherProjectContext:XC,printContext:VC,generateFileTree:YC,_clearContextCache:()=>{kd.clear(),sr.clear(),bc=null,nr={result:null,expiry:0,cwd:null}}}});var Mn=X((M2,l0)=>{var On=require("fs"),xc=require("path"),{atomicWrite:JC}=os();function li(){return xc.join(process.cwd(),".nex","sessions")}function Sd(){let t=li();On.existsSync(t)||On.mkdirSync(t,{recursive:!0,mode:448})}function Ed(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return xc.join(li(),`${e}.json`)}function Td(t,e,n={}){Sd();let o=Ed(t),s={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return JC(o,JSON.stringify(s,null,2)),{path:o,name:t}}function a0(t){let e=Ed(t);if(!On.existsSync(e))return null;try{return JSON.parse(On.readFileSync(e,"utf-8"))}catch{return null}}function c0(){Sd();let t=li(),e=On.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(On.readFileSync(xc.join(t,o),"utf-8"));n.push({name:s.name||o.replace(".json",""),createdAt:s.createdAt,updatedAt:s.updatedAt,messageCount:s.messageCount||0,model:s.model,provider:s.provider,score:s.score!=null?s.score:null,scoreGrade:s.scoreGrade||null})}catch{}return n.sort((o,s)=>(s.updatedAt||"").localeCompare(o.updatedAt||""))}function ZC(t){let e=Ed(t);return On.existsSync(e)?(On.unlinkSync(e),!0):!1}function QC(){let t=c0();return t.length===0?null:a0(t[0].name)}var ao=null,ps=null,ci=null;function eA(t,e={}){t.length!==0&&(ao&&clearTimeout(ao),ps=t,ci=e||{},ao=setTimeout(()=>{ps&&ps.length>0&&Td("_autosave",ps,ci),ao=null,ps=null,ci=null},5e3))}function tA(){ao&&(clearTimeout(ao),ao=null),ps&&ps.length>0&&(Td("_autosave",ps,ci),ps=null,ci=null)}function nA(){Sd();let t=li(),e=On.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,o=new Date(n.getTime()-720*60*60*1e3),s=0;for(let r of e){let i=xc.join(t,r);try{let a=On.statSync(i);new Date(a.mtime)<o&&(On.unlinkSync(i),s++)}catch{}}return s}l0.exports={saveSession:Td,loadSession:a0,listSessions:c0,deleteSession:ZC,getLastSession:QC,autoSave:eA,flushAutoSave:tA,clearOldSessions:nA,_getSessionsDir:li}});var vc=X((N2,y0)=>{"use strict";var ui=require("fs"),u0=require("path");function d0(t){let e=[];return t.forEach((n,o)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_use"&&e.push({name:s.name||"",input:s.input||{},index:o,id:s.id||null})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(s=>{let r=s.function?.name||s.name||"",i={};try{i=typeof s.function?.arguments=="string"?JSON.parse(s.function.arguments):s.function?.arguments||s.input||{}}catch{}e.push({name:r,input:i,index:o,id:s.id||null})}))}),e}function sA(t){let e=new Set;return t.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&e.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_result"&&o.tool_use_id&&typeof o.content=="string"&&o.content.startsWith("BLOCKED:")&&e.add(o.tool_use_id)})}),e}function f0(t){let e=[];return t.forEach((n,o)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{if(s&&s.type==="tool_result"){let r=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(s.content||"");e.push({content:r,index:o})}}),n.role==="tool"){let s=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:s,index:o})}}),e}function p0(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let o=n.content.filter(s=>s&&(s.type==="text"||typeof s=="string")).map(s=>typeof s=="string"?s:s.text||"").join("").trim();if(o)return o}}}return""}function h0(t,e){let n=[];for(let o=t.length-1;o>=0&&n.length<e;o--){let s=t[o];if(s.role!=="assistant")continue;let r="";typeof s.content=="string"?r=s.content.trim():Array.isArray(s.content)&&(r=s.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function m0(t){let e=new Map;for(let n of t){let o;try{o=JSON.stringify(n.input)}catch{o=String(n.input)}let s=`${n.name}|${o}`;e.set(s,(e.get(s)||0)+1)}return e}function g0(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,n=[],o=d0(t),s=f0(t),r=o.length,i=sA(t),a=o.filter(E=>!E.id||!i.has(E.id));t.some(E=>E.role==="user"&&typeof E.content=="string"&&E.content.startsWith("[SYSTEM WARNING]")&&(E.content.includes("edited")||E.content.includes("bash command")||E.content.includes("grep pattern")||E.content.includes("re-read")||E.content.includes("already in your context")))&&(e-=2,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let u=o.find(E=>{let P=E.input?.command||E.input?.cmd||"";return/\bsed\s+-n\b/.test(P)});if(u){let E=(u.input?.command||u.input?.cmd||"").slice(0,80);s.some(W=>W.content.includes("BLOCKED: sed -n is forbidden")||W.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${E}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${E}`))}o.find(E=>{if(E.name!=="grep"&&E.name!=="bash"&&E.name!=="ssh_exec")return!1;let P=E.input?.command||E.input?.cmd||"",W=E.input?.pattern||"",oe=`${P} ${W}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(oe)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(oe)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let f=t.some(E=>E.role==="assistant"),p=p0(t),h=h0(t,3).some(E=>E.length>100&&!/^[^.!]{0,40}\?$/.test(E));if(f&&!h&&(p.length<80||/^[^.!]{0,40}\?$/.test(p))){e-=2;let E=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: ${E}`)}r>40?(e-=1.5,n.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,n.push(`High tool call count: ${r} (>25 threshold)`)),t.some(E=>{let P=typeof E.content=="string"?E.content:Array.isArray(E.content)?E.content.map(W=>typeof W=="string"?W:W.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(P)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let w=m0(a),x=0,S="";for(let[E,P]of w)P>x&&(x=P,S=E);if(x>=3){let[E]=S.split("|");e-=1,n.push(`Same tool call repeated ${x}\xD7 (tool: ${E})`)}let k=!1,v=t.findIndex(E=>E.role==="user"&&typeof E.content=="string"&&E.content.includes("[SYSTEM STOP]")&&E.content.includes('"valid":true'));v>=0&&o.filter(P=>P.index>v).length>0&&(k=!0),k&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let C=o.filter(E=>E.name==="ssh_exec");if(C.length>=8){let E=0,P=1;for(let W=1;W<C.length;W++)C[W].index<=C[W-1].index+2?P++:(E=Math.max(E,P),P=1);E=Math.max(E,P),E>=8&&(e-=.5,n.push(`SSH reconnect storm: ${E} 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 q=new Map;for(let E of a)if(E.name==="read_file"&&E.input?.path){let P=E.input.path;q.has(P)||q.set(P,{count:0,ranges:[]});let W=q.get(P);if(W.count++,E.input.line_start!=null){let oe=E.input.line_start||1,O=E.input.line_end||oe+350;W.ranges.push([oe,O])}}function D(E,P,W){for(let[oe,O]of W){let R=Math.max(E,oe),Q=Math.min(P,O);if(Q>R){let N=Q-R,U=P-E||1;if(N/U>=.7)return!0}}return!1}let ee=0,ue="";for(let[E,P]of q){if(P.count<3)continue;if(P.ranges.length===P.count){let O=!1,R=[];for(let[Q,N]of P.ranges){if(R.length>0&&D(Q,N,R)){O=!0;break}R.push([Q,N])}if(!O)continue}if(P.count-P.ranges.length<=2&&P.ranges.length>=1){let O=!1,R=[];for(let[Q,N]of P.ranges){if(R.length>0&&D(Q,N,R)){O=!0;break}R.push([Q,N])}if(!O)continue}P.count>ee&&(ee=P.count,ue=E)}if(ee>=3){e-=1;let E=ue.split("/").slice(-2).join("/");n.push(`read_file loop: "${E}" read ${ee}\xD7 (file already in context)`)}let le=0,de="";for(let[E,P]of q){if(P.ranges.length<4)continue;let W=[],oe=!1;for(let[O,R]of P.ranges){if(W.length>0&&D(O,R,W)){oe=!0;break}W.push([O,R])}!oe&&P.ranges.length>le&&(le=P.ranges.length,de=E)}if(le>=4){e-=.5;let E=de.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${E}" read in ${le} sequential sections \u2014 use grep instead`)}let M=new Map;for(let E of a)if(E.name==="grep"&&E.input?.path&&E.input?.pattern){let P=E.input.path;M.has(P)||M.set(P,new Set),M.get(P).add(E.input.pattern)}let G=0,te="";for(let[E,P]of M)E.split("/").pop().includes(".")&&P.size>G&&(G=P.size,te=E);if(G>=3){e-=.75;let E=te.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${E}" searched ${G}\xD7 with different patterns (file already in context)`)}{let E=new Set,P=new Set,W=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let O of o){if(O.name==="write_file"&&O.input?.path){let R=O.input.path.split("/").pop(),Q=O.input.path.includes("/tests/");W.test(R)&&!Q&&E.add(O.input.path)}if((O.name==="bash"||O.name==="ssh_exec")&&O.input?.command){let R=O.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(R)for(let Q of R){let N=Q.split(/\s+/),U=N[N.length-1];for(let F of E)(F.endsWith(U)||U.endsWith(F.split("/").pop()))&&P.add(F)}}}let oe=P.size;if(oe>=1){let O=Math.min(oe*.25,.5);e-=O;let R=[...P].map(Q=>Q.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${R} \u2014 write inline logic or use tests/ instead`)}}let ge=s.filter(E=>E.content.startsWith("EXIT")).length;ge>=10?(e-=1,n.push(`Bash exit-error storm: ${ge} tool results started with EXIT (repeated failing commands)`)):ge>=5&&(e-=.5,n.push(`Repeated bash errors: ${ge} tool results with non-zero exit code`));for(let E of t){if(E.role!=="assistant")continue;let P="";if(typeof E.content=="string"?P=E.content:Array.isArray(E.content)&&(P=E.content.filter(U=>U&&(U.type==="text"||typeof U=="string")).map(U=>typeof U=="string"?U:U.text||"").join("")),P.length<=5e3)continue;let W=P.split(/(?<=\. )/).filter(U=>U.trim().length>0);if(W.length<6)continue;let oe=new Map;for(let U=0;U<=W.length-3;U++){let F=W.slice(U,U+3).join("").trim();F.length>30&&oe.set(F,(oe.get(F)||0)+1)}let O=0,R="";for(let[U,F]of oe)F>O&&(O=F,R=U);if(O<3)continue;let N=R.length*O/P.length;if(N>=.4||O>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${O}\xD7 same paragraph, ${Math.round(N*100)}% repeated)`);break}}{let E=new Set(["read_file","list_directory","search_files","glob","grep"]),P=t.some(oe=>Array.isArray(oe.tool_calls)?oe.tool_calls.some(O=>E.has(O.function?.name)):Array.isArray(oe.content)?oe.content.some(O=>O.type==="tool_use"&&E.has(O.name)):!1);t.some(oe=>oe.role==="assistant"&&typeof oe.content=="string"&&(oe.content.includes("## Steps")||oe.content.includes("/plan approve")))&&!P&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let xe=s.filter(E=>E.content.startsWith("BLOCKED:")&&!E.content.includes("BLOCKED: sed -n")&&!E.content.includes("SSH paused")&&!E.content.includes("SSH temporarily paused"));if(xe.length>0){let E=Math.min(xe.length*.5,1.5);e-=E,n.push(`${xe.length} tool call${xe.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Ne=t.filter(E=>{let P=typeof E.content=="string"?E.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(P)}).length;if(Ne>0){let E=Math.min(Ne*1,2);e-=E,n.push(`Super-nuclear context wipe fired ${Ne}\xD7 (context collapse \u2014 task too large or read loops)`)}{let E=!1,P=!1,W=!1;for(let O of o){if(O.name!=="bash")continue;let R=(O.input?.command||O.input?.cmd||"").trim();!(/cat\s*>/.test(R)||/<</.test(R))&&/\bcat\s+\S/.test(R)&&(E=!0),/^\s*ls(\s|$)/.test(R)&&!/npm|yarn|pnpm|make|git\b/.test(R)&&(P=!0),/\bfind\s+\S/.test(R)&&!/git\b|npm\b|-exec\b/.test(R)&&(W=!0)}let oe=[E,P,W].filter(Boolean).length;if(oe>0){let O=Math.min(oe*.25,.75);e-=O;let R=[];E&&R.push("cat (use read_file)"),P&&R.push("ls (use list_directory)"),W&&R.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${R.join(", ")}`)}}{let E=o.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"))),P=o.some(R=>(R.name==="write_file"||R.name==="Write")&&R.input?.path&&R.input.path.endsWith("package.json")),W=o.filter(R=>(R.name==="bash"||R.name==="Bash")&&R.input?.command).map(R=>R.input.command),oe=W.some(R=>/pip\s+install|python\s+-m\s+venv/.test(R)),O=W.some(R=>/npm\s+install/.test(R));E&&!oe?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):P&&!O&&o.some(Q=>(Q.name==="write_file"||Q.name==="Write")&&Q.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(Q.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(f){let E=t.find(R=>R.role==="assistant"),P="";E&&(typeof E.content=="string"?P=E.content:Array.isArray(E.content)&&(P=E.content.filter(R=>R&&(R.type==="text"||typeof R=="string")).map(R=>typeof R=="string"?R:R.text||"").join("")));let W=P.slice(0,400),oe=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,O=W.split(`
|
|
685
685
|
`).find(R=>{let Q=R.trim();return Q.length>0&&Q.length<=30&&/^\d/.test(Q)&&/=/.test(Q)&&!/[a-zA-Z]/.test(Q)});if(oe.test(W)||O){e-=1.5;let R=(O||W.split(`
|
|
686
686
|
`)[0]).trim().slice(0,40);n.push(`Thinking-chain leak: non-sequitur artifact at response start: "${R}"`)}}if(f&&r>0){let E=t.findIndex(W=>W.role==="assistant"),P=t.findIndex(W=>!!(Array.isArray(W.tool_calls)&&W.tool_calls.length>0||Array.isArray(W.content)&&W.content.some(oe=>oe&&oe.type==="tool_use")));if(E!==-1&&P!==-1&&E<P){let W=t[E],oe="";typeof W.content=="string"?oe=W.content:Array.isArray(W.content)&&(oe=W.content.filter(Q=>Q&&(Q.type==="text"||typeof Q=="string")).map(Q=>typeof Q=="string"?Q:Q.text||"").join(""));let O=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(oe),R=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(oe);(O||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 E=p;if(E.length>100){let W=(E.match(/^```/gm)||[]).length%2!==0,oe=/"\s*:\s*$/.test(E.trimEnd()),O=/[,\[{]\s*$/.test(E.trimEnd());(W||oe||O)&&(e-=.75,n.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let E=[];t.forEach((W,oe)=>{let O=[];Array.isArray(W.tool_calls)&&W.tool_calls.forEach(R=>{if((R.function?.name||R.name||"")==="read_file"){let N={};try{N=typeof R.function?.arguments=="string"?JSON.parse(R.function.arguments):R.function?.arguments||{}}catch{}(N.path||"").endsWith(".json")&&O.push({id:R.id,path:N.path})}}),Array.isArray(W.content)&&W.content.forEach(R=>{R&&R.type==="tool_use"&&R.name==="read_file"&&(R.input?.path||"").endsWith(".json")&&O.push({id:R.id,path:R.input.path})}),O.forEach(R=>E.push({...R,msgIdx:oe}))});let P=0;for(let W of E){let oe=null;for(let R of t){if(R.role==="tool"&&R.tool_call_id===W.id&&typeof R.content=="string"){oe=R.content;break}if(R.role==="user"&&Array.isArray(R.content)){let Q=R.content.find(N=>N&&N.type==="tool_result"&&N.tool_use_id===W.id);if(Q){oe=typeof Q.content=="string"?Q.content:"";break}}}if(!oe)continue;oe.split(`
|
|
687
|
-
`).filter(R=>R.trim()).length<5&&/^\s*\[/.test(oe)&&!/\]\s*$/.test(oe.trimEnd())&&P++}P>=1&&(e-=.75,n.push(`Shallow JSON read: ${P} .json file${P>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let E=s.filter(P=>/argument errors?/i.test(P.content)||/missing required (argument|parameter)/i.test(P.content)||/invalid argument/i.test(P.content));E.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${E.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):E.length>=2&&(e-=.25,n.push(`Tool argument errors: ${E.length} tool calls returned argument errors`))}{let E=!1,P=0,W=0;for(let oe of a){if((oe.name==="bash"||oe.name==="Bash")&&oe.input?.command&&/git\s+commit\b/.test(oe.input.command)){E&&(W=Math.max(W,P)),E=!0,P=0;continue}E&&(oe.name==="bash"||oe.name==="Bash")&&oe.input?.command&&/git\s+(status|diff|log|show)\b/.test(oe.input.command)&&P++}W=Math.max(W,P),W>=3&&(e-=.75,n.push(`Post-commit verification waste: ${W} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let Ae=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",ke=n.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${n.length} issue${n.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:Ae,issues:n,summary:ke}}function oA(t){try{let{loadSession:e}=Mn(),n=e(t);return n?
|
|
687
|
+
`).filter(R=>R.trim()).length<5&&/^\s*\[/.test(oe)&&!/\]\s*$/.test(oe.trimEnd())&&P++}P>=1&&(e-=.75,n.push(`Shallow JSON read: ${P} .json file${P>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let E=s.filter(P=>/argument errors?/i.test(P.content)||/missing required (argument|parameter)/i.test(P.content)||/invalid argument/i.test(P.content));E.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${E.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):E.length>=2&&(e-=.25,n.push(`Tool argument errors: ${E.length} tool calls returned argument errors`))}{let E=!1,P=0,W=0;for(let oe of a){if((oe.name==="bash"||oe.name==="Bash")&&oe.input?.command&&/git\s+commit\b/.test(oe.input.command)){E&&(W=Math.max(W,P)),E=!0,P=0;continue}E&&(oe.name==="bash"||oe.name==="Bash")&&oe.input?.command&&/git\s+(status|diff|log|show)\b/.test(oe.input.command)&&P++}W=Math.max(W,P),W>=3&&(e-=.75,n.push(`Post-commit verification waste: ${W} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let Ae=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",ke=n.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${n.length} issue${n.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:Ae,issues:n,summary:ke}}function oA(t){try{let{loadSession:e}=Mn(),n=e(t);return n?g0(n.messages||[]):null}catch{return null}}function rA(t,e=null){let{score:n,issues:o}=t,s=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(n>=8||o.length===0)return"";let a=o.map(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})`),`
|
|
688
688
|
${s}${p}${r}`}let c="";for(let d of a.slice(0,4))c+=`
|
|
689
689
|
${i}\u26A0${r} ${s}${d}${r}`;let u=a.length-4;return u>0&&(c+=`
|
|
690
|
-
${s}(+${u} more)${r}`),c}function iA(t,e={}){try{let n=
|
|
690
|
+
${s}(+${u} more)${r}`),c}function iA(t,e={}){try{let n=u0.join(process.cwd(),".nex");ui.existsSync(n)||ui.mkdirSync(n,{recursive:!0});let o=u0.join(n,"benchmark-history.json"),s=[];if(ui.existsSync(o))try{s=JSON.parse(ui.readFileSync(o,"utf-8"))}catch{s=[]}Array.isArray(s)||(s=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};s.push(i),s.length>100&&(s=s.slice(s.length-100)),ui.writeFileSync(o,JSON.stringify(s,null,2))}catch{}}y0.exports={scoreMessages:g0,scoreSession:oA,formatScore:rA,appendScoreHistory:iA,_extractToolCalls:d0,_extractToolResults:f0,_getLastAssistantText:p0,_getLastNAssistantTexts:h0,_countDuplicateToolCalls:m0}});var Xn=X((P2,x0)=>{"use strict";var aA=require("os"),Rd=require("path"),Rs=require("fs"),di=Rd.join(aA.homedir(),".nex-code","model-routing.json"),kc={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}},$0=["agentic","frontend","sysadmin","data","coding"];function cA(t){if(!t||t.length<8)return null;for(let e of $0){let n=kc[e];if(!n.pattern||n.pattern.test(t))return n}return kc.coding}function fi(){try{if(Rs.existsSync(di))return JSON.parse(Rs.readFileSync(di,"utf-8"))}catch{}return{}}function w0(t){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let e=kc[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:fi()[t]||null}var b0={explore:10,plan:10,implement:35,verify:8},Cd={explore:"devstral-small-2:24b",plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function _0(){let t=fi();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=Xe();if(e()==="ollama")return Cd}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Cd:null}function lA(t,e){if(process.env.NEX_FORCE_MODEL)return process.env.NEX_FORCE_MODEL;let n=_0();return n?.[t]?n[t]:e?w0(e):null}function uA(t){return fi().phaseBudgets?.[t]||b0[t]||20}function dA(){return process.env.NEX_PHASE_ROUTING==="0"||process.env.NEX_FORCE_MODEL?!1:_0()!==null}function fA(t){let e=Rd.dirname(di);Rs.existsSync(e)||Rs.mkdirSync(e,{recursive:!0});let n=fi(),o={...n,...t};!t.phases&&n.phases&&(o.phases=n.phases),!t.phaseBudgets&&n.phaseBudgets&&(o.phaseBudgets=n.phaseBudgets),Rs.writeFileSync(di,JSON.stringify(o,null,2));try{let s=Rd.join(e,".env"),r="";Rs.existsSync(s)&&(r=Rs.readFileSync(s,"utf-8"));let i=r.split(/\r?\n/),a=(c,u)=>{let d=i.findIndex(f=>f.startsWith(c+"="));d>=0?i[d]=`${c}=${u}`:i.push(`${c}=${u}`)};o.coding&&a("NEX_ROUTE_CODING",o.coding),o.frontend&&a("NEX_ROUTE_FRONTEND",o.frontend),o.sysadmin&&a("NEX_ROUTE_SYSADMIN",o.sysadmin),o.data&&a("NEX_ROUTE_DATA",o.data),o.agentic&&a("NEX_ROUTE_AGENTIC",o.agentic),o.phases&&(o.phases.plan&&a("NEX_PHASE_PLAN_MODEL",o.phases.plan),o.phases.implement&&a("NEX_PHASE_IMPLEMENT_MODEL",o.phases.implement),o.phases.verify&&a("NEX_PHASE_VERIFY_MODEL",o.phases.verify)),Rs.writeFileSync(s,i.filter(c=>c.trim()!=="").join(`
|
|
691
691
|
`)+`
|
|
692
|
-
`)}catch{}}
|
|
692
|
+
`)}catch{}}x0.exports={CATEGORIES:kc,DETECTION_ORDER:$0,detectCategory:cA,getModelForCategory:w0,getModelForPhase:lA,getPhaseBudget:uA,isPhaseRoutingEnabled:dA,DEFAULT_PHASE_BUDGETS:b0,BUILTIN_PHASE_DEFAULTS:Cd,saveRoutingConfig:fA,loadRoutingConfig:fi,ROUTING_CONFIG_PATH:di}});var E0=X((L2,S0)=>{"use strict";var co=require("fs"),pi=require("path"),pA=require("os"),{detectCategory:hA}=Xn(),or=pi.join(pA.homedir(),".nex-code","examples"),Ad=pi.join(__dirname,"..","examples");function v0(t){try{let n=co.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),o=n.match(/^user:\s*(.+)$/m);if(!o)return null;let s=o[1].trim(),r=n.indexOf(`
|
|
693
693
|
A: |`);if(r===-1)return null;let i=n.slice(r+5),a=[],c=0;for(let d of i.split(`
|
|
694
694
|
`))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(`
|
|
695
|
-
`).trim();return{user:s,assistant:u}}catch{return null}}function
|
|
695
|
+
`).trim();return{user:s,assistant:u}}catch{return null}}function k0(t){let e=`${t}.md`,n=pi.join(or,e);if(co.existsSync(n)){let s=v0(n);if(s)return s}let o=pi.join(Ad,e);return co.existsSync(o)?v0(o):null}function mA(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=hA(t);return!e||e.id==="coding"&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port)\b/i.test(t)?null:k0(e.id)}function gA(){let t=new Set;for(let e of[or,Ad])try{for(let n of co.readdirSync(e))n.endsWith(".md")&&t.add(n.replace(".md",""))}catch{}return[...t].sort()}function yA(t,e){co.existsSync(or)||co.mkdirSync(or,{recursive:!0});let n=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
|
|
696
696
|
|
|
697
697
|
user: ${e.user}
|
|
698
698
|
|
|
@@ -700,14 +700,14 @@ A: |
|
|
|
700
700
|
${e.assistant.split(`
|
|
701
701
|
`).map(o=>` ${o}`).join(`
|
|
702
702
|
`)}
|
|
703
|
-
`;co.writeFileSync(pi.join(or,`${t}.md`),n,"utf-8")}
|
|
703
|
+
`;co.writeFileSync(pi.join(or,`${t}.md`),n,"utf-8")}S0.exports={getFewShotForInput:mA,loadExampleForCategory:k0,listAvailableExamples:gA,savePrivateExample:yA,PRIVATE_EXAMPLES_DIR:or,BUNDLED_EXAMPLES_DIR:Ad}});var mi=X((j2,O0)=>{var sn=require("fs"),rr=require("path"),{C:I2}=He(),{atomicWrite:$A,withFileLockSync:wA}=os(),Sc={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"},ir={...Sc};function T0(){let t=rr.join(process.cwd(),".nex","config.json");if(sn.existsSync(t))try{let e=JSON.parse(sn.readFileSync(t,"utf-8"));e.permissions&&(ir={...Sc,...e.permissions})}catch{}}function bA(){let t=rr.join(process.cwd(),".nex"),e=rr.join(t,"config.json");sn.existsSync(t)||sn.mkdirSync(t,{recursive:!0}),wA(e,()=>{let n={};if(sn.existsSync(e))try{n=JSON.parse(sn.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=ir,$A(e,JSON.stringify(n,null,2))})}function R0(t){return ir[t]||"ask"}function _A(t,e){return["allow","ask","deny"].includes(e)?(ir[t]=e,!0):!1}function xA(t){return R0(t)}function vA(){return Object.entries(ir).map(([t,e])=>({tool:t,mode:e}))}function kA(){ir={...Sc}}var hi={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 C0(){let t=rr.join(process.cwd(),".nex","config.json");try{return sn.existsSync(t)&&JSON.parse(sn.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function SA(t){let e=rr.join(process.cwd(),".nex"),n=rr.join(e,"config.json");sn.existsSync(e)||sn.mkdirSync(e,{recursive:!0});let o={};try{sn.existsSync(n)&&(o=JSON.parse(sn.readFileSync(n,"utf-8")))}catch{o={}}o.teamPermissions=t,sn.writeFileSync(n,JSON.stringify(o,null,2),"utf-8")}function A0(){let t=C0();if(!t)return hi.admin;let e=t.role||"admin",n=hi[e]||hi.admin;return{...n,...t.overrides,blockedTools:[...n.blockedTools||[],...t.overrides?.blockedTools||[]]}}function EA(t){let e=A0();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 TA(){return Object.entries(hi).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}T0();O0.exports={getPermission:R0,setPermission:_A,checkPermission:xA,listPermissions:vA,loadPermissions:T0,savePermissions:bA,resetPermissions:kA,DEFAULT_PERMISSIONS:Sc,PERMISSION_PRESETS:hi,loadPresetConfig:C0,savePresetConfig:SA,getEffectivePreset:A0,isToolAllowed:EA,listPresets:TA}});var Nn=X((q2,I0)=>{var uo=require("fs"),Ec=require("path"),D2=require("readline"),{C:Ge}=He(),Ue=null,Md=!1,Nd=null,M0=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Tc(){return Ec.join(process.cwd(),".nex","plans")}function N0(){let t=Tc();uo.existsSync(t)||uo.mkdirSync(t,{recursive:!0})}function RA(t,e=[]){return Ue={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()},Ue}function CA(){return Ue}function AA(t){Md=t}function OA(){return Md}function MA(){return!Ue||Ue.status!=="draft"?!1:(Ue.status="approved",Ue.updatedAt=new Date().toISOString(),!0)}function NA(){return!Ue||Ue.status!=="approved"?!1:(Ue.status="executing",!0)}function Od(t,e){return!Ue||t<0||t>=Ue.steps.length?!1:(Ue.steps[t].status=e,Ue.updatedAt=new Date().toISOString(),Ue.steps.every(n=>n.status==="done"||n.status==="skipped")&&(Ue.status="completed"),!0)}function PA(t){if(!t)return`${Ge.dim}No active plan${Ge.reset}`;let e={draft:`${Ge.yellow}DRAFT${Ge.reset}`,approved:`${Ge.green}APPROVED${Ge.reset}`,executing:`${Ge.blue}EXECUTING${Ge.reset}`,completed:`${Ge.green}COMPLETED${Ge.reset}`},n=[];n.push(`
|
|
704
704
|
${Ge.bold}${Ge.cyan}Plan: ${t.task}${Ge.reset}`),n.push(`${Ge.dim}Status: ${e[t.status]||t.status}${Ge.reset}
|
|
705
705
|
`);for(let o=0;o<t.steps.length;o++){let s=t.steps[o],r;switch(s.status){case"done":r=`${Ge.green}\u2713${Ge.reset}`;break;case"in_progress":r=`${Ge.blue}\u2192${Ge.reset}`;break;case"skipped":r=`${Ge.dim}\u25CB${Ge.reset}`;break;default:r=`${Ge.dim} ${Ge.reset}`}n.push(` ${r} ${Ge.bold}Step ${o+1}:${Ge.reset} ${s.description}`),s.files.length>0&&n.push(` ${Ge.dim}Files: ${s.files.join(", ")}${Ge.reset}`)}return n.push(""),n.join(`
|
|
706
|
-
`)}function LA(t){if(t||(t=Ue),!t)return null;
|
|
706
|
+
`)}function LA(t){if(t||(t=Ue),!t)return null;N0();let e=Ec.join(Tc(),`${t.name}.json`);return uo.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function IA(t){let e=Ec.join(Tc(),`${t}.json`);if(!uo.existsSync(e))return null;try{let n=JSON.parse(uo.readFileSync(e,"utf-8"));return Ue=n,n}catch{return null}}function jA(){N0();let t=Tc(),e=uo.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(uo.readFileSync(Ec.join(t,o),"utf-8"));n.push({name:s.name,task:s.task,status:s.status,steps:s.steps?s.steps.length:0,createdAt:s.createdAt})}catch{}return n.sort((o,s)=>(s.createdAt||"").localeCompare(o.createdAt||""))}function DA(t){if(!t)return[];let e=[],n=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),o=n?n[1]:t,s=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=s.exec(o))!==null;){let a=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let a=r[1].replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,a=[...t.matchAll(i)];for(let 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 qA(t){Nd=t}function FA(){return Nd}function BA(){Ue=null,Md=!1,Nd=null,GA()}function UA(){return`
|
|
707
707
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
708
708
|
|
|
709
709
|
# Allowed Tools (read-only)
|
|
710
|
-
You may ONLY use these tools: ${[...
|
|
710
|
+
You may ONLY use these tools: ${[...M0].join(", ")}
|
|
711
711
|
Any other tool call will be blocked and returned with an error.
|
|
712
712
|
|
|
713
713
|
# MANDATORY: Read Before You Plan
|
|
@@ -759,14 +759,14 @@ Bullet list of potential issues and mitigations.
|
|
|
759
759
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
760
760
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
761
761
|
- Do NOT make any file changes \u2014 your role is analysis and planning only.
|
|
762
|
-
- 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 lo=0;function WA(){!Ue||Ue.status!=="executing"||(lo>0&&Od(lo-1,"done"),lo<Ue.steps.length&&(Od(lo,"in_progress"),lo++))}function HA(){if(!Ue||Ue.status!=="executing"||Ue.steps.length===0)return null;let t=Math.min(lo,Ue.steps.length),e=Ue.steps.length,n=Math.max(0,t-1),o=Ue.steps[n]?.description||"";return{current:t,total:e,description:o}}function GA(){lo=0}var
|
|
763
|
-
`),n=[],o=!1,s="";for(let r of e){let i=
|
|
764
|
-
`)}function on(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function fo(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 Ld(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?
|
|
762
|
+
- 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 lo=0;function WA(){!Ue||Ue.status!=="executing"||(lo>0&&Od(lo-1,"done"),lo<Ue.steps.length&&(Od(lo,"in_progress"),lo++))}function HA(){if(!Ue||Ue.status!=="executing"||Ue.steps.length===0)return null;let t=Math.min(lo,Ue.steps.length),e=Ue.steps.length,n=Math.max(0,t-1),o=Ue.steps[n]?.description||"";return{current:t,total:e,description:o}}function GA(){lo=0}var P0=["interactive","semi-auto","autonomous"],L0="interactive";function YA(t){return P0.includes(t)?(L0=t,!0):!1}function zA(){return L0}I0.exports={createPlan:RA,getActivePlan:CA,setPlanMode:AA,isPlanMode:OA,approvePlan:MA,startExecution:NA,updateStep:Od,formatPlan:PA,savePlan:LA,loadPlan:IA,listPlans:jA,clearPlan:BA,getPlanModePrompt:UA,setPlanContent:qA,getPlanContent:FA,extractStepsFromText:DA,advancePlanStep:WA,getPlanStepInfo:HA,PLAN_MODE_ALLOWED_TOOLS:M0,setAutonomyLevel:YA,getAutonomyLevel:zA,AUTONOMY_LEVELS:P0}});var z0=X((F2,Y0)=>{var{C:A}=He();function j0(){return Math.max(10,(process.stdout.columns||80)-2)}function KA(t){if(!t)return"";let e=t.split(`
|
|
763
|
+
`),n=[],o=!1,s="";for(let r of e){let i=j0();if(r.trim().startsWith("```")){if(o)n.push(`${A.dim}${"\u2500".repeat(40)}${A.reset}`),o=!1,s="";else{o=!0,s=r.trim().substring(3).trim();let a=s?` ${s} `:"";n.push(`${A.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${A.reset}`)}continue}if(o){n.push(` ${Ld(r,s)}`);continue}if(r.startsWith("###### ")){n.push(`${A.bold}${A.cyan} ${on(r.substring(7))}${A.reset}`);continue}if(r.startsWith("##### ")){n.push(`${A.bold}${A.cyan} ${on(r.substring(6))}${A.reset}`);continue}if(r.startsWith("#### ")){n.push(`${A.bold}${A.cyan} ${on(r.substring(5))}${A.reset}`);continue}if(r.startsWith("### ")){n.push(`${A.bold}${A.cyan} ${on(r.substring(4))}${A.reset}`);continue}if(r.startsWith("## ")){n.push(`${A.bold}${A.cyan} ${on(r.substring(3))}${A.reset}`);continue}if(r.startsWith("# ")){n.push(`${A.bold}${A.cyan}${on(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} ${fo(c)}`;n.push(po(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} ${fo(d)}`,p=c+" ".repeat(u.length+2);n.push(po(f,i,p));continue}}n.push(po(fo(r),i))}return n.join(`
|
|
764
|
+
`)}function on(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function fo(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 Ld(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?D0(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?q0(t):e==="json"||e==="jsonc"?F0(t):e==="python"||e==="py"?B0(t):e==="go"||e==="golang"?U0(t):e==="rust"||e==="rs"?W0(t):e==="css"||e==="scss"||e==="less"?H0(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?G0(t):t:""}function D0(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,s=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(s,`${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(o,`${A.dim}$1${A.reset}`),r}function q0(t){let e=/^(\s*)([\w-]+)/,n=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(#.*$)/,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(o,`${A.yellow}$&${A.reset}`),r=r.replace(s,`${A.dim}$1${A.reset}`),r}function F0(t){let e=/("[\w-]+")\s*:/g,n=/:\s*("(?:[^"\\]|\\.)*")/g,o=/:\s*(\d+\.?\d*)/g,s=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${A.cyan}$1${A.reset}:`),r=r.replace(n,`: ${A.green}$1${A.reset}`),r=r.replace(o,`: ${A.yellow}$1${A.reset}`),r=r.replace(s,`: ${A.magenta}$1${A.reset}`),r}function B0(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,n=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,o=/(#.*$)/,s=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(s,`${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(o,`${A.dim}$1${A.reset}`),i}function U0(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,n=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,o=/(["'`])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${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(o,`${A.green}$&${A.reset}`),i=i.replace(s,`${A.dim}$1${A.reset}`),i}function W0(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,n=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,a=t;return a=a.replace(r,`${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(o,`${A.green}$&${A.reset}`),a=a.replace(s,`${A.dim}$1${A.reset}`),a}function H0(t){let e=/^(\s*)([\w-]+)\s*:/,n=/:\s*([^;]+)/,o=/^(\s*[.#@][\w-]+)/,s=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,a=t;return a=a.replace(i,`${A.yellow}$1${A.reset}`),a=a.replace(s,`${A.yellow}$1${A.reset}`),a=a.replace(e,`$1${A.cyan}$2${A.reset}:`),a=a.replace(o,`$1${A.magenta}$&${A.reset}`),a=a.replace(r,`${A.dim}$1${A.reset}`),a}function G0(t){let e=/<\/?(\w[\w-]*)/g,n=/\s([\w-]+)=/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(s,`${A.dim}$1${A.reset}`),i=i.replace(o,`${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 po(t,e,n=""){if(!e||e<10)return t;let o="",s=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),s++,s>e&&r!==-1){o+=t.slice(a,r)+`
|
|
765
765
|
`+n,a=r+1,i=a,s=n.length,r=-1;continue}s>e&&r===-1&&(o+=t.slice(a,i)+`
|
|
766
766
|
`+n,a=i,s=n.length+1),i++}return o+=t.slice(a),o}function XA(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)}),o=n.map(i=>"\u2500".repeat(i+2)).join("\u253C"),s=t.map((i,a)=>` ${A.bold}${i.padEnd(n[a])}${A.reset} `).join("\u2502"),r=[];r.push(`${A.dim}\u250C${o.replace(/┼/g,"\u252C")}\u2510${A.reset}`),r.push(`${A.dim}\u2502${A.reset}${s}${A.dim}\u2502${A.reset}`),r.push(`${A.dim}\u251C${o}\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${o.replace(/┼/g,"\u2534")}\u2518${A.reset}`),r.join(`
|
|
767
767
|
`)}function VA(t,e,n,o=30){let s=n>0?Math.round(e/n*100):0,r=Math.round(s/100*o),i=o-r,a=s>=100?A.green:s>50?A.yellow:A.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${A.dim}${"\u2591".repeat(i)}${A.reset} ${s}% (${e}/${n})`}var Pd=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}_cursorWrite(e){try{process.stderr.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let n=[0,1,2,3,4,3,2,1],o=n[this._cursorFrame%n.length],s="";for(let r=0;r<5;r++)s+=r===o?`${Lt().T.cyan}\u25CF${Lt().T.reset}`:" ";this._cursorWrite(`\x1B[2K\r${s}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let n;for(;(n=this.buffer.indexOf(`
|
|
768
768
|
`))!==-1;){let o=this.buffer.substring(0,n);this.buffer=this.buffer.substring(n+1),this._renderLine(o)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${A.dim}${"\u2500".repeat(40)}${A.reset}
|
|
769
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=
|
|
769
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=j0();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${A.dim}${"\u2500".repeat(40)}${A.reset}
|
|
770
770
|
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${A.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${A.reset}
|
|
771
771
|
`)}return}if(this.inCodeBlock){this._safeWrite(` ${Ld(e,this.codeBlockLang)}
|
|
772
772
|
`);return}if(e.startsWith("###### ")){this._safeWrite(`${A.bold}${A.cyan} ${on(e.substring(7))}${A.reset}
|
|
@@ -778,7 +778,7 @@ Bullet list of potential issues and mitigations.
|
|
|
778
778
|
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${s}${A.cyan}\u2022${A.reset} ${fo(r)}`,a=po(i,n,s+" ");this._safeWrite(`${a}
|
|
779
779
|
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){let r=s[1],i=s[2],a=s[3],c=`${r}${A.cyan}${i}.${A.reset} ${fo(a)}`,u=r+" ".repeat(i.length+2),d=po(c,n,u);this._safeWrite(`${d}
|
|
780
780
|
`);return}}let o=po(fo(e),n);this._safeWrite(`${o}
|
|
781
|
-
`)}};
|
|
781
|
+
`)}};Y0.exports={renderMarkdown:KA,renderInline:fo,stripHeadingMarkers:on,highlightCode:Ld,highlightJS:D0,highlightBash:q0,highlightJSON:F0,highlightPython:B0,highlightGo:U0,highlightRust:W0,highlightCSS:H0,highlightHTML:G0,renderTable:XA,renderProgress:VA,wrapAnsi:po,StreamRenderer:Pd}});var Dd=X((B2,J0)=>{var{execSync:JA}=require("child_process"),Id=require("path"),gi=require("fs"),jd=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function K0(){return Id.join(process.cwd(),".nex","hooks")}function ZA(){return Id.join(process.cwd(),".nex","config.json")}function X0(){let t=ZA();if(!gi.existsSync(t))return{};try{return JSON.parse(gi.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Rc(t){if(!jd.includes(t))return[];let e=[],n=K0(),o=Id.join(n,t);gi.existsSync(o)&&e.push(o);let s=X0();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function V0(t,e={},n=3e4){try{return{success:!0,exitCode:0,output:JA(t,{cwd:process.cwd(),encoding:"utf-8",timeout:n,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(o){let s=typeof o.status=="number"?o.status:1;return{success:!1,exitCode:s,blocked:s===2,output:o.stdout?o.stdout.trim():"",error:o.stderr?o.stderr.trim():o.message}}}function QA(t,e={}){let n=Rc(t);if(n.length===0)return{results:[],blocked:!1};let o={};for(let[r,i]of Object.entries(e))o[`NEX_${r.toUpperCase()}`]=String(i);let s=[];for(let r of n){let i=V0(r,o);if(s.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:s,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:s,blocked:!1}}function eO(t){return Rc(t).length>0}function tO(){let t=[];for(let e of jd){let n=Rc(e);n.length>0&&t.push({event:e,commands:n})}return t}function nO(){let t=K0();return gi.existsSync(t)||gi.mkdirSync(t,{recursive:!0}),t}J0.exports={HOOK_EVENTS:jd,loadHookConfig:X0,getHooksForEvent:Rc,executeHook:V0,runHooks:QA,hasHooks:eO,listHooks:tO,initHooksDir:nO}});var yi=X((G2,hw)=>{"use strict";var{callWithRetry:ew,runSubAgent:Z0,clearAllLocks:sO}=ac(),{parseModelSpec:tw,getActiveProviderName:U2,getActiveModelId:W2}=Xe(),{detectCategory:oO,getModelForCategory:Q0}=Xn(),{MultiProgress:rO,C:ve}=He(),{getModelBriefing:H2}=ec(),nw=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Cc=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),sw="devstral-2:123b",ow="kimi-k2.5",rw=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
|
|
782
782
|
|
|
783
783
|
RULES:
|
|
784
784
|
- Output ONLY a JSON array, no markdown fences, no explanation.
|
|
@@ -793,7 +793,7 @@ RULES:
|
|
|
793
793
|
- If the request is simple (single goal), return an array with exactly 1 item.
|
|
794
794
|
|
|
795
795
|
USER REQUEST:
|
|
796
|
-
{prompt}`,
|
|
796
|
+
{prompt}`,iw=`You are a result synthesis engine. Given the results of multiple sub-agents that worked on parts of a larger task, produce a unified summary.
|
|
797
797
|
|
|
798
798
|
RULES:
|
|
799
799
|
- Output ONLY a JSON object with these fields:
|
|
@@ -807,16 +807,16 @@ ORIGINAL REQUEST:
|
|
|
807
807
|
{prompt}
|
|
808
808
|
|
|
809
809
|
SUB-AGENT RESULTS:
|
|
810
|
-
{results}`;async function
|
|
811
|
-
${e.slice(0,200)}`)}async function
|
|
810
|
+
{results}`;async function aw(t,e=1,n=2e3){for(let o=0;o<=e;o++)try{return await t()}catch(s){if(o===e)throw s;await new Promise(r=>setTimeout(r,n))}}function cw(t){let e=0,n=[];return function(){return new Promise(s=>{let r=()=>{e<t?(e++,s(()=>{e--,n.length>0&&n.shift()()})):n.push(r)};r()})}}function iO(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,n=[],o=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);o&&o.length>=2&&(e=Math.max(e,o.length),n.push(`${o.length} numbered items`));let s=t.match(/(?:^|\n)\s*[-*]\s+\S/g);s&&s.length>=3&&(e=Math.max(e,s.length),n.push(`${s.length} bullet points`));let r=t.split(/;\s*/).filter(u=>u.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),n.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),n.push(`${i.length} transition keywords`));let a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=a,estimatedGoals:e,reason:n.length>0?n.join(", "):"single goal"}}function qd(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let n=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(n)try{return JSON.parse(n[1].trim())}catch{}let o=e.search(/[[\{]/);if(o>=0){let s=e.slice(o);try{return JSON.parse(s)}catch{}}throw new Error(`Could not extract valid JSON from response:
|
|
811
|
+
${e.slice(0,200)}`)}async function lw(t,e,n={}){let o=n.maxSubTasks||Cc,r=[{role:"system",content:rw.replace("{maxSubTasks}",String(o)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=tw(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let c=(await ew(r,[],i)).content||"",u=qd(c);if(!Array.isArray(u))throw new Error(`Decompose returned non-array: ${typeof u}`);let d=10,p=u.slice(0,o).map((g,y)=>({id:g.id||`t${y+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:y+1})).filter(g=>g.task.length>0),m=p.reduce((g,y)=>g+y.estimatedCalls,0),h=Cc*d;if(m>h){let{debugLog:g}=Sa();g(`${Lt().T.yellow} \u26A0 Orchestrator: total estimated calls ${m} > ${h} \u2014 consider raising maxSubTasks${Lt().T.reset}`)}return p}async function uw(t,e,n){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let o=t.map((d,f)=>{let p=d.status==="done"?"SUCCESS":d.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${f+1} [${p}] ---
|
|
812
812
|
Task: ${d.task}
|
|
813
813
|
Result: ${d.result}
|
|
814
814
|
Tools: ${(d.toolsUsed||[]).join(", ")||"none"}`}).join(`
|
|
815
815
|
|
|
816
|
-
`),r=[{role:"system",content:
|
|
816
|
+
`),r=[{role:"system",content:iw.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let d=tw(n);d.provider&&(i.provider=d.provider),d.model&&(i.model=d.model)}let c=(await ew(r,[],i)).content||"",u=qd(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 aO(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||ow,o=e.workerModel||sw,s=e.maxParallel||nw,r=e.maxSubTasks||Cc,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
|
|
817
817
|
${ve.bold}Orchestrator${ve.reset} ${ve.dim}model: ${n} | workers: ${o} | max parallel: ${s}${ve.reset}
|
|
818
|
-
`),i("decomposing"),console.log(`${ve.dim}Phase 1: Decomposing prompt into sub-tasks...${ve.reset}`);let c;try{c=await
|
|
819
|
-
`);let d=Date.now(),f=
|
|
818
|
+
`),i("decomposing"),console.log(`${ve.dim}Phase 1: Decomposing prompt into sub-tasks...${ve.reset}`);let c;try{c=await lw(t,n,{maxSubTasks:r})}catch(G){return console.log(`${ve.red}Decompose failed: ${G.message}${ve.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${G.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(c.length===0)return console.log(`${ve.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${ve.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${ve.green}Decomposed into ${c.length} sub-tasks:${ve.reset}`);for(let G of c){console.log(` ${ve.dim}${G.id}:${ve.reset} ${G.task}`);let te=G.scope.filter(Boolean);te.length>0&&console.log(` ${ve.dim}scope: ${te.join(", ")}${ve.reset}`)}console.log("");let u=new Map;for(let G=0;G<c.length;G++)for(let te of c[G].scope)te&&!u.has(te)&&u.set(te,G);i("executing"),console.log(`${ve.dim}Phase 2: Running ${c.length} sub-agents (max ${s} parallel)...${ve.reset}
|
|
819
|
+
`);let d=Date.now(),f=cw(s),p={findings:[],_lock:!1},m=c.map(G=>{let te=oO(G.task);return(te?Q0(te.id):null)||o}),h=c.map((G,te)=>{let ge=`Agent ${te+1} [${m[te]}]: `,xe=Math.max(20,60-ge.length),Ne=G.task.substring(0,xe)+(G.task.length>xe?"...":"");return ge+Ne}),g=new rO(h);g.start();let y=`
|
|
820
820
|
You are a focused coding agent executing ONE specific sub-task.
|
|
821
821
|
Your scope is limited to the files listed in your task definition.
|
|
822
822
|
|
|
@@ -844,21 +844,21 @@ RULES:
|
|
|
844
844
|
`,w=new Map;for(let G=0;G<c.length;G++){let te=c[G].priority||1;w.has(te)||w.set(te,[]),w.get(te).push({st:c[G],idx:G})}let x=[...w.keys()].sort((G,te)=>G-te),S=new Array(c.length);for(let G of x){let ge=w.get(G).map(async({st:xe,idx:Ne})=>{let Ae=await f();try{let ke=await k(xe,Ne,{acquire:f,subTaskModels:m,labels:h,progress:g,sharedContext:p,_fileOwnership:u,workerModel:o,WORKER_SYSTEM_PROMPT:y});return S[Ne]=ke,ke}finally{Ae()}});await Promise.all(ge)}async function k(G,te,ge){try{let xe=p.findings.filter(N=>N.agentId!==G.id).map(N=>`Agent ${N.agentId} found: ${N.summary}`).join(`
|
|
845
845
|
`),Ne=[...u.entries()].filter(([,N])=>N===te).map(([N])=>N),Ae=[...u.entries()].filter(([,N])=>N!==te).map(([N])=>N),ke=[xe?`Prior agent findings:
|
|
846
846
|
${xe}
|
|
847
|
-
`:"",G.scope.length>0?`Focus on files: ${G.scope.join(", ")}`:"",Ne.length>0?`You OWN these files (may read+write): ${Ne.join(", ")}`:"",Ae.length>0?`READ ONLY (owned by other agents, do NOT write): ${Ae.join(", ")}`:""].filter(Boolean),E=
|
|
848
|
-
`)),oe++;let U=N&&P!==W?W:P;return
|
|
849
|
-
`):void 0,max_iterations:Math.min(G.estimatedCalls||10,15),model:U,_skipLog:!0,_systemPrompt:y,_readOnlyFiles:Ae},{onUpdate:F=>{if(F&&F.type==="tool_call"&&process.stderr.isTTY){let pe=`Agent ${te+1} [${U}]`,qe=F.tool||"...";g.labels[te]=`${pe}: ${qe}`}}})},1,2e3),R="";if(
|
|
847
|
+
`:"",G.scope.length>0?`Focus on files: ${G.scope.join(", ")}`:"",Ne.length>0?`You OWN these files (may read+write): ${Ne.join(", ")}`:"",Ae.length>0?`READ ONLY (owned by other agents, do NOT write): ${Ae.join(", ")}`:""].filter(Boolean),E=pw(G.task),P=m[te],W=process.env.NEX_FALLBACK_MODEL||Q0("agentic")||o,oe=0,O=await aw(async()=>{let N=oe>0;N&&(g.update(te,"retry"),process.stderr.write(` ${ve.dim}[Agent ${te+1}] retrying after error...${ve.reset}
|
|
848
|
+
`)),oe++;let U=N&&P!==W?W:P;return Z0({task:G.task,type:E,context:ke.length>0?ke.join(`
|
|
849
|
+
`):void 0,max_iterations:Math.min(G.estimatedCalls||10,15),model:U,_skipLog:!0,_systemPrompt:y,_readOnlyFiles:Ae},{onUpdate:F=>{if(F&&F.type==="tool_call"&&process.stderr.isTTY){let pe=`Agent ${te+1} [${U}]`,qe=F.tool||"...";g.labels[te]=`${pe}: ${qe}`}}})},1,2e3),R="";if(fw(E,O,G,Ne)){let N=[...new Set([...Ne,...Array.isArray(O.filesModified)?O.filesModified:[],...Array.isArray(G.scope)?G.scope:[]])].filter(Boolean);try{g.labels[te]=`Agent ${te+1} [${P}] review`,g.update(te,"retry");let U=await Z0({task:`Review the completed changes for: ${G.task}`,type:"review",context:dO(G,O,N),max_iterations:4,model:P,_skipLog:!0,_systemPrompt:y},{onUpdate:()=>{}},1);dw(U.result)?(R=`
|
|
850
850
|
|
|
851
851
|
Reviewer findings:
|
|
852
852
|
${U.result}`,p.findings.push({agentId:`${G.id}-review`,summary:String(U.result||"").slice(0,200),files:N})):U.result&&(R=`
|
|
853
853
|
|
|
854
854
|
Reviewer: ${U.result}`)}catch(U){R=`
|
|
855
855
|
|
|
856
|
-
Reviewer note: review pass failed (${U.message})`}}let Q=typeof O.result=="string"?`${O.result}${R}`.slice(0,200):`${String(O.result||"")}${R}`.slice(0,200);return p.findings.push({agentId:G.id,summary:Q,files:Array.isArray(G.scope)?G.scope:[]}),g.labels[te]=h[te],g.update(te,O.status==="failed"?"error":"done"),a.input+=O.tokensUsed?.input||0,a.output+=O.tokensUsed?.output||0,O.tokensUsed?._estimated&&(a._estimated=!0),{...O,result:`${String(O.result||"")}${R}`,_scope:G.scope,_idx:te}}catch(xe){return g.labels[te]=h[te],g.update(te,"error"),{task:G.task,status:"failed",result:`Error: ${xe.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let v;try{v=S}finally{g.stop({silent:!0}),sO()}console.log("");let C=Math.round((Date.now()-d)/1e3),q=C>=60?`${Math.floor(C/60)}m ${C%60}s`:`${C}s`;for(let G=0;G<v.length;G++){let te=v[G],xe=te.status==="done"||te.status==="truncated"&&te.result&&!te.result.startsWith("Error")?`${ve.green}\u2713${ve.reset}`:`${ve.red}\u2717${ve.reset}`,Ne=te._scope&&te._scope.length>0?te._scope.map(E=>E.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],Ae=Ne.length>0?Ne.join(", "):te.task.substring(0,35)+(te.task.length>35?"...":""),ke=G===v.length-1;console.log(` ${xe} Agent ${G+1} ${ve.dim}${Ae}${ve.reset}${ke?` ${ve.dim}${q}${ve.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${ve.dim}Phase 3: Synthesizing results...${ve.reset}`);let D;try{D=await
|
|
856
|
+
Reviewer note: review pass failed (${U.message})`}}let Q=typeof O.result=="string"?`${O.result}${R}`.slice(0,200):`${String(O.result||"")}${R}`.slice(0,200);return p.findings.push({agentId:G.id,summary:Q,files:Array.isArray(G.scope)?G.scope:[]}),g.labels[te]=h[te],g.update(te,O.status==="failed"?"error":"done"),a.input+=O.tokensUsed?.input||0,a.output+=O.tokensUsed?.output||0,O.tokensUsed?._estimated&&(a._estimated=!0),{...O,result:`${String(O.result||"")}${R}`,_scope:G.scope,_idx:te}}catch(xe){return g.labels[te]=h[te],g.update(te,"error"),{task:G.task,status:"failed",result:`Error: ${xe.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let v;try{v=S}finally{g.stop({silent:!0}),sO()}console.log("");let C=Math.round((Date.now()-d)/1e3),q=C>=60?`${Math.floor(C/60)}m ${C%60}s`:`${C}s`;for(let G=0;G<v.length;G++){let te=v[G],xe=te.status==="done"||te.status==="truncated"&&te.result&&!te.result.startsWith("Error")?`${ve.green}\u2713${ve.reset}`:`${ve.red}\u2717${ve.reset}`,Ne=te._scope&&te._scope.length>0?te._scope.map(E=>E.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],Ae=Ne.length>0?Ne.join(", "):te.task.substring(0,35)+(te.task.length>35?"...":""),ke=G===v.length-1;console.log(` ${xe} Agent ${G+1} ${ve.dim}${Ae}${ve.reset}${ke?` ${ve.dim}${q}${ve.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${ve.dim}Phase 3: Synthesizing results...${ve.reset}`);let D;try{D=await uw(v,t,n)}catch(G){console.log(`${ve.yellow}Synthesize failed: ${G.message} \u2014 using raw results.${ve.reset}`),D={summary:v.map(te=>te.result).join(`
|
|
857
857
|
`),conflicts:[],commitMessage:"",resourcesChanged:[]}}let ee=p.findings.flatMap(G=>G.files),ue=new Map;for(let G of ee)ue.set(G,(ue.get(G)||0)+1);let le=[...ue.values()].some(G=>G>1),de=p.findings.length>1&&le?` ${ve.dim}(agents shared context)${ve.reset}`:"";if(console.log(`
|
|
858
858
|
${ve.bold}Summary:${ve.reset} ${D.summary}${de}`),D.conflicts.length>0){console.log(`${ve.yellow}Conflicts:${ve.reset}`);for(let G of D.conflicts)console.log(` - ${G}`)}D.commitMessage&&console.log(`${ve.dim}Suggested commit: ${D.commitMessage}${ve.reset}`);let M=a.input===0&&a.output===0?"n/a (provider does not report token counts)":a._estimated?`~${a.input} input / ~${a.output} output (est.)`:`${a.input} input + ${a.output} output`;return console.log(`${ve.dim}Tokens: ${M}${ve.reset}
|
|
859
859
|
`),{results:v,synthesis:D,totalTokens:a}}var cO=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,lO=/\b(review|audit|verify|validate|inspect|critique)\b/i,uO=/\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 dO(t,e,n){let o=Array.isArray(n)&&n.length>0?`Files to review: ${n.join(", ")}`:"Files to review: inspect the files touched by the implementing agent";return["Review the finished implementation for correctness, regressions, and missing verification.",`Original task: ${t.task}`,o,`Implementation summary: ${String(e.result||"").slice(0,600)}`,'Report findings first. If no material issue exists, say "No material findings" and mention the main residual risk.'].join(`
|
|
860
|
-
`)}function
|
|
861
|
-
`)}var
|
|
860
|
+
`)}function dw(t){return!t||typeof t!="string"?!1:!/no material findings/i.test(t)}function fw(t,e,n,o){if(t!=="implement"||!e||e.status==="failed")return!1;let s=Array.isArray(n?.scope)?n.scope.length:0,r=Array.isArray(e.filesModified)?e.filesModified.length:0,i=Array.isArray(o)?o.length:0;return s+r+i>0}function pw(t){if(!t)return"implement";let e=cO.test(t),n=lO.test(t);return uO.test(t)?"implement":n?"review":e?"explore":"implement"}hw.exports={runOrchestrated:aO,decompose:lw,synthesize:uw,detectComplexPrompt:iO,extractJSON:qd,createSemaphore:cw,DECOMPOSE_PROMPT:rw,SYNTHESIZE_PROMPT:iw,DEFAULT_ORCHESTRATOR_MODEL:ow,DEFAULT_WORKER_MODEL:sw,DEFAULT_MAX_PARALLEL:nw,DEFAULT_MAX_SUBTASKS:Cc,withRetry:aw,_classifyWorkerType:pw,_hasMaterialReviewFindings:dw,_shouldRunFollowUpReview:fw}});var Ee=X((J2,zw)=>{var{C:$,Spinner:cr,TaskProgress:fO,formatToolCall:pO,formatToolSummary:Qd,formatSectionHeader:$i,formatMilestone:hO,setActiveTaskProgress:Y2,getThinkingVerb:Fd,setActiveModelForSpinner:mw}=He(),{debugLog:B,warnLog:z2}=Sa(),{MilestoneTracker:mO}=Hh(),{callStream:gw}=Xe(),{parseToolArgs:gO}=Uo(),{executeTool:yO}=Sn(),{gatherProjectContext:$O}=_c(),{fitToContext:wO,forceCompress:Vn,getUsage:Pn,estimateTokens:bO,buildProgressSnapshot:_O}=en(),{autoSave:xO,flushAutoSave:vO}=Mn(),{scoreMessages:kO,formatScore:SO,appendScoreHistory:EO}=vc(),{detectCategory:TO,getModelForPhase:ef,getPhaseBudget:ho,isPhaseRoutingEnabled:RO}=Xn();function We(t){xO(t),vO()}function Ac(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 CO(t){return!t||typeof t!="string"?!1:/\.(?:md|mdx|txt|rst|adoc)$/i.test(t)}function wi(t){try{if(!t.some(o=>o.role!=="assistant"?!1:!!(Array.isArray(o.content)&&o.content.some(s=>s&&s.type==="tool_use")||Array.isArray(o.tool_calls)&&o.tool_calls.length>0)))return;let n=kO(t);if(!n)return;console.log(SO(n,$));try{let{_getSessionsDir:o}=Mn(),s=require("fs"),r=require("path").join(o(),"_autosave.json");if(s.existsSync(r)){let i=JSON.parse(s.readFileSync(r,"utf-8"));i.score=n.score,i.scoreGrade=n.grade,i.scoreIssues=n.issues,s.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:o}=Uo(),s=Po();EO(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:AO}=Rn(),{getDeploymentContextBlock:OO,probeUrlServer:MO,detectRuntimeDebugTarget:yw}=vd(),{getFewShotForInput:NO}=E0(),{checkPermission:PO,setPermission:LO,savePermissions:IO}=mi(),{confirm:Ow,setAllowAlwaysHandler:jO,getAutoConfirm:bo}=It(),{isPlanMode:Ci,getPlanModePrompt:DO,PLAN_MODE_ALLOWED_TOOLS:Mw,setPlanContent:qO,extractStepsFromText:FO,createPlan:BO,getActivePlan:K2,startExecution:X2,advancePlanStep:UO,getPlanStepInfo:WO}=Nn(),{StreamRenderer:HO}=z0(),{runHooks:$w}=Dd(),{routeMCPCall:GO,getMCPToolDefinitions:YO}=Ma(),{getSkillInstructions:zO,getSkillToolDefinitions:KO,routeSkillCall:XO,matchSkillTriggers:VO}=is(),{trackUsage:ww,estimateTokens:bw}=xs();function _w(t){return!t||typeof t!="string"?0:typeof bw=="function"?bw(t):Math.ceil(t.length/4)}var{validateToolArgs:JO}=pu(),{filterToolsForModel:xw,getModelTier:ZO,PROVIDER_DEFAULT_TIER:V2}=Ur(),{getConfiguredProviders:QO,getActiveProviderName:lr,getActiveModelId:In,setActiveModel:Bd,MODEL_EQUIVALENTS:Yc}=Xe(),{getModelProfile:eM,getModelBriefing:tM}=ec(),st=require("fs"),lt=require("path"),nM=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function sM(t){let e=hO(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
|
|
861
|
+
`)}var vw=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi,kw=/(?:^|\s)(https?:\/\/[^\s]+\.(?:png|jpe?g|gif|webp)(?:\?[^\s]*)?)(?:\s|$)/gi,oM=/\b(?:clipboard|pasteboard|zwischenablage|screenshot aus clipboard)\b/i;function rM(t){let e=[],n;for(vw.lastIndex=0;(n=vw.exec(t))!==null;){let o=n[1].trim(),s=o.startsWith("~")?o.replace("~",process.env.HOME||""):lt.resolve(o);st.existsSync(s)&&e.push({raw:o,abs:s})}return e}function Nw(t){let e=[],n;for(kw.lastIndex=0;(n=kw.exec(t))!==null;)e.push(n[1].trim());return e}async function Pw(t){try{let n=await require("axios").get(t,{responseType:"arraybuffer",timeout:1e4,maxContentLength:10*1024*1024,headers:{"User-Agent":"nex-code/vision"}}),o=n.headers["content-type"]||"",s=o.startsWith("image/")?o.split(";")[0]:iM(t);return{data:Buffer.from(n.data).toString("base64"),media_type:s}}catch{return null}}function iM(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 Lw(){if(process.platform!=="darwin")return null;let{spawnSync:t}=require("child_process"),e=lt.join(require("os").tmpdir(),`nex-clipboard-${Date.now()}.png`);if(t("pngpaste",[e],{timeout:3e3}).status===0&&st.existsSync(e)){let s=st.readFileSync(e);if(s.length>100)return{data:s.toString("base64"),media_type:"image/png",path:e};try{st.unlinkSync(e)}catch(r){console.error("Failed to unlink temp file:",r)}}let o=t("osascript",["-e",`try
|
|
862
862
|
set imgData to the clipboard as \xABclass PNGf\xBB
|
|
863
863
|
return "has_image"
|
|
864
864
|
on error
|
|
@@ -869,47 +869,47 @@ end try`],{timeout:3e3});if(o.stdout&&o.stdout.toString().trim()==="has_image"){
|
|
|
869
869
|
set fRef to open for access filePath with write permission
|
|
870
870
|
write imgData to fRef
|
|
871
871
|
close access fRef
|
|
872
|
-
`;if(t("osascript",["-e",s],{timeout:5e3}).status===0&&st.existsSync(e)){let i=st.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function
|
|
872
|
+
`;if(t("osascript",["-e",s],{timeout:5e3}).status===0&&st.existsSync(e)){let i=st.readFileSync(e);if(i.length>100)return{data:i.toString("base64"),media_type:"image/png",path:e}}}return null}function Sw(t){let e=st.readFileSync(t),n=lt.extname(t).toLowerCase().replace(".",""),o=n==="jpg"||n==="jpeg"?"image/jpeg":n==="png"?"image/png":n==="gif"?"image/gif":n==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:o}}function Iw(t){let e=rM(t),n=Nw(t),o=oM.test(t),s=n.length>0||o;if(e.length===0&&!s)return t;if(!s){let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:c}=Sw(i.abs);r.push({type:"image",media_type:c,data:a})}catch{}return r.length>1?r:t}return(async()=>{let r=[{type:"text",text:t}];for(let i of e)try{let{data:a,media_type:c}=Sw(i.abs);r.push({type:"image",media_type:c,data:a})}catch(a){B(`${$.yellow} \u26A0 Path resolution failed: ${a.message}${$.reset}`)}if(n.length>0){let i=await Promise.all(n.map(Pw));for(let a of i)a&&r.push({type:"image",media_type:a.media_type,data:a.data})}if(o){let i=Lw();i?(r.push({type:"image",media_type:i.media_type,data:i.data}),r[0].text+=`
|
|
873
873
|
[Clipboard image attached: ${i.path}]`):r[0].text+=`
|
|
874
|
-
[No image found in clipboard]`}return r.length>1?r:t})()}var aM=[/\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
|
|
874
|
+
[No image found in clipboard]`}return r.length>1?r:t})()}var aM=[/\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 jw(t){return typeof t!="string"||!t?!1:aM.some(e=>e.test(t))}function cM(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 o=new Map;for(let c=0;c<=n.length-3;c++){let u=n.slice(c,c+3).join("").trim();u.length>30&&o.set(u,(o.get(u)||0)+1)}let s=0,r="";for(let[c,u]of o)u>s&&(s=u,r=c);if(s<3)return{text:t,truncated:!1,repeatCount:s};let i=`
|
|
875
875
|
|
|
876
876
|
[SYSTEM: Output repetition detected \u2014 response truncated (${s}\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:s}}function tf(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let n=t.split(`
|
|
877
877
|
`),o=new Map;for(let m of n){let h=m.trim();h.length>=20&&o.set(h,(o.get(h)||0)+1)}let s=0,r="";for(let[m,h]of o)h>s&&(s=h,r=m);let a=r.toLowerCase().includes("read_file")||r.toLowerCase().includes("reading")?2:e;if(s<=a)return{text:t,truncated:!1,repeatCount:s};let c=`
|
|
878
878
|
|
|
879
|
-
\u26A0 [Response truncated: repeated paragraph detected (${s}\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:s}}var Ud=null,Wd=null,Hd=null;function At(){if(Ud===null){let{TOOL_DEFINITIONS:t}=Sn();Ud=t}return Wd===null&&(Wd=KO()),Hd===null&&(Hd=YO()),[...Ud,...Wd,...Hd]}var nf=50;function lM(t){Number.isFinite(t)&&t>0&&(nf=t)}var Pc=()=>null;function uM(t){Pc=t}var vi=null,sf=null,ur=null,dr="",fr=0,of="",rf=0,Lc=new Map,dM=1e4,fM=6e3,pM=/\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 hM(t){return!t||typeof t!="string"?t:t.replace(pM,(e,n)=>`${n}=***REDACTED***`)}var mM=7e3,gM=4e3;function yM(t,e=null){let n=hM(t),o=bO(n),s=e==="read_file"?mM:dM,r=e==="read_file"?gM:fM;if(o>s)try{let{compressToolResult:i}=en();return i(n,r)}catch{return n}return n}function
|
|
879
|
+
\u26A0 [Response truncated: repeated paragraph detected (${s}\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:s}}var Ud=null,Wd=null,Hd=null;function At(){if(Ud===null){let{TOOL_DEFINITIONS:t}=Sn();Ud=t}return Wd===null&&(Wd=KO()),Hd===null&&(Hd=YO()),[...Ud,...Wd,...Hd]}var nf=50;function lM(t){Number.isFinite(t)&&t>0&&(nf=t)}var Pc=()=>null;function uM(t){Pc=t}var vi=null,sf=null,ur=null,dr="",fr=0,of="",rf=0,Lc=new Map,dM=1e4,fM=6e3,pM=/\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 hM(t){return!t||typeof t!="string"?t:t.replace(pM,(e,n)=>`${n}=***REDACTED***`)}var mM=7e3,gM=4e3;function yM(t,e=null){let n=hM(t),o=bO(n),s=e==="read_file"?mM:dM,r=e==="read_file"?gM:fM;if(o>s)try{let{compressToolResult:i}=en();return i(n,r)}catch{return n}return n}function Dw(t){try{let{getActiveModel:e}=Xe(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(Lc.has(o))return Lc.get(o);let s=xw(t);return Lc.set(o,s),s}catch{return xw(t)}}function $M(){Lc.clear()}function wM(t,e){let n=new Set(e);return(t||[]).some(o=>o.role!=="assistant"?!1:Array.isArray(o.tool_calls)?o.tool_calls.some(s=>n.has(s?.function?.name||s?.name)):Array.isArray(o.content)?o.content.some(s=>s?.type==="tool_use"&&n.has(s?.name)):!1)}var ki={hash:null,ts:0},bM=3e4;async function qw(){if(ki.hash&&Date.now()-ki.ts<bM)return ki.hash;try{let t=require("fs").promises,e=require("path"),n=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],s=(await Promise.allSettled(n.map(i=>t.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=Rn(),a=i();a&&s.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(st.existsSync(i)){let a=await t.stat(i);s.push(`brain:${a.mtimeMs}`)}}catch{}let r=s.join("|");return ki={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function af(){vi=null,sf=null,ki={hash:null,ts:0},ur=null}var _M=new Set(["spawn_agents"]),Gd=10,Yd=10,Oc=5,Ew=6e4,zd=12e4,xM=process.env.NEX_STALE_AUTO_SWITCH!=="0";function vM(t){try{let e=require("fs"),n=require("path"),o=n.join(process.cwd(),".nex","plans");e.existsSync(o)||e.mkdirSync(o,{recursive:!0});let s=n.join(o,"current-plan.md");e.writeFileSync(s,t,"utf-8")}catch{}}jO(t=>{LO(t,"allow"),IO(),console.log(`${$.green} \u2713 ${t}: always allow${$.reset}`)});async function kM(t){let e=t.function.name,n=gO(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!n){let f=At().find(m=>m.function.name===e),p=f?JSON.stringify(f.function.parameters,null,2):"unknown";return B(`${$.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${$.reset}`),{callId:o,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
880
880
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
881
881
|
|
|
882
882
|
Expected JSON schema for "${e}":
|
|
883
883
|
${p}
|
|
884
884
|
|
|
885
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}if(n&&typeof n.path=="string")try{let d=require("os"),f=
|
|
886
|
-
`)[0]}${$.reset}`);let d=(
|
|
885
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}if(n&&typeof n.path=="string")try{let d=require("os"),f=lt.resolve(process.cwd(),n.path.replace(/^~/,d.homedir())),p=n.path;n.path=lt.relative(process.cwd(),f)||".",Object.defineProperty(n,"_originalPath",{value:p,enumerable:!1})}catch(d){console.error("path resolution failed:",d.message)}let s=JO(e,n);if(!s.valid){B(`${$.yellow} \u26A0 ${e}: ${s.error.split(`
|
|
886
|
+
`)[0]}${$.reset}`);let d=(Rw.get(e)||0)+1;Rw.set(e,d);let f=d>=2?`${s.error}
|
|
887
887
|
|
|
888
|
-
[SYSTEM: This is argument error #${d} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:s.error;return{callId:o,fnName:e,args:n,canExecute:!1,errorResult:{role:"tool",content:f,tool_call_id:o}}}let r=s.corrected||n;if(s.corrected){let d=Object.keys(n),f=Object.keys(s.corrected),p=d.filter(m=>!f.includes(m));p.length&&console.log(`${$.dim} \u2713 ${e}: corrected args (${p.join(", ")})${$.reset}`)}if(Ci()&&!
|
|
888
|
+
[SYSTEM: This is argument error #${d} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:s.error;return{callId:o,fnName:e,args:n,canExecute:!1,errorResult:{role:"tool",content:f,tool_call_id:o}}}let r=s.corrected||n;if(s.corrected){let d=Object.keys(n),f=Object.keys(s.corrected),p=d.filter(m=>!f.includes(m));p.length&&console.log(`${$.dim} \u2713 ${e}: corrected args (${p.join(", ")})${$.reset}`)}if(Ci()&&!Mw.has(e))return console.log(`${$.yellow} \u2717 ${e}: blocked in plan mode${$.reset}`),{callId:o,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:o}};let i=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),a=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),c=e==="spawn_agents"&&Array.isArray(r?.agents)&&r.agents.length>0&&r.agents.every(d=>d.background===!0);if(Te&&De==="plan"&&!i.has(e)&&!e.startsWith("skill_")&&!c)return As++,Ri=e,B(`${$.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${As})${$.reset}`),{callId:o,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:o}};if(Te&&De==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return B(`${$.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${$.reset}`),{callId:o,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:o}};let u=PO(e);if(u==="deny")return console.log(`${$.red} \u2717 ${e}: denied by permissions${$.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:o}};if(u==="ask"){let d=` Allow ${e}?`;return e==="bash"&&r.command&&(d=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await Ow(d,{toolName:e})?{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:o,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:o}}}return{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function SM(t,e,n={}){let o=await XO(t,e);if(o!==null)return o;let s=await GO(t,e);return s!==null?s:yO(t,e,n)}function EM(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e._originalPath||e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function Kd(t,e=!1){e||console.log(pO(t.fnName,t.args));let n=$w("pre-tool",{tool_name:t.fnName}),o=n.results;if(n.blocked){let y=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${n.blockReason}`;e||console.log(`${$.yellow} [hook pre-tool] BLOCKED: ${n.blockReason}${$.reset}`);let w=Qd(t.fnName,t.args,y,!0);return e||console.log(w),{msg:{role:"tool",content:y,tool_call_id:t.callId},summary:w}}if(!e&&o.length>0)for(let y of o)y.success?console.log(`${$.dim} [hook pre-tool] ${y.command} \u2192 ${y.output||"ok"}${$.reset}`):console.log(`${$.yellow} [hook pre-tool] ${y.command} \u2192 ERROR: ${y.error}${$.reset}`);es?.onToolStart&&es.onToolStart(t.fnName,t.args);let s=await SM(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=null,i;s&&typeof s=="object"&&s.text?(i=String(s.text),Array.isArray(s.images)&&s.images.length>0&&(r=s.images)):i=String(s??"");let a=i.length>5e4?i.substring(0,5e4)+`
|
|
889
889
|
...(truncated ${i.length-5e4} chars)`:i,c=a.split(`
|
|
890
|
-
`)[0],u=c.startsWith("ERROR")||c.includes("CANCELLED")||c.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),d=Qd(t.fnName,t.args,a,u);e||console.log(d),es?.onToolEnd&&es.onToolEnd(t.fnName,d,!u);let p
|
|
890
|
+
`)[0],u=c.startsWith("ERROR")||c.includes("CANCELLED")||c.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(a)&&/✗ Agent/.test(a),d=Qd(t.fnName,t.args,a,u);e||console.log(d),es?.onToolEnd&&es.onToolEnd(t.fnName,d,!u);let p=$w("post-tool",{tool_name:t.fnName}).results;if(!e&&p.length>0)for(let y of p)y.success?console.log(`${$.dim} [hook post-tool] ${y.command} \u2192 ${y.output||"ok"}${$.reset}`):console.log(`${$.yellow} [hook post-tool] ${y.command} \u2192 ERROR: ${y.error}${$.reset}`);let h=yM(a,t.fnName);if(t.fnName==="bash"&&t.args?.command){let y=t.args.command.trim();!/cat\s*>|<</.test(y)&&/\bcat\s+\S/.test(y)?h+=`
|
|
891
891
|
HINT: use read_file instead of bash cat \u2014 it is faster, context-efficient, and the preferred tool for reading files.`:/^\s*ls(\s|$)/.test(y)&&!/npm|yarn|pnpm|make|git\b/.test(y)?h+=`
|
|
892
892
|
HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(y)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test(y)&&(h+=`
|
|
893
|
-
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(y=>({type:"image",media_type:y.media_type,data:y.base64}))]:h,tool_call_id:t.callId},summary:d}}var TM=[{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 Xd(t){for(let{re:e,label:n}of TM){let o=t.match(e);if(o){let s=(o[1]||"").trim();return s?`${n}: ${s}`:n}}return null}async function RM(t,e=!1,n={}){let o=new Array(t.length),s=[],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=EM(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 cr(u),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let c=r[0],{msg:u,summary:d}=await Kd(t[c],e);o[c]=u,s.push(d)}else{let c=r.map(d=>Kd(t[d],e)),u=await Promise.all(c);for(let d=0;d<r.length;d++)o[r[d]]=u[d].msg,s.push(u[d].summary)}r=[]}}for(let c=0;c<t.length;c++){let u=t[c];if(!u.canExecute){await a(),o[c]=u.errorResult,s.push(Qd(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(_M.has(u.fnName)){await a(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await Kd(u,e);o[c]=d,s.push(f)}else r.push(c)}if(await a(),i&&i.stop(),e&&s.length>0&&!n.skipSummaries)for(let c of s)console.log(c);return{results:o,summaries:s}}var j=[],
|
|
894
|
-
`)):(lf=t,qc=1,B(`${e} \u26A0 ${t}${$.reset}`))}var Gc=[];function
|
|
895
|
-
`)}function
|
|
893
|
+
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(y=>({type:"image",media_type:y.media_type,data:y.base64}))]:h,tool_call_id:t.callId},summary:d}}var TM=[{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 Xd(t){for(let{re:e,label:n}of TM){let o=t.match(e);if(o){let s=(o[1]||"").trim();return s?`${n}: ${s}`:n}}return null}async function RM(t,e=!1,n={}){let o=new Array(t.length),s=[],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=EM(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 cr(u),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let c=r[0],{msg:u,summary:d}=await Kd(t[c],e);o[c]=u,s.push(d)}else{let c=r.map(d=>Kd(t[d],e)),u=await Promise.all(c);for(let d=0;d<r.length;d++)o[r[d]]=u[d].msg,s.push(u[d].summary)}r=[]}}for(let c=0;c<t.length;c++){let u=t[c];if(!u.canExecute){await a(),o[c]=u.errorResult,s.push(Qd(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(_M.has(u.fnName)){await a(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await Kd(u,e);o[c]=d,s.push(f)}else r.push(c)}if(await a(),i&&i.stop(),e&&s.length>0&&!n.skipSummaries)for(let c of s)console.log(c);return{results:o,summaries:s}}var j=[],Tw=300,Fw=900*1e3;function Jn(t,e){let n=t.get(e);return n?Date.now()-n.ts>Fw?(t.delete(e),0):n.count:0}function mo(t,e){let n=t.get(e),o=n&&Date.now()-n.ts<=Fw?n.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function Vd(t,e,n){t.set(e,{count:n,ts:Date.now()})}var yf=new Map,Bw=new Map,Ic=new Map,Ai=new Set,Uw=new Map,jc=new Map,Oi=new Set,Qn=new Map,hs=new Map,Mi=new Map,yn=new Map,_o=new Map,Rw=new Map,zc=new Map,cf=new Map,$n=0,Si=0,Dc=0,lf="",qc=0,rn=!1,Mc=0,Fc=0,yo=-1,uf=!1,Bc=0,Uc=!1,bn=0,_n=!1,Ln=0,xn=0,Et=!1,Kt="",Ei=0,Cs=0,Wc="",$o=0,wo=0,Hc="",bi=0,wn=!1,df=!1,Ni=new Map,Pi=new Set,Ti=null,Jd=!1,_i=0,Cw=!1,De="plan",Kc=0,Te=!1,As=0,Ri=null,jn=null,ff=null,pf=null,pr=0,hr=0,mr=0,gr=!1,yr=0,xo=null,vo=[],go=new Set;function CM(t){return t==="write_file"||t==="edit_file"||t==="patch_file"||t==="bash"}function Aw(t){let e=String(t||"");if(!e)return!1;let n=/(?:^|\s)(?:\.{1,2}\/)?[\w./-]+\.(?:js|ts|tsx|jsx|py|md|json|yml|yaml|sh|css|html)\b/i.test(e),o=/\b(create|write|add|make|build|scaffold)\b[\s\S]{0,160}\b(refactor|rename|improve|update|change|edit)\b/i.test(e)||/\b(refactor|update|change|edit)\b[\s\S]{0,160}\b(create|write|add|make|build|scaffold)\b/i.test(e),s=/\b(create|write|add|make|build|refactor|update|change|edit)\b[\s\S]{0,160}\bfile\b/i.test(e);return n&&(o||s)}function AM(t){let e=String(t||"").trim();return e?/^(hi|hello|hey|yo)\b/i.test(e)||/\b(introduce yourself|who are you|what can you do|tell me about yourself)\b/i.test(e):!1}function hf(t){return String(t||"").replace(/\\/g,"/").replace(/^\.\//,"").trim()}function OM(t){let n=String(t||"").match(/(?:^|\s)((?:\.{1,2}\/)?[\w./-]+\.(?:js|ts|tsx|jsx|py|md|json|yml|yaml|sh|css|html))\b/gi);return n?[...new Set(n.map(o=>hf(o)))]:[]}function ar(t,e){t===lf?(qc++,debug&&debug.DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${qc})${$.reset}
|
|
894
|
+
`)):(lf=t,qc=1,B(`${e} \u26A0 ${t}${$.reset}`))}var Gc=[];function MM(t){Gc.push(t.trim())}function NM(){return Gc.length===0?null:Gc.splice(0,Gc.length).join(`
|
|
895
|
+
`)}function PM(t){let e=t._startedAt?Math.round((t.finishedAt-t._startedAt)/1e3):null,n=e!==null?`
|
|
896
896
|
Duration: ${e}s`:"",o=typeof t.result.result=="string"?t.result.result.slice(0,4e3):JSON.stringify(t.result.result||"").slice(0,4e3),s=t.result.filesModified&&t.result.filesModified.length>0?`
|
|
897
897
|
Files modified: ${t.result.filesModified.join(", ")}`:"";return`[BACKGROUND AGENT COMPLETED]
|
|
898
898
|
Job: ${t.jobId}
|
|
899
899
|
Task: "${t.agentDef.task}"`+n+`
|
|
900
900
|
Status: ${t.result.status||"done"}`+s+`
|
|
901
|
-
Result: ${o}`}function Nc(t,e){let{getCompletedJobs:n}=Vo(),o=n();for(let s of o){let r={role:"user",content:
|
|
902
|
-
`)}}function
|
|
903
|
-
`).find(c=>c.includes(r)||c.includes(s));n.push({file:s,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return n}function
|
|
904
|
-
`)}function
|
|
901
|
+
Result: ${o}`}function Nc(t,e){let{getCompletedJobs:n}=Vo(),o=n();for(let s of o){let r={role:"user",content:PM(s)};t.push(r),e.push(r);let i=s.result?.status||"done",a=i==="failed"?$.red+" \u2717":$.cyan+" \u2713";process.stderr.write(`${a} Background agent ${i}: ${s.agentDef.task.slice(0,50)} \u2014 ${String(s.result?.result||"").slice(0,80)}${$.reset}
|
|
902
|
+
`)}}function Ww(t,e){let n=[],o=new Set([...e.keys(),...Ai,...Oi]);if(!o.size||!t)return n;for(let s of o){let r=s.split("/").pop();if(r&&(t.includes(r)||t.includes(s))){let a=t.split(`
|
|
903
|
+
`).find(c=>c.includes(r)||c.includes(s));n.push({file:s,action:(a||"edit this file").trim().slice(0,200),done:!1})}}return n}function LM(t){if(!t||typeof t!="string")return[];let e=t.match(/[A-Za-z_][A-Za-z0-9_]{2,}/g)||[],n=new Set(["the","and","for","with","from","into","that","this","when","then","have","your","just","read","write","edit","file","files","test","tests","verify","phase","implement","summary","report","pass","fail","changes","change","address","original","task","user","request","code","module","function","class"]),o=new Set,s=[];for(let r of e){let i=r.toLowerCase();n.has(i)||o.has(i)||(o.add(i),s.push(r))}return s.sort((r,i)=>i.length-r.length),s.slice(0,6)}function IM(){return st.existsSync(lt.join(process.cwd(),"pnpm-lock.yaml"))?"pnpm":st.existsSync(lt.join(process.cwd(),"yarn.lock"))?"yarn":"npm"}function Zn(t){let e=IM();return t==="test"?e==="yarn"?"yarn test":e==="pnpm"?"pnpm test":"npm test":e==="yarn"?`yarn ${t}`:e==="pnpm"?`pnpm run ${t}`:`npm run ${t}`}function jM(t,e,n){let o=[...t||[]].slice(0,6).join(", ")||"recently modified files",s=(e||[]).slice(0,3),r=(n||[]).slice(0,3),i=[`[SYSTEM] You already changed code in: ${o}.`,"Run one narrow verification step next before more exploration."];return s.length>0&&i.push(`Suggested verification commands: ${s.join(" | ")}`),r.length>0&&i.push(`Likely related tests: ${r.join(", ")}`),i.push("Do not continue broad read/search loops until the latest edit has been checked."),i.join(`
|
|
904
|
+
`)}function DM(t){if(!t||!t.fnName||!["bash","ssh_exec"].includes(t.fnName))return!1;let e=String(t.args?.command||"").toLowerCase();return/\b(test|jest|vitest|pytest|mocha|rspec|phpunit|cargo test|go test|tsc|build|lint|eslint|check)\b/.test(e)}async function Hw(t){let e=LM(t);if(e.length===0)return[];let{searchContentIndex:n}=Hn(),o=[],s=new Set;for(let r of e)try{let i=await n(r,void 0,process.cwd());for(let a of i.slice(0,3)){let c=`${a.file}:${a.name}:${a.line}`;if(!s.has(c)&&(s.add(c),o.push(a),o.length>=5))return o}}catch{}return o}async function Gw(t){let e=await Hw(t);if(e.length===0)return"";let{getRelatedFiles:n,findSymbolReferences:o}=Hn(),s=["Likely symbol targets:"];for(let r=0;r<e.length;r++){let i=e[r],a=Math.max(1,i.line-20),c=i.line+40;s.push(`${r+1}. ${i.name} (${i.type}) in ${i.file}:${i.line} -> read_file(path='${i.file}', line_start=${a}, line_end=${c})`);try{let u=await n(i.file,process.cwd(),3);u.length>0&&s.push(` Follow-up files: ${u.join(", ")} (read only if the primary symbol points into one of these modules)`)}catch{}try{let u=await o(i.name,process.cwd(),{excludeFile:i.file,excludeLine:i.line,limit:2});u.length>0&&s.push(` Likely callers/usages: ${u.map(d=>`${d.file}:${d.line}`).join(", ")} (read these next if behavior depends on where ${i.name} is invoked)`)}catch{}}return`${s.join(`
|
|
905
905
|
`)}
|
|
906
906
|
Use these exact targeted reads before broader searching.
|
|
907
907
|
|
|
908
|
-
`}async function Xc(t){let{getFileIndex:e}=Hn(),{buildContentIndex:n,findSymbolReferences:o,getRelatedFiles:s}=Hn(),i=e().filter(u=>/^tests?\//.test(u)||/\.test\./.test(u)||/\.spec\./.test(u));if(i.length===0)return[];let a=new Set,c=await n(process.cwd());for(let u of t||[]){let d=String(u),f=
|
|
908
|
+
`}async function Xc(t){let{getFileIndex:e}=Hn(),{buildContentIndex:n,findSymbolReferences:o,getRelatedFiles:s}=Hn(),i=e().filter(u=>/^tests?\//.test(u)||/\.test\./.test(u)||/\.spec\./.test(u));if(i.length===0)return[];let a=new Set,c=await n(process.cwd());for(let u of t||[]){let d=String(u),f=lt.basename(d).replace(/\.[^.]+$/,"");if(f.length<3)continue;for(let h of i)if(h.includes(f)&&a.add(h),a.size>=4)return[...a];try{let h=await s(d,process.cwd(),4);for(let g of h){let y=lt.basename(g).replace(/\.[^.]+$/,"");if(!(y.length<3)){for(let w of i)if(w.includes(y)&&a.add(w),a.size>=4)return[...a]}}}catch{}let m=(Array.isArray(c.files?.[d]?.defs)?c.files[d].defs:[]).filter(h=>["function","class","export"].includes(h.type)).map(h=>h.name).filter((h,g,y)=>h&&y.indexOf(h)===g).slice(0,3);for(let h of m)try{let g=await o(h,process.cwd(),{excludeFile:d,limit:8});for(let y of g)if(i.includes(y.file)&&a.add(y.file),a.size>=4)return[...a]}catch{}}return[...a]}function qM(t,e={}){if(!Array.isArray(t)||t.length===0)return[];let n=t.slice(0,4).join(" "),o=[],s=String(e.test||"");return/vitest/.test(s)||st.existsSync(lt.join(process.cwd(),"vitest.config.ts"))||st.existsSync(lt.join(process.cwd(),"vitest.config.js"))?o.push(`npx vitest run ${n}`):(/jest/.test(s)||st.existsSync(lt.join(process.cwd(),"jest.config.js"))||st.existsSync(lt.join(process.cwd(),"jest.config.cjs"))||st.existsSync(lt.join(process.cwd(),"jest.config.mjs")))&&o.push(`npx jest --runInBand ${n}`),(st.existsSync(lt.join(process.cwd(),"pytest.ini"))||st.existsSync(lt.join(process.cwd(),"pyproject.toml")))&&t.some(r=>/\.py$/i.test(r))&&o.push(`pytest ${t.filter(r=>/\.py$/i.test(r)).slice(0,4).join(" ")}`),o}async function xi(t,e,n,o){if(!Te)return null;let s=De;De=t,Kc=0,jn=ef(t,xo),t==="verify"&&(hr=0,mr=0,gr=!1,yr=0),bn=0,_n=!1,Ln=0,xn=0,_o.clear(),zc.clear(),yf.clear(),Mi.clear(),t==="implement"&&(vo=Ww(e||"",Qn));let r=vo.length>0?`
|
|
909
909
|
|
|
910
910
|
ACTION ITEMS (execute these in order, do NOT re-read these files):
|
|
911
911
|
`+vo.map((c,u)=>`${u+1}. ${c.file} \u2014 ${c.action}`).join(`
|
|
912
|
-
`):"",i=await
|
|
912
|
+
`):"",i=await Gw(t==="verify"?o:e||o||""),a;if(t==="implement")ff=e?.slice(0,2e3)||"",a=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
|
|
913
913
|
${ff}
|
|
914
914
|
|
|
915
915
|
${i}Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`+r;else if(t==="verify"){pf=e?.slice(0,500)||"";let c=n?[...n].join(", "):"none",u=await $f(n),d=await Xc(n),f=u.length>0?`Suggested checks (run the narrowest ones that fit the change):
|
|
@@ -929,21 +929,24 @@ Prefer these before broader suites when a targeted run is possible.
|
|
|
929
929
|
Report PASS (all good) or FAIL (list specific issues).
|
|
930
930
|
|
|
931
931
|
Files modified: ${c}
|
|
932
|
-
${i}${f}${p}Summary: ${pf}`}return B(`${$.cyan} \u21B3 Phase transition: ${s} \u2192 ${t} (model: ${jn||"default"})${$.reset}`),a?{role:"user",content:a}:null}async function $f(t){let e=[],o=[...t||[]].map(c=>String(c).toLowerCase()),s={};try{let c=
|
|
933
|
-
`];s?r.push(`RESPONSE LANGUAGE: You MUST always respond in ${s}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${s} only.`):
|
|
932
|
+
${i}${f}${p}Summary: ${pf}`}return B(`${$.cyan} \u21B3 Phase transition: ${s} \u2192 ${t} (model: ${jn||"default"})${$.reset}`),a?{role:"user",content:a}:null}async function $f(t){let e=[],o=[...t||[]].map(c=>String(c).toLowerCase()),s={};try{let c=lt.join(process.cwd(),"package.json");if(st.existsSync(c)){s=JSON.parse(st.readFileSync(c,"utf-8")).scripts||{};let d=[["test",Zn("test")],["lint",Zn("lint")],["typecheck",Zn("typecheck")],["check",Zn("check")],["build",Zn("build")]];for(let[f,p]of d)s[f]&&e.push(p)}}catch{}e.length===0&&(st.existsSync(lt.join(process.cwd(),"package.json"))&&e.push(Zn("test")),(st.existsSync(lt.join(process.cwd(),"pytest.ini"))||st.existsSync(lt.join(process.cwd(),"pyproject.toml")))&&e.push("pytest"));let r=await Xc(t);e.unshift(...qM(r,s));let i=o.some(c=>/\.(ts|tsx)$/.test(c)),a=o.some(c=>/\.(js|jsx|ts|tsx)$/.test(c));return i&&!e.includes(Zn("typecheck"))&&e.push(Zn("typecheck")),a&&!e.includes(Zn("lint"))&&e.push(Zn("lint")),[...new Set(e)].slice(0,4)}function FM(t){let e=process.env.NEX_LANGUAGE;if(e&&e!=="auto")return e;if(wf())return"English";let n=String(t||"").trim();if(!n)return"English";if(/[äöüß]/i.test(n))return"German";let o=n.toLowerCase().match(/[a-zA-Zäöüß]+/g)||[],s=new Set(["a","an","and","are","can","do","does","explain","file","folder","for","how","in","is","it","list","of","please","show","the","this","what","where","why","with"]),r=new Set(["aber","analysiere","bitte","das","den","der","die","dies","diese","diesem","du","ein","eine","einer","englisch","erkl\xE4re","f\xFCr","hier","im","ist","mit","ordner","und","warum","was","wie","wieso","zeige"]),i=0,a=0;for(let c of o)s.has(c)&&i++,r.has(c)&&a++;return a>i?"German":(i>a,"English")}function BM(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,n=process.env.NEX_COMMIT_LANGUAGE,o=wf(),s=!t||t==="auto"?null:t,r=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
933
|
+
`];o?r.push("RESPONSE LANGUAGE: This project requires English. Always respond in English, even if the user writes in another language."):s?r.push(`RESPONSE LANGUAGE: You MUST always respond in ${s}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${s} only.`):r.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),r.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),r.push("COMPLETENESS RULES:"),r.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),bo()?r.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."):r.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files): paste the COMPLETE file content in a fenced code block in your TEXT RESPONSE \u2014 writing a file with a tool does NOT make it visible. The fenced code block MUST appear in your response, not just via write_file."),r.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),r.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),r.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),r.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),r.push(' \u2022 For Makefiles, paste the COMPLETE Makefile code DIRECTLY in your text response \u2014 every target, recipe, dependency, and .PHONY line. Writing the Makefile with a tool does NOT count as showing it. The Makefile MUST appear verbatim in your chat text as a code block, even if you also wrote it to a file. Never describe structure without showing the actual code. CRITICAL: use EXACTLY the command specified \u2014 if the task says "runs jest", write "jest" in the recipe, NEVER "npm test". npm test is NOT jest. Recipes need real TAB indentation. ONE .PHONY line listing ALL phony targets.'),r.push(" \u2022 For dataclasses, paste the COMPLETE dataclass code DIRECTLY in your text response \u2014 @dataclass decorator, all fields with types and defaults, full __post_init__ validation. Writing the file with a tool does NOT count as showing the code. The code MUST appear verbatim in your chat text, even if you also wrote it to a file."),r.push(" \u2022 For cron expressions, re-read the exact time boundaries in the task before writing. If asked for 8-18h, the range is 8,9,...,18 \u2014 write exactly what was asked, not an approximation."),r.push(' \u2022 When a task explicitly specifies a tool (e.g., "use tsc"), NEVER mention alternatives (e.g., "swc build") \u2014 use exactly what was requested.'),r.push(' \u2022 In Makefile prerequisites, NEVER use shell glob patterns like src/**/*.ts \u2014 make does not expand these natively. Keep prerequisite lists explicit or omit them. When a Makefile target says "runs jest", call jest directly in the recipe (not npm test).'),r.push(" \u2022 For bash in-place text replacements with backups: use ONLY ONE backup method \u2014 either sed -i.bak (let sed create the backup) OR cp file file.bak followed by sed -i (no extension). Never use both cp and sed -i.bak together \u2014 that produces redundant double backups (file.bak and file.bak.bak)."),r.push(" \u2022 For iterative array-flattening (flattenDeep): use push() and reverse() at the end \u2014 NEVER unshift(). unshift is O(n) per call making the whole function O(n^2). The iterative version MUST use a loop (while/for) and an explicit stack array \u2014 zero recursive calls. If a function calls itself, it is recursive regardless of its name. Never label a recursive function as iterative."),r.push(" \u2022 FORBIDDEN: when refactoring callbacks to async/await, NEVER write try { ... } catch(e) { throw e } \u2014 this is an explicit anti-pattern. WRONG: async function f() { try { const d = await readFile(..); await writeFile(.., d); } catch(e) { throw e; } } \u2014 RIGHT: async function f() { const d = await readFile(..); await writeFile(.., d); } \u2014 omit the try-catch entirely, let rejections propagate."),r.push(" \u2022 Express/fetch error handling: When adding error handling to an Express route that fetches by ID: (1) validate the ID parameter first (check it exists and is a valid format), (2) wrap fetch in try-catch, (3) check response.ok and handle 404 specifically, (4) call next(error) to pass errors to Express error\u2011handling middleware \u2014 do not just send a raw 500 response."),r.push(' \u2022 Docker HEALTHCHECK: always include --start-period=30s (or appropriate startup time) so the container has time to initialise before failures are counted. Also note that curl may not be available in minimal Node.js images \u2014 offer wget or "node -e" as alternatives.'),r.push(' \u2022 When fixing a bash word-splitting bug like "for f in $(ls *.txt)": replace the entire $(ls *.txt) with a bare glob directly \u2014 "for f in *.txt". The fix is eliminating the ls command and $() subshell entirely. Emphasise this in the explanation: the glob in the for loop prevents word splitting because the shell expands the glob into separate words before the loop \u2014 there is no subshell output to split. CRITICAL: NEVER suggest "ls -N" or any ls variant as a fix \u2014 ls -N outputs filenames one per line, but word splitting still occurs on each line when used in a subshell expansion. The only correct fix is the bare glob pattern.');let i=e||"English";r.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${i}.`);let a=n||"English";return r.push(`COMMIT MESSAGES: Write all git commit messages in ${a}.`),s&&r.push(`
|
|
934
934
|
This is a hard requirement. Always respond in ${s}. Do NOT switch to any other language \u2014 even if the user writes to you in German, French, or any other language, your reply MUST be in ${s}.`),r.join(`
|
|
935
935
|
`)+`
|
|
936
936
|
|
|
937
|
-
`}function
|
|
937
|
+
`}function UM(t){let e=FM(t);return wf()?`# Current Turn Language (CRITICAL \u2014 enforce strictly)
|
|
938
|
+
This repository is English-only. You MUST answer this turn in English, even if the user's message is written in German or any other language. Treat non-English input as content to answer, not as a language-switch instruction. Do NOT switch to another language because of the user's wording, repository files, prior conversation, examples, or project instructions.
|
|
939
|
+
|
|
940
|
+
`:`# Current Turn Language (CRITICAL \u2014 enforce strictly)
|
|
938
941
|
The current user message is in ${e}. You MUST answer this turn in ${e}. Do NOT switch to another language because of repository files, prior conversation, examples, or project instructions.
|
|
939
942
|
|
|
940
|
-
`}function
|
|
943
|
+
`}function WM(){if(ur!==null)return ur;try{let e=QO().flatMap(s=>s.models.map(r=>({spec:`${s.name}:${r.id}`,tier:ZO(r.id,s.name),name:r.name})));if(e.length<2)return ur="","";let n={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
|
|
941
944
|
# Sub-Agent Model Routing
|
|
942
945
|
|
|
943
946
|
`;o+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',o+=`| Model | Tier | Auto-assigned for |
|
|
944
947
|
|---|---|---|
|
|
945
948
|
`;for(let s of e)o+=`| ${s.spec} | ${s.tier} | ${n[s.tier]||s.tier} |
|
|
946
|
-
`;return ur=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),ur="",""}}var mf="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function
|
|
949
|
+
`;return ur=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),ur="",""}}var mf="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function HM(t){let e=t.indexOf(mf);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+mf.length).trimStart()}}async function gf(){let t=await qw()+":"+In();if(vi!==null&&t===sf)return vi;let e=await $O(process.cwd()),n=AO(),o=zO(),s=Ci()?DO():"",r=BM(),i=OO(),a=tM(In());return vi=`${a?`## Model Briefing
|
|
947
950
|
${a}
|
|
948
951
|
|
|
949
952
|
---
|
|
@@ -1204,7 +1207,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
|
|
|
1204
1207
|
- Instead: use bash with inline node -e '...' for quick one-off checks.
|
|
1205
1208
|
- If the test is worth keeping, write it to tests/ with a proper name.
|
|
1206
1209
|
- Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
|
|
1207
|
-
${
|
|
1210
|
+
${WM()}
|
|
1208
1211
|
|
|
1209
1212
|
# Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
|
|
1210
1213
|
|
|
@@ -1396,20 +1399,20 @@ class ErrorBoundary extends React.Component {
|
|
|
1396
1399
|
- Use migrations for schema changes, never manual ALTER TABLE
|
|
1397
1400
|
- Add database-level constraints (unique, foreign key, check) not just app-level
|
|
1398
1401
|
|
|
1399
|
-
`,sf=t,vi}function
|
|
1400
|
-
`):[]).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=
|
|
1401
|
-
\u{1F4E6} ${m}${h}`}}catch{}return u}function
|
|
1402
|
-
${$.dim} ${a}${$.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`;
|
|
1403
|
-
`),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)})}function
|
|
1402
|
+
`,sf=t,vi}function Yw(){yf.clear(),Bw.clear(),Ic.clear(),Ai.clear(),Uw.clear(),jc.clear(),Oi.clear(),Qn.clear(),hs.clear(),Mi.clear(),yn.clear(),_o.clear(),zc.clear(),cf.clear(),$n=0,Si=0,Dc=0,rn=!1,Fc=0,yo=-1,uf=!1,Bc=0,Uc=!1,bn=0,_n=!1,Ln=0,xn=0,Et=!1,Kt="",Ei=0,Wc="",$o=0,Hc="",wo=0,wn=!1,df=!1,De="plan",Kc=0,Te=!1,jn=null,ff=null,pf=null,vo=[],pr=0,hr=0,mr=0,gr=!1,yr=0,As=0,xo=null,Ni.clear(),Pi.clear(),lf="",qc=0}function GM(){j=[],Ti=null,dr="",fr=0,of="",rf=0,Yw();try{let{resetCompactionFailures:t}=Vu();t()}catch{}try{let{cancelAllJobs:t}=Vo();t()}catch{}}function YM(){j.length>Tw&&j.splice(0,j.length-Tw)}function wf(){try{let t=require("fs"),n=require("path").join(process.cwd(),"AGENTS.md");if(!t.existsSync(n))return!1;let o=t.readFileSync(n,"utf8");return/all.*english/i.test(o)&&/no german/i.test(o)}catch{return!1}}function Zd(t,e,n,o=1500){return!t||!e?!1:t===e&&Date.now()-n<o}function zM(){return j.length}function KM(){return j}function XM(t){j=t}async function VM(){let{execFile:t}=require("child_process"),e=require("fs"),n=process.cwd(),o=(f,p)=>new Promise(m=>{t(f,p,{cwd:n,timeout:3e3},(h,g)=>{m(h?"":(g||"").trim())})}),[s]=await Promise.all([o("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(s?s.split(`
|
|
1403
|
+
`):[]).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=lt.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+=`
|
|
1404
|
+
\u{1F4E6} ${m}${h}`}}catch{}return u}function JM(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 Ve(t,e,n,o,s,{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(s){let u=Date.now()-s;c=Math.round(u/1e3),a+=c>=60?` \xB7 ${Math.floor(c/60)}m ${c%60}s`:` \xB7 ${c}s`}if(n.size>0&&(a+=` \xB7 ${n.size} ${n.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
|
|
1405
|
+
${$.dim} ${a}${$.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`;JM(u)}if(Pi.size>0&&Ni.size>0)for(let u of Pi){let d=Ni.get(u);d&&console.log(`${$.dim} \u2714 task #${u} auto-matched: ${d.slice(0,60)}${$.reset}`)}n.size>0?console.log(`${$.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${$.reset}`):!r&&o.size>=5&&n.size===0&&t>=3?console.log(`${$.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${$.reset}`):o.size>0&&t>=2&&console.log(`${$.dim} \u{1F4A1} /save \xB7 /clear${$.reset}`)}async function ZM(){if(!process.stdout.isTTY)return{action:"quit"};let t=lr(),e=In(),n=Yc.fast?.[t],o=Yc.strong?.[t],s=n&&n!==e,r=o&&o!==e&&o!==n,i=[];i.push({key:"r",label:`Retry with current model ${$.dim}(${e})${$.reset}`}),s&&i.push({key:"f",label:`Switch to ${$.bold}${n}${$.reset} ${$.dim}\u2014 fast, low latency${$.reset}`,model:n}),r&&i.push({key:"s",label:`Switch to ${$.bold}${o}${$.reset} ${$.dim}\u2014 reliable tool-calling, medium speed${$.reset}`,model:o}),i.push({key:"q",label:`${$.dim}Quit${$.reset}`}),console.log(),console.log(`${$.yellow} Stream stale \u2014 all retries exhausted.${$.reset} What would you like to do?`);for(let a of i)console.log(` ${$.cyan}[${a.key}]${$.reset} ${a.label}`);return process.stdout.write(` ${$.yellow}> ${$.reset}`),new Promise(a=>{let c=process.stdin,u=c.isRaw;c.setRawMode(!0),c.resume(),c.setEncoding("utf8");let d=!1,f=p=>{if(d)return;d=!0,c.removeListener("data",f),c.setRawMode(u||!1),c.pause();let m=p.toLowerCase().trim();if(process.stdout.write(`${m}
|
|
1406
|
+
`),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)})}function QM(t){let e=/https?:\/\/[^\s/]+(\/[^\s?#]+)/g,n=new Set,o;for(;(o=e.exec(t))!==null;){let s=o[1].replace(/\/$/,"");s.length>1&&s.split("/").filter(i=>i.length>2).forEach(i=>n.add(i))}return Array.from(n)}function eN(t){let e=[];return(t.includes("@click")||t.includes("x-data")||t.includes("v-if")||t.includes("v-model"))&&e.push("Snippet contains Vue/Alpine.js directives (e.g., @click, v-model). Do not restrict your search to just .js/.ts/.vue files; also search .html and .py (templates) if appropriate."),(t.includes("className=")||t.includes("useEffect"))&&e.push("Snippet appears to be React. Look in .jsx, .tsx, .js, .ts files."),e}var es=null;async function tN(t,e=null,n={}){let o=eM(In());Ew=o.staleWarn,zd=o.staleAbort,es=e;let s=t;if(Ti&&typeof t=="string"&&(s=`${Ti}
|
|
1404
1407
|
|
|
1405
|
-
${t}`,Ti=null),typeof s=="string"){let Oe=
|
|
1408
|
+
${t}`,Ti=null),typeof s=="string"){let Oe=QM(s),Se=eN(s);(Oe.length>0||Se.length>0)&&(s+=`
|
|
1406
1409
|
|
|
1407
1410
|
[System Note for Assistant: To resolve this task faster, consider these hints:
|
|
1408
1411
|
`,Oe.length>0&&(s+=`- The user mentioned URLs containing the paths/folders: ${Oe.join(", ")}. Prioritize searching these folder names using glob or grep first.
|
|
1409
1412
|
`),Se.length>0&&Se.forEach(Fe=>{s+=`- ${Fe}
|
|
1410
|
-
`}),s+="Always prefer parallel search execution if unsure.]")}typeof s=="string"&&
|
|
1413
|
+
`}),s+="Always prefer parallel search execution if unsure.]")}typeof s=="string"&&jw(s)&&(s+=`
|
|
1411
1414
|
|
|
1412
|
-
[Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=typeof t=="string"?
|
|
1415
|
+
[Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=typeof t=="string"?yw(t):null,i=Iw(s);i&&typeof i.then=="function"&&(i=await i),j.push({role:"user",content:i}),YM();let a=n.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",c=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:Oe,runOrchestrated:Se}=yi(),Fe=Oe(typeof t=="string"?t:"");if(a&&Fe.isComplex&&Fe.estimatedGoals>=c){console.log(`${$.yellow}\u26A1 Auto-orchestrate: ${Fe.estimatedGoals} goals \u2192 parallel agents${$.reset}`);let dt=await Se(t,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});if(dt&&dt.synthesis){let vt=dt.synthesis.summary||"",$s=dt.synthesis.filesChanged?.length?`
|
|
1413
1416
|
|
|
1414
1417
|
Files changed: ${dt.synthesis.filesChanged.join(", ")}`:"",bt=dt.synthesis.conflicts?.length?`
|
|
1415
1418
|
|
|
@@ -1422,35 +1425,35 @@ ${Se.instructions}`).join(`
|
|
|
1422
1425
|
`);m+=`
|
|
1423
1426
|
`+Oe+`
|
|
1424
1427
|
`}m+=`
|
|
1425
|
-
`+
|
|
1428
|
+
`+UM(t);let y=[{role:"system",content:m},...j];mw(In());let w=new cr(Fd());w.start();let x=j.length===1,S=x?VM().catch(()=>null):Promise.resolve(null),k=x?MO(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),v=At(),[{messages:C,compressed:q,compacted:D,tokensRemoved:ee},ue,le]=await Promise.all([wO(y,v),S,k]),de=Pn(y,v);if(w.stop(),ue&&console.log(`${$.dim}${ue}${$.reset}`),D)console.log(`${$.dim} [context compacted \u2014 summary (~${ee} tokens freed)]${$.reset}`);else if(q){let Oe=de.limit>0?Math.round(ee/de.limit*100):0;B(`${$.dim} [context compressed \u2014 ~${ee} tokens freed (${Oe}%)]${$.reset}`)}de.percentage>85&&B(`${$.yellow} \u26A0 Context ${Math.round(de.percentage)}% used (${Math.round(100-de.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${$.reset}`);let M=C;if(le&&x&&(M=[M[0],{role:"user",content:`[Server probe at task start]
|
|
1426
1429
|
${le}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...M.slice(1)]),r&&x){let Oe=r.shouldPreferSsh?`[Runtime URL detected]
|
|
1427
1430
|
The user linked a live app URL (${r.url}) and described broken behavior. Treat this as a runtime/deployed-instance issue first. Reproduce it with browser_open or browser_screenshot on the URL before reading local files. Because this URL matches server profile "${r.matchedName}", prefer ssh_exec/service_logs on that server for investigation before local repo inspection.`:`[Runtime URL detected]
|
|
1428
1431
|
The user linked a live app URL (${r.url}) and described broken behavior. Treat this as a runtime issue first. Reproduce it with browser_open or browser_screenshot before reading local files. Only inspect the local repo after you have confirmed the live behavior.`;M=[M[0],{role:"user",content:Oe},{role:"assistant",content:"Understood \u2014 I will inspect the live app/runtime first."},...M.slice(1)]}if(x){let Oe=NO(typeof t=="string"?t:"");Oe&&(M=[M[0],{role:"user",content:`[EXAMPLE \u2014 illustrative only, not the real task]
|
|
1429
1432
|
`+Oe.user},{role:"assistant",content:Oe.assistant+`
|
|
1430
|
-
[END EXAMPLE \u2014 wait for the real user request below]`},...M.slice(1)])}if(Pn(M,At()).percentage>=65){let{messages:Se,tokensRemoved:Fe}=Vn(M,At());Fe>0&&(M=Se,console.log(`${$.dim} [pre-flight compress \u2014 ${Fe} tokens freed, now ${Math.round(Pn(M,At()).percentage)}% used]${$.reset}`))}let G=0,te=0,ge=0,xe=0,Ne=0,Ae=9,ke=0,E=new Set,P=(()=>{let Oe=j.find(Se=>Se.role==="user");return typeof Oe?.content=="string"?Oe.content:""})(),W=typeof P=="string"?
|
|
1431
|
-
`),Se=Xd(Oe);Se&&(Et=!0,Kt=Se.slice(0,120),B(`${$.yellow} \u26A1 Root cause in briefing: ${Kt} \u2014 fix phase active from start (read budget: 3)${$.reset}`))}if(!Et&&!wn&&/\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(P)&&(wn=!0,B(`${$.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${$.reset}`)),j.length<=1&&!n.skipPhaseRouting&&(Te=RO(),Te)){xo=TO(P)?.id||"coding";let Se=
|
|
1432
|
-
`);Se()&&Date.now()<Fe;)await new Promise(dt=>setTimeout(dt,500).unref()),Nc(j,M)}Nc(j,M),j.length>0&&We(j)}},ys=typeof t=="string"?t.trim():"",
|
|
1433
|
+
[END EXAMPLE \u2014 wait for the real user request below]`},...M.slice(1)])}if(Pn(M,At()).percentage>=65){let{messages:Se,tokensRemoved:Fe}=Vn(M,At());Fe>0&&(M=Se,console.log(`${$.dim} [pre-flight compress \u2014 ${Fe} tokens freed, now ${Math.round(Pn(M,At()).percentage)}% used]${$.reset}`))}let G=0,te=0,ge=0,xe=0,Ne=0,Ae=9,ke=0,E=new Set,P=(()=>{let Oe=j.find(Se=>Se.role==="user");return typeof Oe?.content=="string"?Oe.content:""})(),W=typeof P=="string"?yw(P):null,oe=OM(P),O=/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(P)||!!W?.shouldPreferSsh,R=!!W,Q=0;if(!Et){let Oe=j.filter(Fe=>Fe.role==="user"||Fe.role==="tool").map(Fe=>typeof Fe.content=="string"?Fe.content:"").join(`
|
|
1434
|
+
`),Se=Xd(Oe);Se&&(Et=!0,Kt=Se.slice(0,120),B(`${$.yellow} \u26A1 Root cause in briefing: ${Kt} \u2014 fix phase active from start (read budget: 3)${$.reset}`))}if(!Et&&!wn&&/\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(P)&&(wn=!0,B(`${$.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${$.reset}`)),j.length<=1&&!n.skipPhaseRouting&&!AM(P)&&(Te=RO(),Te)){xo=TO(P)?.id||"coding";let Se=Aw(P);if(De=Se?"implement":"plan",jn=ef(De,xo),Kc=0,pr=0,As=0,Ri=null,go.clear(),process.stdout.isTTY&&console.log(Se?`${$.dim} \u21B3 Phase routing: implement(${jn||"default"}) \u2192 verify ${$.yellow}[plan skipped: direct file task]${$.reset}`:`${$.dim} \u21B3 Phase routing: plan(${jn||"default"}) \u2192 implement \u2192 verify${$.reset}`),B(Se?`${$.cyan} \u26A1 Phase routing enabled \u2014 skipping plan phase for direct file task, starting in implement with ${jn||"default model"} (category: ${xo})${$.reset}`:`${$.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${jn||"default model"} (category: ${xo})${$.reset}`),Se&&oe.length>0){let dt={role:"user",content:`[SYSTEM] This is a direct file task targeting: ${oe.slice(0,3).join(", ")}. Modify only the explicitly requested file(s) unless the user asks for more. Do NOT create extra helper or test files for verification. Prefer inline verification with bash or by reading the edited file.`};j.push(dt),M.push(dt)}}let N=0,U=new Map,F=new Set,pe=new Set,qe=new Set,Ie=0,Pt=0,Je=0,ot=0,Pe=Date.now(),Tr=new mO(nM),Ji=Mi,Ze=n.skillLoop?10:1,Zi=3*Ze,Ro=5*Ze,Qi=yf,H_=5*Ze,G_=8*Ze,Y_=Bw,z_=(Te?6:4)*Ze,K_=(Te?10:7)*Ze,$l=Ic,X_=(Te?5:3)*Ze,ea=(Te?8:5)*Ze,V_=Uw,J_=(Te?4:3)*Ze,Z_=(Te?6:4)*Ze,Q_=3*Ze,ex=4*Ze,Co=Qn,tx=(Te?6:4)*Ze,nx=(Te?10:8)*Ze,Ao=(Te?12:10)*Ze,sx=25,Is=0,ox=10*Ze,rx=15*Ze,js=0,hp=5*Ze,Ds=0,ix=2*Ze,ax=3,wl=0,Rr=10,cx=16,mp=n.skillLoop?999:o.investigationCap,gp=async()=>{let{hasPendingOrCompletedJobs:Oe,getPendingJobSummary:Se}=Vo();if(Oe()){if(Se()){let Fe=Date.now()+45e3;for(process.stderr.write(`${$.cyan} \u23F3 Waiting for background agents to finish\u2026${$.reset}
|
|
1435
|
+
`);Se()&&Date.now()<Fe;)await new Promise(dt=>setTimeout(dt,500).unref()),Nc(j,M)}Nc(j,M),j.length>0&&We(j)}},ys=typeof t=="string"?t.trim():"",yp=ys.length>0&&/^\s*(analyze|analyse|analysiere|explain|erkläre|describe|beschreib|review|audit|summari[sz]e|zusammenfass|list|liste|understand|document|documentation|docs|what is|what does|wie funktioniert|wie geht|how does|show me|zeig|show the|show all|tell me about|erzähl)/i.test(ys)&&!/\b(fix|bug|crash|error|implement|add|create|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|edit|write|delete|remove|install|setup|deploy|run)\b/i.test(ys),ta=ys.length>0&&/\b(analyze|analyse|explain|describe|review|audit|summari[sz]e|understand|document|scan|count|inventory|map|list|identify)\b/i.test(ys)&&/\b(create|write|generate|produce|output)\b/i.test(ys)&&/\b([A-Z0-9_-]+\.md|markdown|report|summary|overview|architecture|audit|table|documentation|docs|inventory|catalog)\b/i.test(ys)&&!/\b(fix|bug|crash|error|implement|add(?!\s+(?:to|into)\b)|change|update|refactor|rewrite|broken|fail|patch|migrate|port|build|delete|remove|install|setup|deploy|run)\b/i.test(ys),ut,Jt=n.maxIterations||(Te?ho(De):nf);yp&&(Jt=Math.min(Jt,4),B(`${$.dim} \u21B3 Analysis-only prompt detected \u2014 iter cap=${Jt}${$.reset}`));let bl=0,$p=3,_l=!1,na=0,xl=!1;e:for(;;){for(_l=!1,ut=0;ut<Jt&&!Pc()?.aborted;ut++){Nc(j,M);{let _=At(),b=Pn(M,_),ne=N===0?65:78;if(b.percentage>=ne){if(F.size>0||Te&&De!=="plan"){let re=_O(j,{filesModified:F,currentPhase:Te?De:null});if(re){let Y=M.findIndex(I=>I._progressSnapshot);Y!==-1&&M.splice(Y,1);let me=M.findIndex(I=>I.role==="system");M.splice(me+1,0,re)}}let{messages:V,tokensRemoved:se}=Vn(M,_,N===0);if(se>0&&(M=V,se>50&&console.log(`${$.dim} [auto-compressed \u2014 ~${se} tokens freed, now ${Math.round(Pn(M,_).percentage)}%]${$.reset}`),wn&&F.size>=3)){let re=[...F].map(me=>me.split("/").pop()).slice(0,10).join(", "),Y={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${F.size} files: ${re}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};M.push(Y)}}}if(rn&&!Et&&Ei<2){Ei++;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."};M.push(_),j.push(_),B(`${$.yellow} \u26A0 Pre-call SSH-blocked nudge #${Ei} injected \u2014 model told to synthesize${$.reset}`)}rn||(Ei=0);let Se=!0;N>0&&UO();let Fe=null;if(d&&d.isActive())d._paused&&d.resume();else if(!d){let _,b=WO();if(b&&b.total>1){let se=b.description.length>40?b.description.slice(0,37)+"\u2026":b.description;_=`Plan step ${b.current}/${b.total}: ${se}`}else _=N>0?`${Fd()} (step ${N+1})`:Fd();let{getPendingJobSummary:ne}=Vo(),V=ne();V&&(_+=` [${V}]`),Fe=new cr(_),Fe.start()}let dt=!0,vt="",$s=!1,bt=new HO,dn,vl=Date.now(),sa=!1,kl=new AbortController,wp=setInterval(()=>{let _=Date.now()-vl;if(_>=zd)bt._clearCursorLine(),B(`${$.yellow} \u26A0 Stream stale for ${Math.round(_/1e3)}s \u2014 aborting and retrying${$.reset}`),kl.abort();else if(_>=Ew&&!sa){sa=!0,bt._clearCursorLine();let b=Yc.fast?.[lr()],ne=ge>0?` (retry ${ge+1}/${Oc})`:"",V=Math.round((zd-_)/1e3);B(`${$.yellow} \u26A0 No tokens received for ${Math.round(_/1e3)}s \u2014 waiting...${ne}${$.reset}`),b&&b!==In()?console.log(`${$.dim} \u{1F4A1} Will auto-switch to ${b} in ~${V}s if no tokens arrive${$.reset}`):console.log(`${$.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${V}s${$.reset}`)}},5e3),fn="",ns=null;try{let _=Dw(At()),b=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),ne=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),V;Ci()?V=_.filter(Y=>Mw.has(Y.function.name)):Te&&De==="plan"?V=_.filter(Y=>b.has(Y.function.name)):Te&&De==="verify"?V=_.filter(Y=>ne.has(Y.function.name)):V=_;let se=Pc(),re=new AbortController;se&&se.addEventListener("abort",()=>re.abort(),{once:!0}),kl.signal.addEventListener("abort",()=>re.abort(),{once:!0}),dn=await gw(M,V,{signal:re.signal,...jn?{model:jn}:{},onThinkingToken:()=>{vl=Date.now(),sa=!1,es?.onThinkingToken&&es.onThinkingToken()},onToken:Y=>{if(vl=Date.now(),sa=!1,es?.onToken){es.onToken(Y),vt+=Y;return}if(vt+=Y,!$s&&vt.length>400&&vt.length%250<Y.length+1){let me=tf(vt,3);me.truncated&&($s=!0,bt._clearCursorLine?.(),B(`${$.yellow} \u26A0 LLM stream loop detected (${me.repeatCount}\xD7 repeated) \u2014 suppressing display${$.reset}`))}$s||(fn+=Y,process.stdout.isTTY?ns||(ns=setTimeout(()=>{fn&&bt&&bt.push(fn),fn="",ns=null},50)):(bt.push(fn),fn=""),dt&&(d&&!d._paused?d.pause():Fe&&Fe.stop(),Se||(Se=!0),bt.startCursor(),dt=!1))}})}catch(_){if(clearInterval(wp),ns&&(clearTimeout(ns),ns=null),fn&&bt&&(bt.push(fn),fn=""),d&&!d._paused&&d.pause(),Fe&&Fe.stop(),bt.stopCursor(),kl.signal.aborted&&!Pc()?.aborted){if(ge++,ge>Oc){if(xe<1){xe++,ar("Stale retries exhausted \u2014 last-resort force-compress...",$.yellow);let me=At(),{messages:I,tokensRemoved:J}=Vn(M,me);M=I,J>50&&B(`${$.dim} [force-compressed \u2014 ~${J} tokens freed]${$.reset}`),ge=0,ut--;continue}d&&(d.stop(),d=null);let Y=await ZM();if(Y.action==="quit"){u(null),Ve(N,U,F,pe,Pe),We(j);break}Y.action==="switch"&&(Bd(`${Y.provider}:${Y.model}`),console.log(`${$.green} \u2713 Switched to ${Y.provider}:${Y.model}${$.reset}`)),ge=0,ut--;continue}let se=ge===1?3e3:5e3;if(ge>=1&&ke<1){ke++,ar(`Stale retry ${ge}/${Oc} \u2014 force-compressing before retry...`,$.yellow);let Y=At(),{messages:me,tokensRemoved:I}=Vn(M,Y,!0);if(M=me,I>0&&I>50&&B(`${$.dim} [force-compressed \u2014 ~${I} tokens freed]${$.reset}`),xM){let J=Yc.fast?.[lr()];J&&J!==In()&&(Bd(`${lr()}:${J}`),console.log(`${$.cyan} \u26A1 Auto-switched to ${J} to avoid further stale timeouts${$.reset}`),console.log(`${$.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${$.reset}`))}}else B(`${$.yellow} \u26A0 Stale retry ${ge}/${Oc} \u2014 retrying in ${se/1e3}s...${$.reset}`);let re=new cr(`Waiting ${se/1e3}s before retry...`);re.start(),await new Promise(Y=>setTimeout(Y,se)),re.stop(),ut--;continue}if(_.name==="AbortError"||_.name==="CanceledError"||_.message?.includes("canceled")||_.message?.includes("aborted")){d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe),We(j);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")){let se=In?In():"unknown",re=I=>I.includes(":")&&I.split(":")[0].match(/^[a-z]+$/)&&!I.split(":")[1].includes(":")?I.split(":").slice(1).join(":"):I;E.add(re(se));let me=(()=>{let I=[];process.env.NEX_FALLBACK_MODEL&&I.push(process.env.NEX_FALLBACK_MODEL);try{let{getModelForCategory:J}=Xn(),L=["agentic","coding","plan","verify","sysadmin","data","frontend"];for(let Z of L){let $e=J(Z);$e&&!I.includes($e)&&I.push($e)}}catch{}return I.filter(J=>!E.has(re(J)))})()[0];if(me){console.log(`${$.yellow} \u26A0 Model ${se} unavailable (404) \u2014 switching to ${me}${$.reset}`),Bd(me),mw(me),ut--;continue}b=`Model not found (404): ${se} \u2014 no fallback available. Set NEX_FALLBACK_MODEL or run /models to list available models`,console.log(`${$.red} \u2717 ${b}${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe),We(j);break}else if(_.message.includes("400")){if(xe<3&&Ne<Ae){xe++,Ne++;let se=N===0&&xe===1,re=se||xe===3||ke>0;if(se){xe=3;let J=_.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);ar(`Bad request (400) \u2014 ${J||"system prompt too large"}, compressing...`,$.yellow)}else ar(re?`Bad request (400) \u2014 nuclear compression (attempt ${xe}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${xe}/3)`,$.yellow);let Y=At(),{messages:me,tokensRemoved:I}=Vn(M,Y,re);M=me,I>50&&B(`${$.dim} [force-compressed \u2014 ~${I} tokens freed]${$.reset}`),ut--;continue}{let se=M.find(L=>L.role==="system"),re=M.find(L=>L.role==="user"&&!String(L.content).startsWith("[SYSTEM")&&!String(L.content).startsWith("BLOCKED:")),Y=[se,re].filter(Boolean),{getUsage:me}=en(),I=en().estimateMessagesTokens(Y),J=en().estimateMessagesTokens(M);if(I<J){let L=[],Z=j.filter(H=>H.role==="assistant"&&typeof H.content=="string"&&H.content.trim().length>30).slice(-5).map(H=>H.content.trim().slice(0,300).replace(/\n+/g," "));Z.length>0&&L.push(`Key findings:
|
|
1433
1436
|
`+Z.map(H=>`- ${H}`).join(`
|
|
1434
1437
|
`));let $e=j.filter(H=>H.role==="tool"&&typeof H.content=="string"&&!H.content.startsWith("BLOCKED:")&&H.content.trim().length>10).slice(-5).map(H=>H.content.trim().split(`
|
|
1435
1438
|
`).slice(0,8).join(`
|
|
1436
1439
|
`).slice(0,500));if($e.length>0&&L.push(`Tool results summary:
|
|
1437
1440
|
`+$e.map(H=>`- ${H}`).join(`
|
|
1438
|
-
`)),F.size>0){let H=[...F].map(Ce=>Ce.split("/").slice(-2).join("/")).join(", ");L.unshift(`Already modified: ${H} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(pe.size>0){let H=[...pe].map(Ce=>Ce.split("/").slice(-2).join("/")).join(", ");L.push(`Files already investigated: ${H}`)}let Re=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(Re,JSON.stringify({filesWritten:[...F].map(H=>H.split("/").slice(-2).join("/")),filesRead:[...pe].map(H=>H.split("/").slice(-2).join("/")),isCreationTask:wn,wipeNumber:Si+1,timestamp:Date.now()},null,2)),L.push(`Session checkpoint: ${Re} \u2014 read it for exact file list`)}catch{}let fe=0;{let Ce=((typeof re?.content=="string"?re.content:Array.isArray(re?.content)?re.content.filter($t=>$t.type==="text").map($t=>$t.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($t=>$t.trim()).filter(Boolean),je=[...F],
|
|
1441
|
+
`)),F.size>0){let H=[...F].map(Ce=>Ce.split("/").slice(-2).join("/")).join(", ");L.unshift(`Already modified: ${H} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(pe.size>0){let H=[...pe].map(Ce=>Ce.split("/").slice(-2).join("/")).join(", ");L.push(`Files already investigated: ${H}`)}let Re=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(Re,JSON.stringify({filesWritten:[...F].map(H=>H.split("/").slice(-2).join("/")),filesRead:[...pe].map(H=>H.split("/").slice(-2).join("/")),isCreationTask:wn,wipeNumber:Si+1,timestamp:Date.now()},null,2)),L.push(`Session checkpoint: ${Re} \u2014 read it for exact file list`)}catch{}let fe=0;{let Ce=((typeof re?.content=="string"?re.content:Array.isArray(re?.content)?re.content.filter($t=>$t.type==="text").map($t=>$t.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($t=>$t.trim()).filter(Boolean),je=[...F],rt=Ce.filter($t=>!je.some(ia=>ia.endsWith($t)||$t.endsWith(ia.split("/").pop())));fe=rt.length;let ft=[...j].reverse().find($t=>$t.role==="tool"&&typeof $t.content=="string"&&!$t.content.startsWith("BLOCKED:")&&$t.content.length>5),pn={completed:je.map($t=>$t.split("/").slice(-2).join("/")),pending:rt.length>0?rt:je.length===0?["(task files not yet identified)"]:[],lastEdit:ft?ft.content.trim().slice(0,120):null};(pn.completed.length>0||pn.pending.length>0)&&L.unshift(`Work manifest:
|
|
1439
1442
|
${JSON.stringify(pn,null,2)}`)}if(L.length>0){let H={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
|
|
1440
1443
|
${L.join(`
|
|
1441
1444
|
`)}
|
|
1442
1445
|
Continue implementing the fixes based on these findings.`};Y.push(H)}if(Si>=3){let H=F.size>0?`
|
|
1443
1446
|
Files modified so far: ${[...F].map(Ce=>Ce.split("/").slice(-1)[0]).join(", ")}`:"";B(`${$.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${$.reset}`),console.log(`${$.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${H?$.dim+H:""}${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe,{suppressHint:!0}),We(j);break}M=Y,Si++,yo=10+Math.min(fe*3,7),uf=!0,Bc=F.size,Uc=!1,$n=0,Q=0;for(let[H,Ce]of Qn){let je=Ce?.count??Ce??0;Vd(Qn,H,je>=2?je:1)}for(let[H]of hs)Jn(Qn,H)<2&&hs.delete(H);yn.clear(),_o.clear(),wn&&xn>0&&(_n=!0,B(`${$.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${xn} edits already made)${$.reset}`));for(let[H]of Ic)Vd(Ic,H,ea-1);if(ar(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${J-I} tokens freed)`,$.yellow),Si>=1){let H=[...Qn.entries()].filter(([,ft])=>ft>=Ao).map(([ft])=>ft.split("/").slice(-1)[0]),Ce=H.length>0?`
|
|
1444
1447
|
|
|
1445
|
-
Files already at read cap \u2014 use grep_search instead: ${H.join(", ")}`:"",
|
|
1446
|
-
Use /undo to revert changes made during this session.${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe),We(j);break e}let se=Math.min(2e3*Math.pow(2,te-1),3e4),re=new cr(`API temporarily unavailable \u2014 retrying in ${Math.round(se/1e3)}s (${te}/${Yd}). Your changes are safe.`);re.start(),await new Promise(Y=>setTimeout(Y,se)),re.stop(),ut--;continue}d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe),We(j);break}if(clearInterval(
|
|
1447
|
-
`),Ve(N,U,F,pe,Pe),We(j);break e}let Z=await xi("implement",re);if(Z){j.push(Z),M.push(Z),ut=0,Jt=ho("implement");continue}}else if(De==="implement"&&(F.size>0||
|
|
1448
|
+
Files already at read cap \u2014 use grep_search instead: ${H.join(", ")}`:"",rt={role:"user",content:rn&&!Et?"[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.${Ce}`};j.push(rt),M.push(rt)}xe=0,ut--;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(`${$.red} \u2717 ${b}${$.reset}`),_.message.includes("429")){if(G++,G>Gd){console.log(`${$.red} Rate limit: max retries (${Gd}) exceeded. Try again later or use /budget to check your limits.${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe),We(j);break e}let se=Math.min(1e4*Math.pow(2,G-1),12e4),re=new cr(`Rate limit \u2014 waiting ${Math.round(se/1e3)}s (retry ${G}/${Gd})`);re.start(),await new Promise(Y=>setTimeout(Y,se)),re.stop();continue}let ne=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return Xe().getActiveProviderName()==="ollama"}catch{return!1}})();if(_.message.includes("socket disconnected")||_.message.includes("TLS")||_.message.includes("ECONNRESET")||_.message.includes("ECONNABORTED")||_.message.includes("ETIMEDOUT")||ne&&(_.message.includes("500")||_.message.includes("502")||_.message.includes("503")||_.message.includes("504")||_.message.includes("401")||_.message.includes("Unauthorized"))||_.code==="ECONNRESET"||_.code==="ECONNABORTED"){if(te++,te>Yd){console.log(`${$.red} Network error: max retries (${Yd}) exceeded. Check your connection and try again.
|
|
1449
|
+
Use /undo to revert changes made during this session.${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe),We(j);break e}let se=Math.min(2e3*Math.pow(2,te-1),3e4),re=new cr(`API temporarily unavailable \u2014 retrying in ${Math.round(se/1e3)}s (${te}/${Yd}). Your changes are safe.`);re.start(),await new Promise(Y=>setTimeout(Y,se)),re.stop(),ut--;continue}d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe),We(j);break}if(clearInterval(wp),G=0,te=0,dt&&(d&&!d._paused&&d.pause(),Fe&&Fe.stop()),ns&&(clearTimeout(ns),ns=null),fn&&bt&&(bt.push(fn),fn=""),vt&&bt.flush(),te=0,ge=0,dn&&dn.usage){let _=dn.usage.prompt_tokens||0,b=dn.usage.completion_tokens||0;ww(lr(),In(),_,b),f+=_+b,d&&d.setStats({tokens:f})}else if(dn&&!dn.usage){let _=M.map(V=>typeof V.content=="string"?V.content:Array.isArray(V.content)?V.content.map(se=>typeof se=="string"?se:se.text||"").join(""):"").join(" "),b=_w(_),ne=_w(dn.content||vt||"");ww(lr(),In(),b,ne),f+=b+ne,d&&d.setStats({tokens:f})}let{content:bp,tool_calls:Oo}=dn,Bn=Oo,Sl=!1;if(Array.isArray(Oo)&&Oo.length>0){let _=Oo.filter(b=>b?.function?.name==="ask_user");_.length>0&&(Bn=[_[0]],Sl=Oo.length!==1,Sl&&B(`${$.yellow} \u26A0 ask_user must run alone \u2014 deferring ${Oo.length-1} other tool call(s) until the user replies${$.reset}`))}let oa=tf(bp||""),_p=oa.truncated?oa.text:bp;oa.truncated&&B(`${$.yellow} \u26A0 LLM output loop detected (${oa.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${$.reset}`);let ra=cM(_p||""),Zt=ra.truncated?ra.text:_p;ra.truncated&&B(`${$.yellow} \u26A0 LLM output loop detected (${ra.repeatCount}\xD7 repeated window) \u2014 response truncated${$.reset}`);let Cr={role:"assistant",content:Zt||""};if(Bn&&Bn.length>0&&(Cr.tool_calls=Bn),j.push(Cr),M.push(Cr),yp&&!Ac(Zt||vt||"")&&F.size===0&&ot===0){B(`${$.green} \u2713 Analysis-only early exit: ${(Zt||"").length} chars produced, no file changes${$.reset}`),Cr.tool_calls&&delete Cr.tool_calls,Ve(N,U,F,pe,Pe),We(j);break e}if(!Et&&Zt&&Bn&&Bn.length>0){let _=Xd(Zt);if(_){Et=!0,Kt=_.slice(0,120),bn=0,_n=!1,Ln=0,B(`${$.yellow} \u26A1 Root cause in model analysis: ${Kt} \u2014 fix phase (read budget: 3)${$.reset}`);let b={role:"user",content:`[SYSTEM] Root cause identified: ${Kt}. Read only the file that needs fixing, then edit it. Do not read other files.`};j.push(b),M.push(b)}}if(!Bn||Bn.length===0){let _=(Zt||"").trim().length>0||vt.trim().length>0,b=!1;if(rn&&_&&(Mc>=2?B(`${$.yellow} \u26A0 SSH permanently blocked after ${Mc} storm warnings \u2014 no further SSH calls allowed${$.reset}`):(rn=!1,$n=Rr-4,b=!0)),b&&_){let re=(Zt||"").trim();if(re.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(re.slice(-200))){let me={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};M.push(me),j.push(me);continue}}if(!_&&N>0&&ut<nf-1){let re={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."};M.push(re),j.push(re);continue}let ne=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if(_&&ut<3&&ne.test((Zt||"").slice(0,600)))if(uf&&yo<=0||rn){B(`${$.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${$.reset}`);let Y={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."};M.push(Y),j.push(Y);continue}else{B(`${$.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${$.reset}`);let Y={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."};M.push(Y),j.push(Y);continue}if(n.skillLoop&&_&&N>3&&na<5){let re=(Zt||vt||"").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(re.slice(-600))){na=(na||0)+1,B(`${$.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${na}${$.reset}`);let me={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."};M.push(me),j.push(me);continue}}if(bo()&&!n.skillLoop&&(F.size>0||ot>0)&&_&&!Ac(Zt||vt||"")&&N>=1&&(!Te||De==="implement")){B(`${$.green} \u2713 Headless early exit: ${F.size} file(s) modified (+ ${ot} bash writes), substantive text response received${$.reset}`),Ve(N,U,F,pe,Pe),We(j);break e}let se=CM(Ri)?1:2;if(Te&&De==="plan"&&As>=se){B(`${$.cyan} \u21B3 Plan phase: ${As} consecutive blocks (last: ${Ri||"unknown"}) \u2014 auto-advancing to implement${$.reset}`),As=0,Ri=null;let re=await xi("implement","[auto-advance: task only requires direct action]");if(re){j.push(re),M.push(re),ut=0,Jt=ho("implement");continue}}if(Te&&_){let re=(Zt||vt||"").trim();if(De==="plan"){let Y=/\b(no match(es)?|not found|couldn'?t find|does not exist|no results|nothing found|no files|keine (Ergebnisse|Treffer|Übereinstimmung|Funde|passenden)|nicht gefunden|nichts gefunden)\b/i,me=Ww(re,Qn).length===0,I=Ai.size>0,J=Oi.size>0,L=re.length>1500;if(bo()&&me&&!I&&!J&&!L&&Y.test(re)){B(`${$.yellow} \u26A0 Plan phase: nothing actionable found \u2014 exiting gracefully${$.reset}`),process.stdout.isTTY&&process.stderr.write(`${$.yellow} \u26A0 Could not find the target in this project. The plan phase found no actionable items.${$.reset}
|
|
1450
|
+
`),Ve(N,U,F,pe,Pe),We(j);break e}let Z=await xi("implement",re);if(Z){j.push(Z),M.push(Z),ut=0,Jt=ho("implement");continue}}else if(De==="implement"&&(F.size>0||ot>0)){let Y=j.find(J=>J.role==="user"),me=typeof Y?.content=="string"?Y.content:"",I=await xi("verify",re,F,me);if(I){j.push(I),M.push(I),ut=0,Jt=Math.min(ho("verify")+Math.max(0,(F.size-2)*2),20);continue}}else if(De==="verify"){let Y=/\bPASS\b/i.test(re.slice(0,500)),I=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(re.slice(0,500)),J=hr>0||M.some(L=>L.role==="assistant"&&typeof L.content=="string"&&/\bPASS\b/i.test(L.content.slice(0,500)));if(bo()&&!n.skillLoop&&J&&!I&&!Ac(re)){B(`${$.green} \u2713 Verification phase complete (headless substantive summary)${$.reset}`),Ve(N,U,F,pe,Pe),We(j),wi(j);break e}if(I&&pr<3){pr++;let L={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
|
|
1448
1451
|
${re.slice(0,400)}
|
|
1449
1452
|
|
|
1450
1453
|
Fix the identified issues. This is attempt ${pr}/3.`};De="implement",jn=ef("implement",xo),j.push(L),M.push(L),ut=0,Jt=ho("implement"),B(`${$.yellow} \u21B3 Verify \u2192 implement loop-back #${pr} (issues found)${$.reset}`);continue}if(!I&&(!Y||hr===0)){if(mr<2){mr++;let L=[];hr===0&&L.push("run at least one verification tool"),Y||L.push("end your report with PASS or FAIL");let Z={role:"user",content:`[SYSTEM] Verification is incomplete: ${L.join(" and ")}. Do not stop yet. Re-read the modified files and/or run tests or linters, then respond with PASS or FAIL.`};j.push(Z),M.push(Z),B(`${$.yellow} \u26A0 Verify phase incomplete \u2014 nudging for evidence (${mr}/2)${$.reset}`);continue}B(`${$.yellow} \u26A0 Verify phase completion accepted without full markers after ${mr} nudges${$.reset}`)}if(B(`${$.green} \u2713 Verification phase complete${I?" (loop-back exhausted)":" (PASS)"}${$.reset}`),!I){Ve(N,U,F,pe,Pe),We(j),wi(j);break e}}}if(Ci()&&_&&N===0)if(Dc++,Dc>2)B(`${$.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${$.reset}`);else{let re={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.).
|
|
1451
1454
|
|
|
1452
1455
|
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.`};j.push(re),M.push(re),B(`${$.yellow} \u26A0 Plan rejected (${Dc}/2): no files read \u2014 forcing investigation${$.reset}`);continue}if(Ci()&&_){let re=(Zt||vt||"").trim();qO(re),vM(re);let Y=FO(re);if(Y.length>0){let me=j.find($e=>$e.role==="user"),I=typeof me?.content=="string"?me.content.slice(0,120):"Task";BO(I,Y);let J=Y.length===1?"step":"steps",L=!1;if(process.stdout.isTTY&&process.stdin.isTTY&&!process.env.JEST_WORKER_ID){let{approvePlan:$e,startExecution:Re,setPlanMode:fe}=Nn();process.stdout.write(`
|
|
1453
|
-
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${Y.length} ${J})${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${$.reset} ${$.yellow}[E]${$.reset}${$.dim}dit${$.reset} ${$.red}[R]${$.reset}${$.dim}eject${$.reset} ${$.dim}[\u21B5 = approve]:${$.reset} `);let H=process.stdin.isRaw,Ce=await new Promise(je=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",
|
|
1456
|
+
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${Y.length} ${J})${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${$.reset} ${$.yellow}[E]${$.reset}${$.dim}dit${$.reset} ${$.red}[R]${$.reset}${$.dim}eject${$.reset} ${$.dim}[\u21B5 = approve]:${$.reset} `);let H=process.stdin.isRaw,Ce=await new Promise(je=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",rt=>{try{process.stdin.setRawMode(H||!1)}catch{}let ft=rt.toString().toLowerCase()[0]||"\r";je(ft)})});if(process.stdout.write(`
|
|
1454
1457
|
`),Ce==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(Ce==="e")console.log(`${$.yellow}Type /plan edit to open in editor, or give feedback.${$.reset}`);else if($e()){Re(),fe(!1),af(),console.log(`${$.green}${$.bold}Approved!${$.reset} Executing ${Y.length} ${J}...`);let je=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1455
1458
|
|
|
1456
1459
|
Implement the following plan step by step. All tools are now available.
|
|
@@ -1463,27 +1466,27 @@ ${$.cyan}${$.bold}Plan ready.${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${
|
|
|
1463
1466
|
Implement the following plan step by step. All tools are now available.
|
|
1464
1467
|
|
|
1465
1468
|
${getPlanContent()||dn.content}`;j.push({role:"user",content:H}),M.push({role:"user",content:H}),me=!0}}else console.log(`
|
|
1466
|
-
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.dim}Type ${$.reset}${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ask follow-up questions to refine.${$.reset}`);if(me){d&&(d.stop(),d=null),ut--;continue}}}if(d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe),wn&&F.size>=3){let re=[...F].map(L=>L.split("/").pop()).slice(0,8).join(", "),Y=[...F].some(L=>L.endsWith("package.json")),me=[...F].some(L=>L.endsWith("requirements.txt")),I=[...F].some(L=>L.endsWith("package-lock.json")||L.endsWith("yarn.lock")||L.endsWith("pnpm-lock.yaml")),J=Y&&!I?"npm install not yet run":me?"pip install not yet run":null;Ti=`[Previous session created ${F.size} files: ${re}`+(J?` \u2014 ${J}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(wn&&!df&&N>0){let re=[...F].some(fe=>fe.endsWith("package.json")),Y=[...F].some(fe=>fe.endsWith("requirements.txt")||fe.endsWith("Pipfile")||fe.endsWith("pyproject.toml")),me=[...F].some(fe=>fe.endsWith("package-lock.json")||fe.endsWith("yarn.lock")||fe.endsWith("pnpm-lock.yaml")),I=j.flatMap(fe=>{let H=Array.isArray(fe.tool_calls)?fe.tool_calls:[],Ce=Array.isArray(fe.content)?fe.content.filter(je=>je?.type==="tool_use"):[];return[...H,...Ce]}).filter(fe=>{let H=fe.function?.name||fe.name||"";return H==="bash"||H==="Bash"}).map(fe=>{try{let H=fe.function?.arguments??fe.input??{};return(typeof H=="string"?JSON.parse(H):H)?.command||""}catch{return""}}),J=I.some(fe=>/pip\s+install|python\s+-m\s+venv/.test(fe)),L=I.some(fe=>/npm\s+install/.test(fe)),$e=[...F].some(fe=>/\/App\.(js|ts|jsx|tsx)$/.test(fe))&&!re&&!L;if(Y&&!J||re&&!me&&!L||$e){df=!0;let fe=[];Y&&!J&&fe.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),$e?fe.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):re&&!me&&!L&&fe.push("npm install");let H=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${fe.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;B(`${$.dim} [post-creation] bootstrapping environment (${fe.join(", ")})${$.reset}`),j.push({role:"user",content:H}),M.push({role:"user",content:H});continue}}if(N>0&&!n._isSummaryTurn&&Ac(Zt))try{B(`${$.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${$.reset}`);let re=F.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.",Y=[...M,{role:"user",content:re}],I=((await
|
|
1467
|
-
${I}`),j.push({role:"user",content:re},{role:"assistant",content:I}))}catch{}We(j),wi(j),await mp();return}N++,Kc++,N>=1&&(Se=!1);for(let _ of Bn){let b=_.function.name;U.set(b,(U.get(b)||0)+1)}if(N>=30&&!Rw){Rw=!0,B(`${$.yellow} \u26A0 Tool budget warning: ${N} tool calls used \u2014 nudging model to wrap up${$.reset}`);let _={role:"user",content:"[SYSTEM] \u26A0 You have used "+N+" tool calls. This is approaching the quality threshold (40). Wrap up NOW: write your final summary and stop. Do NOT run additional verification commands (git status, git diff, git log) \u2014 your changes are already committed and verified. Further tool calls will hurt session quality."};j.push(_),M.push(_)}let Me=await Promise.all(Bn.map(_=>kM(_)));if(xl){let _=new Set(["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"]);for(let b of Me)!b.canExecute||!_.has(b.fnName)||(b.canExecute=!1,b.errorResult={role:"tool",content:"BLOCKED: You already have enough evidence to produce the requested summary/document. Write the deliverable now and stop reading more files.",tool_call_id:b.callId})}{let _=Pn(M,At()),b=_.percentage,ne=Me.some(Y=>Y.canExecute&&Y.fnName==="read_file"&&!Y.args?.line_end),V=Me.filter(Y=>Y.canExecute&&Y.fnName==="read_file"&&Y.args?.path&&Jn(Co,Y.args.path)>=1&&!Y.args?.line_start).map(Y=>Y.args.path.split("/").slice(-2).join("/")),se=V.length>0;if(b>=70&&ne&&wl<70||b>=85&&wl<85||se){wl=b;let Y=b>=85?"URGENT":"WARNING",me;se?(Y="WARNING",me=`Full-file read of ${V.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):ne?me=`Unbounded read at ${Math.round(b)}% context \u2014 use line_start/line_end to avoid overflow.`:me="Use targeted reads (line_start/line_end) to save space.";let I={role:"user",content:`[SYSTEM ${Y}] Context ${Math.round(b)}% used (${_.used}/${_.limit} tokens). ${me}`};if(j.push(I),M.push(I),b>=85){let J=se?` (re-read of: ${V.join(", ")})`:"";B(`${$.yellow} \u26A0 Context ${Math.round(b)}% used \u2014 agent warned to use targeted reads${J}${$.reset}`)}}}let El=new Map;for(let _ of Me){if(!_.canExecute||_.fnName!=="read_file")continue;let b=_.args?.path;if(!b)continue;let ne=Jn(Co,b),V=El.get(b)||0,se=ne+V,re=go.has(b),Y=_.args?.line_start!=null,me=yn.get(b)||0,I=me>0,J=2;if(!re&&se>=Ao){let L=b.split("/").slice(-2).join("/"),Z=(_o.get(b)||0)+1;if(_o.set(b,Z),Z===1)B(`${$.red} \u2716 Blocked: "${L}" read ${se}\xD7 \u2014 hard cap (${Ao}) reached${$.reset}`);else if(Z===2){B(`${$.red} \u2716 Escalated block: "${L}" \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let $e={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 (${Ao}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};j.push($e),M.push($e)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already read ${se}\xD7 (hard cap: ${Ao}). 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(!re&&se>=1&&Y)if(I&&me<=J){let L=b.split("/").slice(-2).join("/");console.log(`${$.cyan} \u21A9 Targeted re-read: "${L}" (line_start=${_.args.line_start}) \u2014 edit recovery #${me}${$.reset}`),yn.set(b,me-1)}else if(I&&me>J){let L=b.split("/").slice(-2).join("/");B(`${$.red} \u2716 Edit recovery blocked: "${L}" \u2014 ${J} recovery reads already used. Use grep to find the exact line numbers, then retry.${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 edit recovery budget exhausted (${J} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:_.callId}}else{let L=parseInt(_.args.line_start,10)||1,Z=parseInt(_.args.line_end,10)||L+350,$e=hs.get(b)||[],Re=!1;for(let[fe,H]of $e){let Ce=Math.max(L,fe),je=Math.min(Z,H);if(je>Ce){let ot=je-Ce,ft=Z-L||1,pn=H-fe||1,$t=ot/pn>=.7&&ot/ft<.7,ia=Z-L<=sx;if(ot>=ft||!ia&&(ot/ft>=.7||ot/pn>=.7)){let Rl=b.split("/").slice(-2).join("/"),Sp=`${b}:${L}-${Z}`,No=(zc.get(Sp)||0)+1;if(zc.set(Sp,No),B($t?`${$.red} \u2716 Blocked superread: "${Rl}" lines ${L}-${Z} subsumes already-read ${fe}-${H} \u2014 use line_start=${H+1} to skip known content (block #${No})${$.reset}`:`${$.red} \u2716 Blocked duplicate read: "${Rl}" lines ${L}-${Z} (\u226570% overlap with lines ${fe}-${H} already in context, block #${No})${$.reset}`),No>=2){B(`${$.red} \u2716 Escalated range-block: "${Rl}" lines ${L}-${Z} \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let Ep={role:"user",content:$t?`[SYSTEM] Read blocked ${No}\xD7 for read_file("${b}", lines ${L}-${Z}). Lines ${fe}-${H} were already read. Use line_start=${H+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${No}\xD7 for read_file("${b}", lines ${L}-${Z}). Lines ${fe}-${H} were already read and will NOT change. Use grep_search to find specific content instead.`};j.push(Ep),M.push(Ep)}_.canExecute=!1,_.errorResult={role:"tool",content:$t?`BLOCKED: read_file("${b}", lines ${L}-${Z}) re-reads lines ${fe}-${H} already in context. Use line_start=${H+1} to read only the new content beyond line ${H}.`:`BLOCKED: read_file("${b}", lines ${L}-${Z}) is a duplicate \u2014 lines ${fe}-${H} 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 fe=$e.length,H=2;if(fe>=3){let je=b.split("/").slice(-2).join("/");B(`${$.red} \u2716 Blocked file-scroll: "${je}" \u2014 ${fe} sections already read. Use grep to find specific content.${$.reset}`);let ot=Jn($l,b)>=ea;_.canExecute=!1,_.errorResult={role:"tool",content:ot?`BLOCKED: read_file("${b}") denied \u2014 you have already read ${fe} 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 ${fe} 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 fe>=H&&(_._scrollWarn={sectionCount:fe+1,path:b})}}else if(!re&&se>=1){let L=yn.get(b)||0;if(L>0){let Z=b.split("/").slice(-2).join("/");console.log(`${$.cyan} \u21A9 Full re-read: "${Z}" \u2014 test-failure recovery (${L} remaining)${$.reset}`);let $e=L-1;$e<=0?yn.delete(b):yn.set(b,$e)}else{let Z=b.split("/").slice(-2).join("/"),$e=(_o.get(b)||0)+1;if(_o.set(b,$e),$e===1)B(`${$.red} \u2716 Blocked unbounded re-read: "${Z}" \u2014 already in context. Use line_start/line_end for specific sections.${$.reset}`);else if($e===2){B(`${$.red} \u2716 Escalated block: "${Z}" \u2014 model ignored unbounded re-read block, injecting system warning${$.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.`};j.push(Re),M.push(Re)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already in context (read ${se}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:_.callId}}}_.canExecute&&El.set(b,(El.get(b)||0)+1)}if(Cs>=3)for(let _ of Me)_.canExecute&&(_.fnName!=="read_file"&&_.fnName!=="edit_file"||(B(`${$.red} \u2716 Blocked ${_.fnName} \u2014 ${Cs} consecutive file-not-found errors, must search first${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${Cs} 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 Me){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)){B(`${$.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${$.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)&&(B(`${$.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${$.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 Me)_.canExecute&&(_.fnName!=="ssh_exec"&&_.fnName!=="bash"||/\bsed\s+-n\b/.test(_.args?.command||"")&&(B(`${$.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${$.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 Me){if(!_.canExecute||_.fnName!=="write_file")continue;let b=_.args?.path,ne=_.args?.content||"";if(b)try{let V=require("fs"),se=require("path").resolve(process.cwd(),b);if(V.existsSync(se)){let re=V.statSync(se).size,Y=Buffer.byteLength(ne,"utf8"),me=re>0?Y/re:1,I=hf(P),J=hf(b);if(Cw(P)&&(I.includes(J)||I.includes(`./${J}`)))continue;if(me<.6&&re>200){let Z=b.split("/").slice(-2).join("/");console.log(`${$.red} \u2716 write_file shrink guard: "${Z}" would shrink to ${Math.round(me*100)}% of original \u2014 likely context loss${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: write_file("${b}") denied \u2014 new content is only ${Math.round(me*100)}% of current file size (${re} \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 _p=new Map;for(let _ of Me){if(!_.canExecute||_.fnName!=="grep")continue;let b=_.args?.path;if(!b)continue;let ne=_p.get(b)||0,V=Jn($l,b)+ne,se=Jn(Co,b)>=1,re=se?Math.min(3,ea):ea;if(V>=re){let Y=b.split("/").slice(-2).join("/");B(`${$.red} \u2716 Blocked grep: "${Y}" grepped ${V}\xD7 with different patterns \u2014 flood threshold exceeded${$.reset}`);let me=Jn(Co,b),I=me>=Ao;if(I){let J={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${b}". You have already read ${me} sections and tried ${V} 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.`};j.push(J),M.push(J),B(`${$.red} \u2716 Deadlock detected: "${Y}" \u2014 both read and grep blocked, injecting deadlock-break${$.reset}`)}_.canExecute=!1,_.errorResult={role:"tool",content:I?`BLOCKED: grep("${b}") denied \u2014 ${V} 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.`:se?`BLOCKED: grep("${b}") denied \u2014 file was already read and ${V} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${b}") denied \u2014 ${V} patterns already tried. Work with the grep results already in your context.`,tool_call_id:_.callId}}_.canExecute&&_p.set(b,ne+1)}let lx=5,xp=new Map;for(let _ of Me){if(!_.canExecute||_.fnName!=="ssh_exec")continue;let ne=(_.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),V=xp.get(ne)||0,se=Jn(Qi,ne)+V;se>=lx&&(B(`${$.yellow} \u26A0 Blocked ssh_exec: same command run ${se}\xD7 \u2014 result already in context${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${se} 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&&xp.set(ne,V+1)}if(rn){let _=Me.filter(V=>V.canExecute&&V.fnName==="ssh_exec"),b=Me.some(V=>V.canExecute&&V.fnName!=="ssh_exec"),ne=O&&Q<3;if(_.length>0&&!b&&ne&&Fc<1)rn=!1,Fc++,$n=Math.max(0,Rr-2),B(`${$.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Fc}/1)]${$.reset}`);else for(let V of _)V.canExecute=!1,V.errorResult={role:"tool",content:Et?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Rr}+ calls). Root cause is known (${Kt}). 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 (${Rr}+ 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:V.callId}}let ux=wM(j,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if((O||R)&&!ux&&Q<3&&!rn)for(let _ of Me){if(!_.canExecute||!["bash","read_file","find_files","list_directory","search_files","glob","grep"].includes(_.fnName))continue;Q++;{let V=At(),{messages:se}=Vn(M,V);M=se}let b=W?.matchedName?`${W.matchedName} (${W.matchedProfile?.host||"server"})`:W?.url,ne=W?.shouldPreferSsh?`BLOCKED: ${_.fnName} denied \u2014 this looks like a live app/server issue. Inspect ${W?.url} with browser_open or use ssh_exec on ${b} first, then return to local code if needed.`:`BLOCKED: ${_.fnName} denied \u2014 this looks like a live app issue. Inspect ${W?.url} with browser_open first, then return to local code if needed.`;B(`${$.yellow} \u26A0 Runtime guard: blocking local ${_.fnName} \u2014 inspect the live app first${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:ne,tool_call_id:_.callId};break}if(!Te&&_n&&wn&&xn>=1){let _=["read_file","grep","search_files","glob","list_directory","find_files"];for(let b of Me)b.canExecute&&_.includes(b.fnName)&&(B(`${$.red} \u2716 Creation hard-block: ${b.fnName} denied \u2014 cap fired, files already written${$.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(yo>=0){let _=Me.filter(b=>b.canExecute).length;if(_>0&&(yo-=_,yo<0))if(!Uc&&F.size>Bc){Uc=!0,yo=5,B(`${$.green} \u2713 Post-wipe progress detected (${F.size-Bc} files modified) \u2014 granting 5 bonus tool calls${$.reset}`);let b={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};j.push(b),M.push(b)}else{B(`${$.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${$.reset}`);for(let ne of Me)ne.canExecute&&(ne.canExecute=!1,ne.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:ne.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."};j.push(b),M.push(b)}}let dx=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 Me){if(!_.canExecute||dx.has(_.fnName))continue;let b=JSON.stringify(_.args||{}),ne=`${_.fnName}|${b}`,V=Jn(cf,ne);V>=2?(B(`${$.red} \u2716 Blocked duplicate: ${_.fnName}(${b.substring(0,80)}) \u2014 called ${V+1}\xD7 with identical args${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${_.fnName}() with these exact arguments has already been called ${V}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:_.callId}):V===1&&B(`${$.yellow} \u26A0 Duplicate tool call: ${_.fnName}(${b.substring(0,80)}) \u2014 2nd call with identical args${$.reset}`),mo(cf,ne)}{let _=new Set;for(let b of Me){if(!b.canExecute||!["edit_file","patch_file"].includes(b.fnName))continue;let ne=b.args?.path;ne&&(_.has(ne)?(b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: "${ne}" is already being edited in this batch. Finish one edit first, then re-read the changed section before the next one.`,tool_call_id:b.callId},B(`${$.yellow} \u26A0 Map-first gate: blocked duplicate same-batch edit of "${ne.split("/").slice(-1)[0]}"${$.reset}`)):qe.has(ne)&&!go.has(ne)?(b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: "${ne}" 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},B(`${$.yellow} \u26A0 Map-first gate: blocked re-edit of "${ne.split("/").slice(-1)[0]}" \u2014 re-read required${$.reset}`)):_.add(ne))}}let Ar=d?{skipSpinner:!0,skipSummaries:!0}:{},fx=Me.some(_=>_.fnName==="ask_user"),vp=!Ar.skipSummaries&&!Se,kn=null,Mo=null;if(vp&&!fx){if(Se=!0,Ar.skipSpinner=!0,process.stdout.isTTY){global._nexFooter&&(Mo=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd));let _=$i(Me,N,!1,0),b=$i(Me,N,!1);process.stdout.write(`${N>1?`
|
|
1469
|
+
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.dim}Type ${$.reset}${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ask follow-up questions to refine.${$.reset}`);if(me){d&&(d.stop(),d=null),ut--;continue}}}if(d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe),wn&&F.size>=3){let re=[...F].map(L=>L.split("/").pop()).slice(0,8).join(", "),Y=[...F].some(L=>L.endsWith("package.json")),me=[...F].some(L=>L.endsWith("requirements.txt")),I=[...F].some(L=>L.endsWith("package-lock.json")||L.endsWith("yarn.lock")||L.endsWith("pnpm-lock.yaml")),J=Y&&!I?"npm install not yet run":me?"pip install not yet run":null;Ti=`[Previous session created ${F.size} files: ${re}`+(J?` \u2014 ${J}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(wn&&!df&&N>0){let re=[...F].some(fe=>fe.endsWith("package.json")),Y=[...F].some(fe=>fe.endsWith("requirements.txt")||fe.endsWith("Pipfile")||fe.endsWith("pyproject.toml")),me=[...F].some(fe=>fe.endsWith("package-lock.json")||fe.endsWith("yarn.lock")||fe.endsWith("pnpm-lock.yaml")),I=j.flatMap(fe=>{let H=Array.isArray(fe.tool_calls)?fe.tool_calls:[],Ce=Array.isArray(fe.content)?fe.content.filter(je=>je?.type==="tool_use"):[];return[...H,...Ce]}).filter(fe=>{let H=fe.function?.name||fe.name||"";return H==="bash"||H==="Bash"}).map(fe=>{try{let H=fe.function?.arguments??fe.input??{};return(typeof H=="string"?JSON.parse(H):H)?.command||""}catch{return""}}),J=I.some(fe=>/pip\s+install|python\s+-m\s+venv/.test(fe)),L=I.some(fe=>/npm\s+install/.test(fe)),$e=[...F].some(fe=>/\/App\.(js|ts|jsx|tsx)$/.test(fe))&&!re&&!L;if(Y&&!J||re&&!me&&!L||$e){df=!0;let fe=[];Y&&!J&&fe.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),$e?fe.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):re&&!me&&!L&&fe.push("npm install");let H=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${fe.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;B(`${$.dim} [post-creation] bootstrapping environment (${fe.join(", ")})${$.reset}`),j.push({role:"user",content:H}),M.push({role:"user",content:H});continue}}if(N>0&&!n._isSummaryTurn&&Ac(Zt))try{B(`${$.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${$.reset}`);let re=F.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.",Y=[...M,{role:"user",content:re}],I=((await gw(Y,[],{}))?.content||"").trim();I&&(console.log(`
|
|
1470
|
+
${I}`),j.push({role:"user",content:re},{role:"assistant",content:I}))}catch{}We(j),wi(j),await gp();return}N++,Kc++,N>=1&&(Se=!1);for(let _ of Bn){let b=_.function.name;U.set(b,(U.get(b)||0)+1)}if(N>=30&&!Cw){Cw=!0,B(`${$.yellow} \u26A0 Tool budget warning: ${N} tool calls used \u2014 nudging model to wrap up${$.reset}`);let _={role:"user",content:"[SYSTEM] \u26A0 You have used "+N+" tool calls. This is approaching the quality threshold (40). Wrap up NOW: write your final summary and stop. Do NOT run additional verification commands (git status, git diff, git log) \u2014 your changes are already committed and verified. Further tool calls will hurt session quality."};j.push(_),M.push(_)}let Me=await Promise.all(Bn.map(_=>kM(_)));if(xl){let _=new Set(["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"]);for(let b of Me)!b.canExecute||!_.has(b.fnName)||(b.canExecute=!1,b.errorResult={role:"tool",content:"BLOCKED: You already have enough evidence to produce the requested summary/document. Write the deliverable now and stop reading more files.",tool_call_id:b.callId})}{let _=Pn(M,At()),b=_.percentage,ne=Me.some(Y=>Y.canExecute&&Y.fnName==="read_file"&&!Y.args?.line_end),V=Me.filter(Y=>Y.canExecute&&Y.fnName==="read_file"&&Y.args?.path&&Jn(Co,Y.args.path)>=1&&!Y.args?.line_start).map(Y=>Y.args.path.split("/").slice(-2).join("/")),se=V.length>0;if(b>=70&&ne&&wl<70||b>=85&&wl<85||se){wl=b;let Y=b>=85?"URGENT":"WARNING",me;se?(Y="WARNING",me=`Full-file read of ${V.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):ne?me=`Unbounded read at ${Math.round(b)}% context \u2014 use line_start/line_end to avoid overflow.`:me="Use targeted reads (line_start/line_end) to save space.";let I={role:"user",content:`[SYSTEM ${Y}] Context ${Math.round(b)}% used (${_.used}/${_.limit} tokens). ${me}`};if(j.push(I),M.push(I),b>=85){let J=se?` (re-read of: ${V.join(", ")})`:"";B(`${$.yellow} \u26A0 Context ${Math.round(b)}% used \u2014 agent warned to use targeted reads${J}${$.reset}`)}}}let El=new Map;for(let _ of Me){if(!_.canExecute||_.fnName!=="read_file")continue;let b=_.args?.path;if(!b)continue;let ne=Jn(Co,b),V=El.get(b)||0,se=ne+V,re=go.has(b),Y=_.args?.line_start!=null,me=yn.get(b)||0,I=me>0,J=2;if(!re&&se>=Ao){let L=b.split("/").slice(-2).join("/"),Z=(_o.get(b)||0)+1;if(_o.set(b,Z),Z===1)B(`${$.red} \u2716 Blocked: "${L}" read ${se}\xD7 \u2014 hard cap (${Ao}) reached${$.reset}`);else if(Z===2){B(`${$.red} \u2716 Escalated block: "${L}" \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let $e={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 (${Ao}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};j.push($e),M.push($e)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already read ${se}\xD7 (hard cap: ${Ao}). 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(!re&&se>=1&&Y)if(I&&me<=J){let L=b.split("/").slice(-2).join("/");console.log(`${$.cyan} \u21A9 Targeted re-read: "${L}" (line_start=${_.args.line_start}) \u2014 edit recovery #${me}${$.reset}`),yn.set(b,me-1)}else if(I&&me>J){let L=b.split("/").slice(-2).join("/");B(`${$.red} \u2716 Edit recovery blocked: "${L}" \u2014 ${J} recovery reads already used. Use grep to find the exact line numbers, then retry.${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 edit recovery budget exhausted (${J} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:_.callId}}else{let L=parseInt(_.args.line_start,10)||1,Z=parseInt(_.args.line_end,10)||L+350,$e=hs.get(b)||[],Re=!1;for(let[fe,H]of $e){let Ce=Math.max(L,fe),je=Math.min(Z,H);if(je>Ce){let rt=je-Ce,ft=Z-L||1,pn=H-fe||1,$t=rt/pn>=.7&&rt/ft<.7,ia=Z-L<=sx;if(rt>=ft||!ia&&(rt/ft>=.7||rt/pn>=.7)){let Rl=b.split("/").slice(-2).join("/"),Ep=`${b}:${L}-${Z}`,No=(zc.get(Ep)||0)+1;if(zc.set(Ep,No),B($t?`${$.red} \u2716 Blocked superread: "${Rl}" lines ${L}-${Z} subsumes already-read ${fe}-${H} \u2014 use line_start=${H+1} to skip known content (block #${No})${$.reset}`:`${$.red} \u2716 Blocked duplicate read: "${Rl}" lines ${L}-${Z} (\u226570% overlap with lines ${fe}-${H} already in context, block #${No})${$.reset}`),No>=2){B(`${$.red} \u2716 Escalated range-block: "${Rl}" lines ${L}-${Z} \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let Tp={role:"user",content:$t?`[SYSTEM] Read blocked ${No}\xD7 for read_file("${b}", lines ${L}-${Z}). Lines ${fe}-${H} were already read. Use line_start=${H+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${No}\xD7 for read_file("${b}", lines ${L}-${Z}). Lines ${fe}-${H} were already read and will NOT change. Use grep_search to find specific content instead.`};j.push(Tp),M.push(Tp)}_.canExecute=!1,_.errorResult={role:"tool",content:$t?`BLOCKED: read_file("${b}", lines ${L}-${Z}) re-reads lines ${fe}-${H} already in context. Use line_start=${H+1} to read only the new content beyond line ${H}.`:`BLOCKED: read_file("${b}", lines ${L}-${Z}) is a duplicate \u2014 lines ${fe}-${H} 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 fe=$e.length,H=2;if(fe>=3){let je=b.split("/").slice(-2).join("/");B(`${$.red} \u2716 Blocked file-scroll: "${je}" \u2014 ${fe} sections already read. Use grep to find specific content.${$.reset}`);let rt=Jn($l,b)>=ea;_.canExecute=!1,_.errorResult={role:"tool",content:rt?`BLOCKED: read_file("${b}") denied \u2014 you have already read ${fe} 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 ${fe} 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 fe>=H&&(_._scrollWarn={sectionCount:fe+1,path:b})}}else if(!re&&se>=1){let L=yn.get(b)||0;if(L>0){let Z=b.split("/").slice(-2).join("/");console.log(`${$.cyan} \u21A9 Full re-read: "${Z}" \u2014 test-failure recovery (${L} remaining)${$.reset}`);let $e=L-1;$e<=0?yn.delete(b):yn.set(b,$e)}else{let Z=b.split("/").slice(-2).join("/"),$e=(_o.get(b)||0)+1;if(_o.set(b,$e),$e===1)B(`${$.red} \u2716 Blocked unbounded re-read: "${Z}" \u2014 already in context. Use line_start/line_end for specific sections.${$.reset}`);else if($e===2){B(`${$.red} \u2716 Escalated block: "${Z}" \u2014 model ignored unbounded re-read block, injecting system warning${$.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.`};j.push(Re),M.push(Re)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already in context (read ${se}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:_.callId}}}_.canExecute&&El.set(b,(El.get(b)||0)+1)}if(Cs>=3)for(let _ of Me)_.canExecute&&(_.fnName!=="read_file"&&_.fnName!=="edit_file"||(B(`${$.red} \u2716 Blocked ${_.fnName} \u2014 ${Cs} consecutive file-not-found errors, must search first${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${Cs} 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 Me){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)){B(`${$.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${$.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)&&(B(`${$.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${$.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 Me)_.canExecute&&(_.fnName!=="ssh_exec"&&_.fnName!=="bash"||/\bsed\s+-n\b/.test(_.args?.command||"")&&(B(`${$.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${$.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 Me){if(!_.canExecute||_.fnName!=="write_file")continue;let b=_.args?.path,ne=_.args?.content||"";if(b)try{let V=require("fs"),se=require("path").resolve(process.cwd(),b);if(V.existsSync(se)){let re=V.statSync(se).size,Y=Buffer.byteLength(ne,"utf8"),me=re>0?Y/re:1,I=hf(P),J=hf(b);if(Aw(P)&&(I.includes(J)||I.includes(`./${J}`)))continue;if(me<.6&&re>200){let Z=b.split("/").slice(-2).join("/");console.log(`${$.red} \u2716 write_file shrink guard: "${Z}" would shrink to ${Math.round(me*100)}% of original \u2014 likely context loss${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: write_file("${b}") denied \u2014 new content is only ${Math.round(me*100)}% of current file size (${re} \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 xp=new Map;for(let _ of Me){if(!_.canExecute||_.fnName!=="grep")continue;let b=_.args?.path;if(!b)continue;let ne=xp.get(b)||0,V=Jn($l,b)+ne,se=Jn(Co,b)>=1,re=se?Math.min(3,ea):ea;if(V>=re){let Y=b.split("/").slice(-2).join("/");B(`${$.red} \u2716 Blocked grep: "${Y}" grepped ${V}\xD7 with different patterns \u2014 flood threshold exceeded${$.reset}`);let me=Jn(Co,b),I=me>=Ao;if(I){let J={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${b}". You have already read ${me} sections and tried ${V} 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.`};j.push(J),M.push(J),B(`${$.red} \u2716 Deadlock detected: "${Y}" \u2014 both read and grep blocked, injecting deadlock-break${$.reset}`)}_.canExecute=!1,_.errorResult={role:"tool",content:I?`BLOCKED: grep("${b}") denied \u2014 ${V} 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.`:se?`BLOCKED: grep("${b}") denied \u2014 file was already read and ${V} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${b}") denied \u2014 ${V} patterns already tried. Work with the grep results already in your context.`,tool_call_id:_.callId}}_.canExecute&&xp.set(b,ne+1)}let lx=5,vp=new Map;for(let _ of Me){if(!_.canExecute||_.fnName!=="ssh_exec")continue;let ne=(_.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),V=vp.get(ne)||0,se=Jn(Qi,ne)+V;se>=lx&&(B(`${$.yellow} \u26A0 Blocked ssh_exec: same command run ${se}\xD7 \u2014 result already in context${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${se} 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&&vp.set(ne,V+1)}if(rn){let _=Me.filter(V=>V.canExecute&&V.fnName==="ssh_exec"),b=Me.some(V=>V.canExecute&&V.fnName!=="ssh_exec"),ne=O&&Q<3;if(_.length>0&&!b&&ne&&Fc<1)rn=!1,Fc++,$n=Math.max(0,Rr-2),B(`${$.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Fc}/1)]${$.reset}`);else for(let V of _)V.canExecute=!1,V.errorResult={role:"tool",content:Et?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Rr}+ calls). Root cause is known (${Kt}). 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 (${Rr}+ 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:V.callId}}let ux=wM(j,["browser_open","browser_screenshot","ssh_exec","service_logs","remote_agent"]);if((O||R)&&!ux&&Q<3&&!rn)for(let _ of Me){if(!_.canExecute||!["bash","read_file","find_files","list_directory","search_files","glob","grep"].includes(_.fnName))continue;Q++;{let V=At(),{messages:se}=Vn(M,V);M=se}let b=W?.matchedName?`${W.matchedName} (${W.matchedProfile?.host||"server"})`:W?.url,ne=W?.shouldPreferSsh?`BLOCKED: ${_.fnName} denied \u2014 this looks like a live app/server issue. Inspect ${W?.url} with browser_open or use ssh_exec on ${b} first, then return to local code if needed.`:`BLOCKED: ${_.fnName} denied \u2014 this looks like a live app issue. Inspect ${W?.url} with browser_open first, then return to local code if needed.`;B(`${$.yellow} \u26A0 Runtime guard: blocking local ${_.fnName} \u2014 inspect the live app first${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:ne,tool_call_id:_.callId};break}if(!Te&&_n&&wn&&xn>=1){let _=["read_file","grep","search_files","glob","list_directory","find_files"];for(let b of Me)b.canExecute&&_.includes(b.fnName)&&(B(`${$.red} \u2716 Creation hard-block: ${b.fnName} denied \u2014 cap fired, files already written${$.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(yo>=0){let _=Me.filter(b=>b.canExecute).length;if(_>0&&(yo-=_,yo<0))if(!Uc&&F.size>Bc){Uc=!0,yo=5,B(`${$.green} \u2713 Post-wipe progress detected (${F.size-Bc} files modified) \u2014 granting 5 bonus tool calls${$.reset}`);let b={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};j.push(b),M.push(b)}else{B(`${$.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${$.reset}`);for(let ne of Me)ne.canExecute&&(ne.canExecute=!1,ne.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:ne.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."};j.push(b),M.push(b)}}let dx=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 Me){if(!_.canExecute||dx.has(_.fnName))continue;let b=JSON.stringify(_.args||{}),ne=`${_.fnName}|${b}`,V=Jn(cf,ne);V>=2?(B(`${$.red} \u2716 Blocked duplicate: ${_.fnName}(${b.substring(0,80)}) \u2014 called ${V+1}\xD7 with identical args${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${_.fnName}() with these exact arguments has already been called ${V}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:_.callId}):V===1&&B(`${$.yellow} \u26A0 Duplicate tool call: ${_.fnName}(${b.substring(0,80)}) \u2014 2nd call with identical args${$.reset}`),mo(cf,ne)}{let _=new Set;for(let b of Me){if(!b.canExecute||!["edit_file","patch_file"].includes(b.fnName))continue;let ne=b.args?.path;ne&&(_.has(ne)?(b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: "${ne}" is already being edited in this batch. Finish one edit first, then re-read the changed section before the next one.`,tool_call_id:b.callId},B(`${$.yellow} \u26A0 Map-first gate: blocked duplicate same-batch edit of "${ne.split("/").slice(-1)[0]}"${$.reset}`)):qe.has(ne)&&!go.has(ne)?(b.canExecute=!1,b.errorResult={role:"tool",content:`BLOCKED: "${ne}" 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},B(`${$.yellow} \u26A0 Map-first gate: blocked re-edit of "${ne.split("/").slice(-1)[0]}" \u2014 re-read required${$.reset}`)):_.add(ne))}}let Ar=d?{skipSpinner:!0,skipSummaries:!0}:{},fx=Me.some(_=>_.fnName==="ask_user"),kp=!Ar.skipSummaries&&!Se,kn=null,Mo=null;if(kp&&!fx){if(Se=!0,Ar.skipSpinner=!0,process.stdout.isTTY){global._nexFooter&&(Mo=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd));let _=$i(Me,N,!1,0),b=$i(Me,N,!1);process.stdout.write(`${N>1?`
|
|
1468
1471
|
`:""}${_}`),dr=b,fr=Date.now(),kn={start:Date.now(),frame:0,timer:null}}else if(!es){let _=$i(Me,N,!1);Zd(_,dr,fr)||(process.stdout.write(`${N>1?`
|
|
1469
1472
|
`:""}${_}
|
|
1470
|
-
`),dr=_,fr=Date.now())}}else
|
|
1473
|
+
`),dr=_,fr=Date.now())}}else kp&&(Se=!0,Ar.skipSpinner=!0);d&&d._paused&&d.resume(),kn&&process.stdout.isTTY&&(kn.timer=setInterval(()=>{kn.frame++;let _=Math.round((Date.now()-kn.start)/1e3),b=_>=1?` ${$.dim}[${_}s]${$.reset}`:"",ne=`${$i(Me,N,!1,kn.frame)}${b}`;Mo!==null?process.stdout.write(`\x1B[${Mo};1H\x1B[2K${ne}`):process.stdout.write(`\r\x1B[2K${ne}`)},120));let{results:yt,summaries:px}=await RM(Me,!0,{...Ar,skipSummaries:!0});if(Sl){let _={role:"user",content:"[SYSTEM] ask_user is exclusive. Wait for the user's answer before making any other tool calls."};j.push(_),M.push(_)}if(kn){kn.timer&&(clearInterval(kn.timer),kn.timer=null);let _=$i(Me,N,!1);Zd(_,dr,fr)||(Mo!==null?process.stdout.write(`\x1B[${Mo};1H\x1B[2K${_}
|
|
1471
1474
|
`):process.stdout.write(`\r\x1B[2K${_}
|
|
1472
|
-
`),dr=_,fr=Date.now()),Mo=null,kn=null}if(!Ar.skipSummaries){let _=px.filter((V,se)=>!(Me[se]&&Me[se].fnName==="ask_user"));for(let V of _)Zd(V,of,rf)||(console.log(V),of=V,rf=Date.now());let b=Me.filter(V=>V&&V.fnName!=="ask_user").map(V=>V.fnName),ne=Tr.record(0,b,pe,F);ne&&sM(ne)}for(let _ of Me){if(_.canExecute||!_.errorResult)continue;let b=typeof _.errorResult.content=="string"?_.errorResult.content:"";if((b.startsWith("BLOCKED:")||b.startsWith("PLAN MODE:")||b.startsWith("PLAN PHASE:"))&&(js++,js>=
|
|
1475
|
+
`),dr=_,fr=Date.now()),Mo=null,kn=null}if(!Ar.skipSummaries){let _=px.filter((V,se)=>!(Me[se]&&Me[se].fnName==="ask_user"));for(let V of _)Zd(V,of,rf)||(console.log(V),of=V,rf=Date.now());let b=Me.filter(V=>V&&V.fnName!=="ask_user").map(V=>V.fnName),ne=Tr.record(0,b,pe,F);ne&&sM(ne)}for(let _ of Me){if(_.canExecute||!_.errorResult)continue;let b=typeof _.errorResult.content=="string"?_.errorResult.content:"";if((b.startsWith("BLOCKED:")||b.startsWith("PLAN MODE:")||b.startsWith("PLAN PHASE:"))&&(js++,js>=hp)){B(`${$.red} \u2716 Loop abort: ${js} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe,{suppressHint:!0}),We(j);return}}let Tl=!1;for(let _=0;_<Me.length;_++){let b=Me[_];if(!b.canExecute)continue;let ne=yt[_].content,V=ne.split(`
|
|
1473
1476
|
`)[0],se=!V.startsWith("ERROR")&&!V.startsWith("CANCELLED")&&!V.startsWith("Command failed")&&!V.startsWith("EXIT");if(!se&&(b.fnName==="edit_file"||b.fnName==="patch_file")&&b.args?.path&&V.includes("old_text not found")){let I=yn.get(b.args.path)||0;yn.set(b.args.path,I+1)}if(!se&&b.fnName==="bash"&&Mi.size>0){let I=(b.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(I))for(let[L]of Mi)yn.has(L)||(yn.set(L,1),B(`${$.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${L.split("/").pop()}"${$.reset}`))}if(!se&&(b.fnName==="read_file"||b.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(V)){if(Cs++,Cs>=2){B(`${$.yellow} \u26A0 File-not-found streak: ${Cs} consecutive misses \u2014 forcing search${$.reset}`);let I={role:"user",content:`[SYSTEM] ${Cs} 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.`};j.push(I),M.push(I)}}else se&&(b.fnName==="read_file"||b.fnName==="edit_file"||b.fnName==="search_files"||b.fnName==="glob_files")&&(Cs=0);if(se&&b.fnName==="write_file"&&b.args?.path){let I=b.args.path.split("/").pop(),J=b.args.path.includes("/tests/")||b.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(I)&&!J){B(`${$.yellow} \u26A0 Temp file: "${I}" \u2014 delete with bash rm when done to keep the workspace clean${$.reset}`);let Z={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.`};j.push(Z),M.push(Z)}}if(se&&["write_file","edit_file","patch_file"].includes(b.fnName)&&b.args&&b.args.path){yn.delete(b.args.path),F.add(b.args.path);for(let L of vo)!L.done&&b.args.path.endsWith(L.file.split("/").pop())&&(L.done=!0,B(`${$.green} \u2713 TODO done: ${L.file}${$.reset}`));let I=mo(Ji,b.args.path),J=b.args.path.split("/").slice(-2).join("/");if(I===Zi){B(`${$.yellow} \u26A0 Loop warning: "${J}" edited ${I}\xD7 \u2014 possible edit loop${$.reset}`);let L={role:"user",content:`[SYSTEM WARNING] "${b.args.path}" edited ${I}\xD7. One more edit max, then move on.`};j.push(L),M.push(L)}else if(I>=Ro){B(`${$.red} \u2716 Loop abort: "${J}" edited ${I}\xD7 \u2014 aborting to prevent runaway loop${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe,{suppressHint:!0}),We(j);return}Te&&De==="verify"||(gr=!0,yr=0,Tl=!0)}if(se&&b.canExecute&&Te&&(As=0),se&&b.canExecute&&!(Te&&De==="plan")){let I=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(b.fnName)){bn=0,_n=!1,Ln=0,xn++;let H=b.args?.path||b.args?.file_path;H&&(b.fnName==="write_file"?(go.add(H),Qn.delete(H),hs.delete(H),qe.delete(H)):(go.delete(H),Vd(Qn,H,1),hs.delete(H),qe.add(H)))}else if(I.includes(b.fnName)){if(bn++,_n&&Ln++,Te&&De==="implement"&&b.fnName==="read_file"){let H=b.args?.path||b.args?.file_path||"";if(H&&go.has(H)){let Ce={role:"user",content:`[SYSTEM] You just created and re-read "${H}". Do NOT analyze further. Apply the requested refactor now with edit_file.`};j.push(Ce),M.push(Ce),B(`${$.yellow} \u26A0 Fresh-write nudge: ${H} \u2014 refactor directly after re-read${$.reset}`)}}if(Te&&De==="implement"&&b.fnName==="read_file"&&vo.length>0){let H=b.args?.path||b.args?.file_path||"",Ce=vo.find(je=>!je.done&&H.endsWith(je.file.split("/").pop()));if(Ce){let je={role:"user",content:`[TODO OBSERVER] You already analyzed "${Ce.file}" in the plan phase. Action: ${Ce.action}
|
|
1474
|
-
Do NOT re-read \u2014 apply the edit directly with edit_file.`};j.push(je),M.push(je),B(`${$.yellow} \u26A0 TODO nudge: ${Ce.file} \u2014 already analyzed, edit directly${$.reset}`)}}Te&&De==="implement"&&gr&&yr<1&&(yr++,Tl=!0)}Te&&De==="verify"&&hr++,se&&
|
|
1477
|
+
Do NOT re-read \u2014 apply the edit directly with edit_file.`};j.push(je),M.push(je),B(`${$.yellow} \u26A0 TODO nudge: ${Ce.file} \u2014 already analyzed, edit directly${$.reset}`)}}Te&&De==="implement"&&gr&&yr<1&&(yr++,Tl=!0)}Te&&De==="verify"&&hr++,se&&DM(b)&&(gr=!1,yr=0);let L=o.postEditCap,Z=Te&&De==="implement"?Math.min(mp,10):mp,$e=Et?8:ta?xn>0?4:6:wn?xn>0?6:10:xn>0?L:Z,Re=6,fe=!Te&&_n&&(Et&&Ln>=Re||wn&&xn>=3&&Ln>=Re||Ln>=Re);if(bi<2&&!_n&&bn>=3&&F.size===0){let H=parseInt(process.env.NEX_TASK_TIMEOUT_MS,10)||0,Ce=Date.now()-Pe,je=bi===0?.4:.65;if(H>0&&Ce>H*je){bi++;let rt=Math.round(Ce/6e4),ft=Math.round(Ce/H*100);B(`${$.yellow} \u26A0 Time nudge #${bi}: ${rt}m elapsed (${ft}%), ${bn} reads, 0 edits${$.reset}`);let pn={role:"user",content:bi===1?`[SYSTEM] ${ft}% of available time used and no files edited yet. Start implementing now using edit_file or write_file \u2014 you have enough context.`:`[SYSTEM] ${ft}% 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.`};j.push(pn),M.push(pn)}}if(fe&&I.includes(b.fnName)){let H=Et?`root cause already identified (${Kt})`:Ln>=Re?`${bn} consecutive reads without an edit`:`${xn} file edit(s) already made`;B(`${$.red} \u2716 Blocked read-only tool: cap fired, ${H}${$.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:Et?`BLOCKED: root cause already identified (${Kt}). Use edit_file to fix the issue \u2014 do not read more files.`:wn?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":Ln>=Re?`BLOCKED: You have read ${bn} 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: ${xn} 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(bn>=$e&&!_n){if(_n=!0,ta&&(xl=!0),B(`${$.yellow} \u26A0 Investigation cap: ${bn} read-only calls without an edit \u2014 forcing implementation${$.reset}`),Te&&De==="plan"){let je=[...M].reverse().find(pn=>pn.role==="assistant"),rt=typeof je?.content=="string"?je.content:"",ft=await xi("implement",rt);ft&&(j.push(ft),M.push(ft),ut=0,Jt=ho("implement"))}let H;Et?H=`[SYSTEM] Root cause was already identified (${Kt}). Edit the file now \u2014 do not read more files.`:ta?H="[SYSTEM] You have enough evidence to write the requested summary/document now. Use write_file or edit_file to produce the deliverable, and stop reading more files unless a required section is still unsupported.":rn?H="[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.":H="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let Ce={role:"user",content:H};j.push(Ce),M.push(Ce)}}if((b.fnName==="bash"||b.fnName==="ssh_exec")&&b.args&&b.args.command){let I=b.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),J=mo(Qi,I);if(J===H_){B(`${$.yellow} \u26A0 Loop warning: same bash command run ${J}\xD7 \u2014 possible debug loop${$.reset}`);let L={role:"user",content:`[SYSTEM WARNING] Same bash command ${J}\xD7. Debug loop detected \u2014 try a different approach.`};j.push(L),M.push(L)}else if(J>=G_){B(`${$.red} \u2716 Loop abort: same bash command run ${J}\xD7 \u2014 aborting runaway debug loop${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe,{suppressHint:!0}),We(j);return}}if(b.fnName==="ssh_exec"){$n++;{let L=(yt[_]?.content??"").split(`
|
|
1475
1478
|
`).map(Z=>Z.trim()).find(Z=>Z.length>0&&!Z.startsWith("**")&&(Z.startsWith("EXIT")||/^[\w./-]+:\s/.test(Z)||Z.startsWith("bash:")||Z.startsWith("sh:")))??"";if(L){if(L===Wc?$o++:(Wc=L,$o=1),$o===3&&!rn){B(`${$.yellow} \u26A0 SSH repeated-error: "${L.slice(0,60)}" returned ${$o}\xD7 \u2014 nudging to change approach${$.reset}`);let Z={role:"user",content:`[SYSTEM WARNING] The last ${$o} SSH commands all failed with the same error: "${L}". 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).`};j.push(Z),M.push(Z)}}else Wc="",$o=0}if($n>=cx){B(`${$.red} \u2716 SSH storm abort: ${$n} consecutive ssh_exec calls \u2014 aborting${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe,{suppressHint:!0}),We(j);return}else if($n===Rr){{let L=At(),{messages:Z}=Vn(M,L);M=Z}rn=!0,Mc++,B(`${$.yellow} \u26A0 SSH storm warning (#${Mc}): ${$n} consecutive ssh_exec calls \u2014 blocking further SSH${$.reset}`);let J={role:"user",content:Et?`[SYSTEM WARNING] ${$n} consecutive SSH calls. Root cause identified (${Kt}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${$n} 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.`};j.push(J),M.push(J)}}else b.canExecute&&($n=0);if(b.fnName==="bash"&&b.canExecute){let L=(yt[_]?.content??"").split(`
|
|
1476
1479
|
`).map(Z=>Z.trim()).find(Z=>Z.length>0&&(Z.startsWith("EXIT")||/^[\w./-]+:\s/.test(Z)||Z.startsWith("bash:")||Z.startsWith("sh:")))??"";if(L){if(L===Hc?wo++:(Hc=L,wo=1),wo===3){B(`${$.yellow} \u26A0 Bash repeated-error: "${L.slice(0,60)}" returned ${wo}\xD7 \u2014 nudging to change approach${$.reset}`);let Z={role:"user",content:`[SYSTEM WARNING] The last ${wo} bash commands all failed with the same error: "${L}". 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).`};j.push(Z),M.push(Z)}}else Hc="",wo=0}if(b.fnName==="bash"&&b.canExecute&&!Jd&&b.args?.command){let I=yt[_]?.content??"";if(/git\s+commit\b/.test(b.args.command)&&!I.startsWith("EXIT")&&!I.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(I)||I.includes("files changed")||I.includes("file changed")||I.includes("insertions(+)")||I.includes("create mode"))){Jd=!0,_i=0,B(`${$.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${$.reset}`);let Z={role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. Your changes are committed. Do NOT run further git status / git diff / git log calls \u2014 the commit is done. Write your final summary and stop. Running extra verification commands wastes tool calls and hurts session quality."};j.push(Z),M.push(Z)}}if(Jd&&b.fnName==="bash"&&b.args?.command&&/git\s+(status|diff|log|show)\b/.test(b.args.command)&&(_i++,_i>2)){B(`${$.yellow} \u26A0 Post-commit git verification blocked (call ${_i})${$.reset}`);let J={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(_i-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};j.push(J),M.push(J)}if(se&&b.fnName==="grep"&&ne&&!ne.startsWith("(no matches)")){let I=ne.split(`
|
|
1477
1480
|
`);for(let J of I){let L=J.indexOf(":");if(L>0){let Z=J.substring(0,L);Z.startsWith("/")&&!Z.includes(" ")&&Ai.add(Z)}else J.startsWith("/")&&!J.includes(" ")&&Ai.add(J.trim())}}{let I=["grep","search_files","glob","glob_files"].includes(b.fnName);if(I&&se&&ne&&(ne.startsWith("(no matches)")||ne.trim()===""||/^No matches found/.test(ne.trim())||/^\(0 results\)/.test(ne.trim()))){if(Je++,Je===3){B(`${$.yellow} \u26A0 3 consecutive empty local searches \u2014 injecting SSH pivot hint${$.reset}`);let L={role:"user",content:"[SYSTEM NOTE] 3 consecutive local searches returned no results. The target files may be on a remote server. If you have an SSH profile configured for this project's server, use ssh_exec to search there (e.g. ssh_exec with grep). Do not keep searching locally if the code does not exist on this machine."};j.push(L),M.push(L)}}else I&&se&&ne&&ne.trim().length>0&&(Je=0)}if(se&&b.fnName==="grep"&&b.args&&b.args.pattern){let I=`${b.args.pattern}|${b.args.path||""}`,J=mo(Y_,I);if(J===z_){B(`${$.yellow} \u26A0 Loop warning: grep pattern "${b.args.pattern.slice(0,40)}" run ${J}\xD7 \u2014 possible search loop${$.reset}`);let L={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${J}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};j.push(L),M.push(L)}else if(J>=K_){B(`${$.red} \u2716 Loop abort: grep pattern run ${J}\xD7 \u2014 aborting runaway search loop${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe,{suppressHint:!0}),We(j);return}if(b.args.path){let L=mo($l,b.args.path),Z=Jn(Co,b.args.path)>=1;if(L===(Z?1:X_)){let Re=b.args.path.split("/").slice(-2).join("/");B(`${$.yellow} \u26A0 Loop warning: "${Re}" grepped ${L}\xD7 with different patterns \u2014 context flood risk${$.reset}`);let fe={role:"user",content:Z?`[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 ${L}\xD7 \u2014 use the search results already in context instead of searching again.`};j.push(fe),M.push(fe)}}}if(se&&(b.fnName==="glob"||b.fnName==="glob_files"||b.fnName==="search_files")&&b.args){if(ne&&!ne.startsWith("(no matches)")){let Z=ne.split(`
|
|
1478
|
-
`);for(let $e of Z)($e.startsWith("/")&&!$e.includes(" ")||!$e.includes(":")&&!$e.startsWith("["))&&Oi.add($e.trim())}let I=b.args.pattern||b.args.query||b.args.path||"",J=mo(V_,I);if(J===J_){B(`${$.yellow} \u26A0 Loop warning: glob pattern "${I.slice(0,40)}" run ${J}\xD7 \u2014 possible search loop${$.reset}`);let Z={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${J}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};j.push(Z),M.push(Z)}else if(J>=Z_){B(`${$.red} \u2716 Loop abort: glob pattern run ${J}\xD7 \u2014 aborting runaway search loop${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe,{suppressHint:!0}),We(j);return}let L=I.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(Z=>Z.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(Z));for(let Z of L){let $e=Z.toLowerCase();jc.has($e)||jc.set($e,new Set);let Re=jc.get($e);if(Re.add(I),Re.size===ex){B(`${$.red} \u2716 Glob core-term block: ${Re.size} different patterns all searching for "${$e}" \u2014 search loop${$.reset}`);let fe={role:"user",content:`[SYSTEM WARNING] You have searched for "${$e}" using ${Re.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.`};j.push(fe),M.push(fe)}else if(Re.size===Q_){B(`${$.yellow} \u26A0 Glob core-term warning: ${Re.size} different patterns searching for "${$e}"${$.reset}`);let fe={role:"user",content:`[SYSTEM WARNING] ${Re.size} different glob patterns all target "${$e}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};j.push(fe),M.push(fe)}}}let re=(b.args?.command||b.args?.cmd||b.args?.script||"").toLowerCase(),Y=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(re)||/\/(health|status|ping|ready|alive)\b/.test(re);if(se&&(b.fnName==="bash"||b.fnName==="ssh_exec")&&Y&&ne.includes('"valid":true')){{let J=At();if(Pn(M,J).percentage>=60){let{messages:Z,tokensRemoved:$e}=Vn(M,J);$e>0&&(M=Z,console.log(`${$.dim} [pre-stop-compress \u2014 ~${$e} tokens freed before STOP injection, now ${Math.round(Pn(M,J).percentage)}%]${$.reset}`))}}let I={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.'};j.push(I),M.push(I),console.log(`${$.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${$.reset}`)}if(se&&(b.fnName==="bash"||b.fnName==="ssh_exec")&&re&&/\bsed\s+-[ie]\b|\btee\b|\bcp\b|\bmv\b|\bpatch\b|\bdd\b|>\s*\S|\becho\b.*>|\bcat\b.*>|\bprintf\b.*>|\bpython[23]?\b.*open\b.*['"'w]|\bnpm\b.*run\b|\byarn\b.*run\b/.test(re)&&(
|
|
1481
|
+
`);for(let $e of Z)($e.startsWith("/")&&!$e.includes(" ")||!$e.includes(":")&&!$e.startsWith("["))&&Oi.add($e.trim())}let I=b.args.pattern||b.args.query||b.args.path||"",J=mo(V_,I);if(J===J_){B(`${$.yellow} \u26A0 Loop warning: glob pattern "${I.slice(0,40)}" run ${J}\xD7 \u2014 possible search loop${$.reset}`);let Z={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${J}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};j.push(Z),M.push(Z)}else if(J>=Z_){B(`${$.red} \u2716 Loop abort: glob pattern run ${J}\xD7 \u2014 aborting runaway search loop${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe,{suppressHint:!0}),We(j);return}let L=I.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(Z=>Z.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(Z));for(let Z of L){let $e=Z.toLowerCase();jc.has($e)||jc.set($e,new Set);let Re=jc.get($e);if(Re.add(I),Re.size===ex){B(`${$.red} \u2716 Glob core-term block: ${Re.size} different patterns all searching for "${$e}" \u2014 search loop${$.reset}`);let fe={role:"user",content:`[SYSTEM WARNING] You have searched for "${$e}" using ${Re.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.`};j.push(fe),M.push(fe)}else if(Re.size===Q_){B(`${$.yellow} \u26A0 Glob core-term warning: ${Re.size} different patterns searching for "${$e}"${$.reset}`);let fe={role:"user",content:`[SYSTEM WARNING] ${Re.size} different glob patterns all target "${$e}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};j.push(fe),M.push(fe)}}}let re=(b.args?.command||b.args?.cmd||b.args?.script||"").toLowerCase(),Y=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(re)||/\/(health|status|ping|ready|alive)\b/.test(re);if(se&&(b.fnName==="bash"||b.fnName==="ssh_exec")&&Y&&ne.includes('"valid":true')){{let J=At();if(Pn(M,J).percentage>=60){let{messages:Z,tokensRemoved:$e}=Vn(M,J);$e>0&&(M=Z,console.log(`${$.dim} [pre-stop-compress \u2014 ~${$e} tokens freed before STOP injection, now ${Math.round(Pn(M,J).percentage)}%]${$.reset}`))}}let I={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.'};j.push(I),M.push(I),console.log(`${$.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${$.reset}`)}if(se&&(b.fnName==="bash"||b.fnName==="ssh_exec")&&re&&/\bsed\s+-[ie]\b|\btee\b|\bcp\b|\bmv\b|\bpatch\b|\bdd\b|>\s*\S|\becho\b.*>|\bcat\b.*>|\bprintf\b.*>|\bpython[23]?\b.*open\b.*['"'w]|\bnpm\b.*run\b|\byarn\b.*run\b/.test(re)&&(ot++,B(`${$.dim} [bash write detected: _bashModifiedFiles=${ot}]${$.reset}`)),ne.startsWith("BLOCKED:")){if(js++,js>=hp){B(`${$.red} \u2716 Loop abort: ${js} consecutive blocked calls \u2014 model not heeding BLOCKED messages${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe,{suppressHint:!0}),We(j);return}}else js=0;if(se)Is=0,_l=!0;else if(Is++,Is===ox){B(`${$.yellow} \u26A0 Loop warning: ${Is} consecutive tool errors \u2014 possible stuck loop${$.reset}`);let I={role:"user",content:`[SYSTEM WARNING] ${Is} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};j.push(I),M.push(I)}else if(Is>=rx){B(`${$.red} \u2716 Loop abort: ${Is} consecutive errors \u2014 aborting stuck loop${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe,{suppressHint:!0}),We(j);return}if(se&&b.fnName==="read_file"&&b.args&&b.args.path){pe.add(b.args.path),go.delete(b.args.path),qe.delete(b.args.path);let I=mo(Co,b.args.path);{let $e=b.args.line_start!=null&&parseInt(b.args.line_start,10)||1,Re=b.args.line_start!=null?parseInt(b.args.line_end,10)||$e+350:350;hs.has(b.args.path)||hs.set(b.args.path,[]),hs.get(b.args.path).push([$e,Re])}if(b._scrollWarn){let{sectionCount:$e,path:Re}=b._scrollWarn,fe={role:"user",content:`[SYSTEM WARNING] "${Re}" \u2014 you have now read ${$e} 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.`};j.push(fe),M.push(fe),B(`${$.yellow} \u26A0 Scroll warning: "${Re.split("/").slice(-2).join("/")}" \u2014 ${$e} sections read \u2014 use grep instead${$.reset}`)}let J=b.args.path.split("/").slice(-2).join("/"),L=!b.args?.line_start&&!b.args?.line_end,Z=Te&&De==="plan";if(!Z&&L&&I===tx){{let Re=At();if(Pn(M,Re).percentage>=60){let{messages:H}=Vn(M,Re);M=H}}B(`${$.yellow} \u26A0 Loop warning: "${J}" read unbounded ${I}\xD7 \u2014 use line_start/line_end${$.reset}`);let $e={role:"user",content:`[SYSTEM WARNING] "${b.args.path}" read ${I}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};j.push($e),M.push($e)}else if(!Z&&L&&I>=nx){B(`${$.red} \u2716 Loop abort: "${J}" read unbounded ${I}\xD7 \u2014 aborting runaway read loop${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe,{suppressHint:!0}),We(j);return}}if(b.fnName==="spawn_agents"){let I=(ne.match(/\bStatus: done\b/g)||[]).length;if((ne.match(/\bStatus: truncated\b/g)||[]).length>0&&I===0){if(Ds++,Ds===ix){B(`${$.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${Ds}\xD7 in a row${$.reset}`);let L={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${Ds}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};j.push(L),M.push(L)}else if(Ds>=ax){console.log(`${$.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Ds}\xD7 \u2014 aborting stuck swarm${$.reset}`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe,{suppressHint:!0}),We(j);return}}else I>0&&(Ds=0)}}if(Tl&&gr&&!(Te&&De==="verify")){let _=await $f(F),b=await Xc(F),ne={role:"user",content:jM(F,_,b)};j.push(ne),M.push(ne),B(`${$.cyan} \u21B3 Post-edit verify prompt injected (${_.length} checks, ${b.length} tests)${$.reset}`)}{let b=yt.reduce((ne,V)=>ne+(typeof V.content=="string"?V.content.length:0),0);if(b>2e5){let ne=yt.map((V,se)=>({i:se,len:typeof V.content=="string"?V.content.length:0})).sort((V,se)=>se.len-V.len);for(let{i:V,len:se}of ne){if(b<=2e5)break;let re=b-2e5,Y=Math.max(se-re,500);Y<se&&typeof yt[V].content=="string"&&(yt[V]={...yt[V],content:yt[V].content.substring(0,Y)+`
|
|
1479
1482
|
...(truncated ${se-Y} chars \u2014 per-message budget)`},b-=se-Y)}}}for(let _ of yt)j.push(_),M.push(_);let hx=ta&&Me.some((_,b)=>{if(!_||!["write_file","edit_file","patch_file"].includes(_.fnName))return!1;let ne=_.args?.path||_.args?.file_path;return CO(ne)&&typeof yt[b]?.content=="string"&&!yt[b].content.startsWith("ERROR")&&!yt[b].content.startsWith("BLOCKED:")});if(bo()&&!n.skillLoop&&xl&&hx){B(`${$.green} \u2713 Synthesis deliverable exit: text deliverable written after evidence threshold reached${$.reset}`),Ve(N,U,F,pe,Pe),We(j);break e}if(Nc(j,M),!Et)for(let _=0;_<yt.length;_++){if(!Me[_]||Me[_].fnName!=="ssh_exec")continue;let b=yt[_];if(!b||typeof b.content!="string")continue;let ne=Xd(b.content);if(ne){Et=!0,Kt=ne.slice(0,120),bn=0,_n=!1,Ln=0,B(`${$.yellow} \u26A1 Root cause detected: ${Kt} \u2014 fix phase (read budget: 3)${$.reset}`);let V={role:"user",content:`[SYSTEM] Root cause identified: ${Kt}. Read only the file that needs fixing, then edit it. Do not read other files.`};j.push(V),M.push(V);break}}for(let _=0;_<yt.length;_++){let b=Me[_];if(!b)continue;let ne=typeof yt[_]?.content=="string"?yt[_].content:"";if(b.fnName==="create_task"){let V=ne.match(/Task #(\d+) created/),se=typeof b.args?.subject=="string"?b.args.subject:"";V&&se&&Ni.set(V[1],se)}else if((b.fnName==="write_file"||b.fnName==="edit_file")&&!ne.startsWith("BLOCKED:")&&ne.trim().length>0){let se=(typeof b.args?.path=="string"?b.args.path:typeof b.args?.file_path=="string"?b.args.file_path:"").split("/").pop().toLowerCase(),re=se.split(/[._\-/]/).filter(Y=>Y.length>2);for(let[Y,me]of Ni){if(Pi.has(Y))continue;let I=me.toLowerCase().split(/\W+/).filter(L=>L.length>3);re.filter(L=>I.some(Z=>Z.includes(L)||L.includes(Z))).length>=1&&(Pi.add(Y),B(`${$.green} \u2714 Auto-matched task #${Y} to ${se}: ${me.slice(0,60)}${$.reset}`))}}}{let _=At();if(Pn(M,_).percentage>=78){let{messages:ne,tokensRemoved:V}=Vn(M,_);V>0&&(M=ne,console.log(`${$.dim} [auto-compressed \u2014 ~${V} tokens freed, now ${Math.round(Pn(M,_).percentage)}%]${$.reset}`))}}if(bo()&&!n.skillLoop&&(Me.some(b=>b&&["write_file","edit_file","patch_file"].includes(b.fnName))?Ie=0:(Ie===0&&(Pt=F.size),Ie++),Ie>=9&&N>=4&&F.size===Pt)){B(`${$.green} \u2713 Stagnation exit: ${Ie} read-only iterations, no new file changes${$.reset}`),process.stdout.isTTY&&process.stderr.write(`${$.yellow} \u26A0 Stagnation detected: ${Ie} iterations without edits \u2014 exiting. The model investigated but did not apply changes.${$.reset}
|
|
1480
|
-
`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe),We(j);break e}let
|
|
1481
|
-
${$.yellow}\u26A0 Max iterations reached.${$.reset}`),await
|
|
1482
|
-
`),await t(a,i,d)}catch(u){if(n=u,!Kw(u)||r>=e.length-1)throw u;if(i==="ollama"&&
|
|
1483
|
-
`),await t(a,i,f)}catch(p){if(n=p,!Kw(p))throw p}}continue}}throw o>0&&o===s?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):s===0?new Error("No configured provider available"):n||new Error("No configured provider available")}async function
|
|
1483
|
+
`),d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe),We(j);break e}let Sp=NM();if(Sp){let _={role:"user",content:`[User note mid-run]: ${Sp}`};j.push(_),M.push(_),console.log(`${$.cyan} \u270E Context added${$.reset}`)}}if(ut>=Jt){if(d&&(d.stop(),d=null),u(null),Ve(N,U,F,pe,Pe),We(j),wi(j),Te&&De==="plan"){let dt=[...j].reverse().find(bt=>bt.role==="assistant"),vt=typeof dt?.content=="string"?dt.content:"",$s=await xi("implement",vt);if($s){j.push($s),M=[{role:"system",content:await gf()},...j],Jt=ho("implement"),B(`${$.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${$.reset}`);continue e}}else if(Te&&De==="verify"){B(`${$.yellow} \u26A0 Verify budget exhausted \u2014 completing session${$.reset}`);break e}let{getActiveProviderName:Oe}=Xe();if(Oe()==="ollama"&&bl<$p){if(F.size===0&&!_l){console.log(`${$.yellow} \u26A0 Max iterations reached with no progress. Stopping.${$.reset}`);break e}bl++,Jt=20,console.log(`${$.dim} \u2500\u2500 auto-extending (+20 turns, ext ${bl}/${$p}) \u2500\u2500${$.reset}`);continue e}if(console.log(`
|
|
1484
|
+
${$.yellow}\u26A0 Max iterations reached.${$.reset}`),await Ow(" Continue for 20 more turns?")){Jt=20;continue e}console.log(`${$.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${$.reset}`)}break e}await gp()}zw.exports={processInput:tN,clearConversation:GM,getConversationLength:zM,getConversationMessages:KM,setConversationMessages:XM,setAbortSignalGetter:uM,setMaxIterations:lM,invalidateSystemPromptCache:af,clearToolFilterCache:$M,getCachedFilteredTools:Dw,buildSystemPrompt:gf,splitSystemPrompt:HM,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:mf,getProjectContextHash:qw,_inferVerificationCommands:$f,_inferRelevantTests:Xc,_inferSymbolTargets:Hw,_buildSymbolHintBlock:Gw,buildUserContent:Iw,_detectImageURLs:Nw,_downloadImageURL:Pw,_grabClipboardImage:Lw,detectFrustration:jw,detectAndTruncateLoop:tf,injectMidRunNote:MM,resetSessionTracking:Yw}});var Xe=X((Z2,Jw)=>{var{OllamaProvider:nN}=mh(),{OpenAIProvider:sN}=wh(),{AnthropicProvider:oN}=vh(),{GeminiProvider:rN}=Th(),{LocalProvider:iN}=Ah(),{checkBudget:aN}=xs(),xf={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"}},bf=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Xw={};for(let[t,e]of Object.entries(xf))for(let n of Object.values(e))Xw[n]=t;function _f(t,e){let n=Xw[t];return n&&xf[n][e]||t}var Tt={},Xt=null,mt=null,Li=[];function vn(){if(Object.keys(Tt).length>0)return;$r("ollama",new nN),$r("openai",new sN),$r("anthropic",new oN),$r("gemini",new rN),$r("local",new iN);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;Tt[t]?(Xt=t,mt=e||Tt[t].defaultModel):(Xt="ollama",mt="kimi-k2.5");let n=process.env.FALLBACK_CHAIN;n&&(Li=n.split(",").map(o=>o.trim()).filter(Boolean))}function $r(t,e){Tt[t]=e}function cN(t){return vn(),Tt[t]||null}function vf(){return vn(),Tt[Xt]||null}function lN(){return vn(),Xt}function uN(){return vn(),mt}function dN(){vn();let t=vf();if(!t)return{id:mt,name:mt,provider:Xt};let e=t.getModel(mt);return e?{...e,provider:Xt}:{id:mt,name:mt,provider:Xt}}function kf(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(Tt[n]||["ollama","openai","anthropic","gemini","local"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function fN(t){vn();let{provider:e,model:n}=kf(t);if(e){let s=Tt[e];return s&&(s.getModel(n)||e==="local"||e==="ollama")?(Xt=e,mt=n,Vc(),!0):!1}let o=vf();if(o&&o.getModel(n))return mt=n,Vc(),!0;for(let[s,r]of Object.entries(Tt))if(r.getModel(n))return Xt=s,mt=n,Vc(),!0;return!1}function Vc(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Ee();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=en();t()}catch{}}function pN(){vn();let t=new Set;for(let e of Object.values(Tt))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function hN(){return vn(),Object.entries(Tt).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===Xt&&n.id===mt}))}))}function mN(){vn();let t=[];for(let[e,n]of Object.entries(Tt)){let o=n.isConfigured();for(let s of Object.values(n.getModels()))t.push({spec:`${e}:${s.id}`,name:s.name,provider:e,configured:o})}return t}function gN(t){Li=Array.isArray(t)?t:[]}function yN(){return[...Li]}function Kw(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 Vw(t){let e=[Xt,...Li.filter(r=>r!==Xt)],n,o=0,s=0;for(let r=0;r<e.length;r++){let i=e[r],a=Tt[i];if(!a||!a.isConfigured())continue;s++;let c=aN(i);if(!c.allowed){o++,n=new Error(`Budget limit reached for ${i}: $${c.spent.toFixed(2)} / $${c.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?_f(mt,i):mt;return u&&d!==mt&&process.stderr.write(` [fallback: ${i}:${d}]
|
|
1485
|
+
`),await t(a,i,d)}catch(u){if(n=u,!Kw(u)||r>=e.length-1)throw u;if(i==="ollama"&&bf.length>0){let d=isFallback?_f(mt,i):mt;for(let f of bf)if(f!==d)try{return process.stderr.write(` [ollama fallback: ${f}]
|
|
1486
|
+
`),await t(a,i,f)}catch(p){if(n=p,!Kw(p))throw p}}continue}}throw o>0&&o===s?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):s===0?new Error("No configured provider available"):n||new Error("No configured provider available")}async function $N(t,e,n={}){vn();let o=n.model,s=o?(()=>{let{model:i}=kf(o);return i||o})():void 0,r=s!==o?{...n,model:s}:n;return Vw((i,a,c)=>i.stream(t,e,{model:c,signal:r.signal,...r}))}async function wN(t,e,n={}){if(vn(),n.provider){let o=Tt[n.provider];if(!o||!o.isConfigured())throw new Error(`Provider '${n.provider}' is not available`);let s={model:n.model||mt,...n};try{return await o.chat(t,e,s)}catch(r){if(typeof o.stream=="function")try{return await o.stream(t,e,{...s,onToken:()=>{}})}catch{}throw r}}return Vw(async(o,s,r)=>{try{return await o.chat(t,e,{model:r,...n})}catch(i){if(typeof o.stream=="function")try{return await o.stream(t,e,{model:r,...n,onToken:()=>{}})}catch{}throw i}})}function bN(){vn();let t=[];for(let[e,n]of Object.entries(Tt))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function _N(){for(let t of Object.keys(Tt))delete Tt[t];Xt=null,mt=null,Li=[]}Jw.exports={registerProvider:$r,getProvider:cN,getActiveProvider:vf,getActiveProviderName:lN,getActiveModelId:uN,getActiveModel:dN,setActiveModel:fN,getModelNames:pN,parseModelSpec:kf,listProviders:hN,listAllModels:mN,callStream:$N,callChat:wN,getConfiguredProviders:bN,setFallbackChain:gN,getFallbackChain:yN,resolveModelForProvider:_f,MODEL_EQUIVALENTS:xf,OLLAMA_FALLBACK_MODELS:bf,_reset:_N}});var Sf=X((Q2,Zw)=>{"use strict";var ts=require("fs"),Jc=require("path"),xN=require("readline"),{T:wr}=Lt(),Le=wr.reset,Ii=wr.bold,Ot=wr.dim,Zc=wr.yellow,qi=wr.cyan,ji=wr.green;function vN(t){return(e,n="")=>new Promise(o=>{let s=n?` ${Ot}[${n}]${Le}`:"";t.question(` ${qi}${e}${s}${Le}: `,r=>o(r.trim()||n))})}function Di(t,e){return new Promise(n=>{e&&e.pause(),process.stdout.write(` ${qi}${t}${Le}: `);let o=process.stdin,s=o.isRaw,r="";o.setRawMode(!0),o.resume(),o.setEncoding("utf8");let i=a=>{a==="\r"||a===`
|
|
1484
1487
|
`?(o.setRawMode(s||!1),o.removeListener("data",i),process.stdout.write(`
|
|
1485
1488
|
`),e&&e.resume(),n(r)):a===""?(process.stdout.write(`
|
|
1486
|
-
`),process.exit(0)):a==="\x7F"?r.length>0&&(r=r.slice(0,-1),process.stdout.write("\b \b")):(r+=a,process.stdout.write("*"))};o.on("data",i)})}async function
|
|
1489
|
+
`),process.exit(0)):a==="\x7F"?r.length>0&&(r=r.slice(0,-1),process.stdout.write("\b \b")):(r+=a,process.stdout.write("*"))};o.on("data",i)})}async function kN({rl:t=null,force:e=!1}={}){if(!e){let p=ts.existsSync(Jc.join(process.cwd(),".env"))||ts.existsSync(Jc.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,o=t||xN.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),s=vN(o),r=!e;console.log(),console.log(r?`${Zc}${Ii} \u2726 Welcome to nex-code! No configuration found.${Le}`:`${qi}${Ii} \u2726 nex-code \u2014 Provider & API Key Setup${Le}`),console.log(`${Ot} \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${Le}`),r&&console.log(` Let's set you up in 60 seconds.
|
|
1487
1490
|
`),console.log(` ${Ii}Which AI provider do you want to use?${Le}
|
|
1488
1491
|
`),console.log(` ${ji}1)${Le} ${Ii}Ollama Cloud${Le} ${Ot}recommended \u2014 devstral-2:123b, no API key needed${Le}`),console.log(` ${Ot} (also works with a local Ollama server)${Le}`),console.log(` ${Ot}2) Anthropic Claude (claude-sonnet-4-6 etc.)${Le}`),console.log(` ${Ot}3) OpenAI GPT-4o, GPT-4.1 etc.${Le}`),console.log(` ${Ot}4) Gemini Google Gemini 2.x${Le}`),console.log(` ${Ot}5) Skip / Cancel${Le}`),console.log();let i=await s("Enter number","1"),a=[];if(i==="5"){n&&o.close(),console.log(`
|
|
1489
1492
|
${Ot} Cancelled \u2014 no changes made.${Le}
|
|
@@ -1506,20 +1509,20 @@ ${Zc} No key entered \u2014 cancelled.${Le}
|
|
|
1506
1509
|
${ji} \u2713 Saved to ${u}${Le}`),a.some(h=>h.includes("API_KEY"))&&console.log(`${Ot} (key stored locally \u2014 never committed)${Le}`)}if(process.env.DEFAULT_PROVIDER)try{let{setActiveModel:p}=Xe(),m=process.env.DEFAULT_MODEL?`${process.env.DEFAULT_PROVIDER}:${process.env.DEFAULT_MODEL}`:process.env.DEFAULT_PROVIDER;p(m),console.log(`${ji} \u2713 Switched to ${m} for this session${Le}`)}catch{}console.log(`
|
|
1507
1510
|
${ji} \u2713 Setup complete!${Le}`),console.log(`
|
|
1508
1511
|
${qi}\u{1F4A1} Tip: Run ${Ii}/benchmark${Le} ${qi}to automatically find and use the best models for your tasks.${Le}
|
|
1509
|
-
`)}Zw.exports={runSetupWizard:
|
|
1512
|
+
`)}Zw.exports={runSetupWizard:kN}});var Qc=X((ej,rb)=>{"use strict";var Dn=require("fs"),Fi=require("path"),{atomicWrite:tb}=os(),SN=20,EN=3,nb=3,TN=14400*1e3;function Bi(){return Fi.join(process.cwd(),".nex","dream-logs")}function Ef(){return Fi.join(Bi(),"_meta.json")}function RN(){let t=Bi();return Dn.existsSync(t)||Dn.mkdirSync(t,{recursive:!0}),t}function sb(t){if(!Array.isArray(t)||t.length===0)return null;let e={},n={},o={},s={},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")&&(o[m]=(o[m]||0)+1),(f==="write_file"||f==="edit_file"||f==="patch_file")&&(s[m]=(s[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<EN?null:{timestamp:new Date().toISOString(),userMessages:a,assistantMessages:c,totalToolCalls:r,totalErrors:i,toolCalls:e,toolErrors:n,filesAccessed:Qw(o,10),filesModified:Qw(s,10)}}function CN(t){let e=sb(t);if(!e)return null;let n=RN(),o=`dream-${Date.now()}.json`,s=Fi.join(n,o);try{return tb(s,JSON.stringify(e,null,2)),MN(n),s}catch{return null}}function AN(){let t=Ef();if(!Dn.existsSync(t))return!0;try{let s=JSON.parse(Dn.readFileSync(t,"utf-8")),r=new Date(s.lastConsolidation||0).getTime();if(Date.now()-r<TN)return!1}catch{return!0}let e=Tf(),n=Rf();return e.filter(s=>!n.processed?.includes(s)).length>=nb}function ON(){let t=Tf(),e=Rf(),n=t.filter(h=>!e.processed?.includes(h));if(n.length<nb)return{insights:[],memoriesWritten:0};let o=[];for(let h of n)try{let g=JSON.parse(Dn.readFileSync(Fi.join(Bi(),h),"utf-8"));o.push(g)}catch{}if(o.length===0)return{insights:[],memoriesWritten:0};let s=[],r=0,i={},a={},c={};for(let h of o){for(let[g,y]of Object.entries(h.toolCalls||{}))i[g]=(i[g]||0)+y;for(let[g,y]of Object.entries(h.toolErrors||{}))a[g]=(a[g]||0)+y;for(let[g,y]of Object.entries(h.filesAccessed||{}))c[g]=(c[g]||0)+y}let u=[];for(let[h,g]of Object.entries(a)){let y=i[h]||g,w=g/y;w>.3&&g>=3&&u.push({tool:h,errors:g,calls:y,rate:Math.round(w*100)})}if(u.length>0){let h=u.sort((w,x)=>x.rate-w.rate).map(w=>`- ${w.tool}: ${w.rate}% error rate (${w.errors}/${w.calls} calls)`).join(`
|
|
1510
1513
|
`),g=`High-error tools detected across ${o.length} sessions:
|
|
1511
1514
|
${h}`;s.push(g),eb("dream-error-prone-tools","Tools with high error rates across recent sessions",g)&&r++}let d=o.length,f={};for(let h of o){let g=new Set;for(let y of Object.keys(h.filesAccessed||{}))g.has(y)||(f[y]=(f[y]||0)+1,g.add(y))}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(`
|
|
1512
1515
|
`),g=`Frequently accessed files across ${d} sessions:
|
|
1513
|
-
${h}`;s.push(g),eb("dream-hot-files","Files accessed frequently across multiple sessions",g)&&r++}let m=o.map(h=>h.userMessages===0?null:h.totalToolCalls/h.userMessages).filter(Boolean);if(m.length>=3){let h=m.reduce((y,w)=>y+w,0)/m.length,g=o.reduce((y,w)=>y+(w.totalErrors||0),0)/o.length;if(h>15){let y=`High tool-call density: avg ${h.toFixed(1)} tool calls per user message across ${o.length} sessions. Consider more targeted investigation.`;s.push(y)}if(g>5){let y=`High error rate: avg ${g.toFixed(1)} errors per session across ${o.length} sessions.`;s.push(y)}}return ob({lastConsolidation:new Date().toISOString(),processed:[...e.processed||[],...n],totalConsolidations:(e.totalConsolidations||0)+1}),{insights:s,memoriesWritten:r}}function Qw(t,e=10){return Object.fromEntries(Object.entries(t).sort(([,n],[,o])=>o-n).slice(0,e))}function
|
|
1514
|
-
`))}function ib(t,e){if(!
|
|
1516
|
+
${h}`;s.push(g),eb("dream-hot-files","Files accessed frequently across multiple sessions",g)&&r++}let m=o.map(h=>h.userMessages===0?null:h.totalToolCalls/h.userMessages).filter(Boolean);if(m.length>=3){let h=m.reduce((y,w)=>y+w,0)/m.length,g=o.reduce((y,w)=>y+(w.totalErrors||0),0)/o.length;if(h>15){let y=`High tool-call density: avg ${h.toFixed(1)} tool calls per user message across ${o.length} sessions. Consider more targeted investigation.`;s.push(y)}if(g>5){let y=`High error rate: avg ${g.toFixed(1)} errors per session across ${o.length} sessions.`;s.push(y)}}return ob({lastConsolidation:new Date().toISOString(),processed:[...e.processed||[],...n],totalConsolidations:(e.totalConsolidations||0)+1}),{insights:s,memoriesWritten:r}}function Qw(t,e=10){return Object.fromEntries(Object.entries(t).sort(([,n],[,o])=>o-n).slice(0,e))}function Tf(){let t=Bi();if(!Dn.existsSync(t))return[];try{return Dn.readdirSync(t).filter(e=>e.startsWith("dream-")&&e.endsWith(".json")).sort()}catch{return[]}}function MN(t){try{let e=Dn.readdirSync(t).filter(n=>n.startsWith("dream-")&&n.endsWith(".json")).sort();for(;e.length>SN;){let n=e.shift();Dn.unlinkSync(Fi.join(t,n))}}catch{}}function Rf(){let t=Ef();if(!Dn.existsSync(t))return{};try{return JSON.parse(Dn.readFileSync(t,"utf-8"))}catch{return{}}}function ob(t){try{tb(Ef(),JSON.stringify(t,null,2))}catch{}}function eb(t,e,n){try{let{saveMemory:o}=Rn();return o("feedback",t,n,e).ok}catch{return!1}}rb.exports={extractSessionStats:sb,writeDreamLog:CN,shouldConsolidate:AN,consolidate:ON,_getDreamDir:Bi,_listDreamLogs:Tf,_readMeta:Rf,_writeMeta:ob}});var lb=X((nj,cb)=>{"use strict";var el=require("fs"),{T:qn,isDark:NN}=Lt(),an="\x1B[0m",PN=!NN,LN=process.env.FOOTER_DEBUG==="1"||process.env.FOOTER_DEBUG==="2",IN=process.env.FOOTER_DEBUG==="2",tj=process.env.FOOTER_DEBUG==="3",br=null;function Os(...t){LN&&(br||(br=el.openSync("/tmp/footer-debug.log","w",384)),el.writeSync(br,t.join(" ")+`
|
|
1517
|
+
`))}function ib(t,e){if(!IN||typeof e!="string")return;br||(br=el.openSync("/tmp/footer-debug.log","w",384));let n=e.replace(/\x1b\[([^a-zA-Z]*)([a-zA-Z])/g,(o,s,r)=>`<ESC[${s}${r}>`).replace(/\x1b([^[])/g,(o,s)=>`<ESC${s}>`).replace(/\r/g,"<CR>").replace(/\n/g,`<LF>
|
|
1515
1518
|
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,o=>`<${o.charCodeAt(0).toString(16).padStart(2,"0")}>`);el.writeSync(br,`${t}: ${n}
|
|
1516
|
-
`)}function ab(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var
|
|
1519
|
+
`)}function ab(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Cf=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:o,mode:s}={}){e!==void 0&&(this._statusModel=e),n!==void 0&&(this._statusBranch=n),o!==void 0&&(this._statusProject=o),s!==void 0&&(this._statusMode=s),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,o=this._statusBranch,s=this._statusProject,r=this._statusMode;if(!n)return`${qn.footer_sep}\u2550${"\u2550".repeat(Math.max(0,e-2))}\u2550${an}`;let i=` ${qn.footer_divider}\u2502${an} `,a=o?`${qn.footer_branch}git:${o}${an}`:"",c=s?`${qn.footer_project}${s}${an}`:"",u=[];n&&u.push(`${qn.footer_model}${n}${an}`),a&&u.push(a),c&&u.push(c);let d=u.join(i),f=[n,o?`git:${o}`:"",s].filter(Boolean).join(" \xB7 ").length,p="\u257C ";if(r){let g=`[${r}]`,y=g.length,w=Math.max(0,e-p.length-f-1-1-y-3),x="\u2550".repeat(w);return`${qn.footer_sep}${p}${an}${d}${qn.footer_sep} ${x} ${an}${qn.footer_mode}${g}${an}${qn.footer_sep} \u257E${an}`}let m=Math.max(0,e-p.length-f-2),h="\u2550".repeat(m);return`${qn.footer_sep}${p}${an}${d}${qn.footer_sep} ${h}${an}`}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(PN)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 ib("RAW",e),this._origWrite?this._origWrite(e):process.stdout.write(e)}_relayout(e){if(!this._origWrite)return;let n=this._origWrite,o=this._rows,s=this._cols,r=Math.max(1,o-2);Os("RELAYOUT:",e,"rows="+o,"cols="+s,"scrollEnd="+r,"cursorOnInput="+this._cursorOnInputRow),this._prevTermRows=o,this._prevTermCols=s;let i=Math.min(this._lastOutputRow+1,r+1),a="";for(let c=i;c<=o;c++)a+=this._goto(c)+"\x1B[2K";n(a),this._setScrollRegion(),this._lastOutputRow=Math.min(this._lastOutputRow,r),this.drawFooter(),this._cursorOnInputRow&&this._rl&&this._rl.prompt(!0),this._dirty=!1}activate(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,o=process.stdout.write.bind(process.stdout);this._origWrite=o,process.stdout.write=function(h,...g){if(ib("PATCH",h),!n._active||typeof h!="string")return o(h,...g);if(n._inRefreshLine){let k=h.replace(/\n/g,"");return k?o(k,...g):!0}if(n._cursorOnInputRow){if(h.length<=4&&!h.includes(`
|
|
1517
1520
|
`)&&!h.includes("\r"))return Os("STDOUT: input-row intercept:",JSON.stringify(h)),n._origRefreshLine&&n._doRefreshLine(),!0;Os("STDOUT: non-echo on input row, anchoring to workspace, data="+JSON.stringify(h).slice(0,100)),n._cursorOnInputRow=!1,o(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd)))}let y=n._cols||80,w=0,x=h.split(`
|
|
1518
1521
|
`);for(let k=0;k<x.length;k++){let v=ab(x[k]);v>0&&(w+=Math.floor((v-1)/y))}let S=x.length-1;return S+w>0&&(n._lastOutputRow=Math.min(n._lastOutputRow+S+w,n._scrollEnd)),o(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 x=n._origStderrWrite(h,...g);return n._origWrite("\x1B8"),x}n._origWrite(n._goto(w))}let y=n._origStderrWrite(h,...g);return typeof h=="string"&&h.includes(`
|
|
1519
|
-
`)&&!/\x1b\[\d+A/.test(h)&&n._cursorOnInputRow&&(n.drawFooter(),n._origWrite(n._goto(n._rowInput)+"\x1B[2K")),y},this._origLog=console.log,this._origError=console.error;function s(...h){if(!n._active){n._origLog(...h);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origLog(...h),n.drawFooter(),o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}function r(...h){if(!n._active){n._origError(...h);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origError(...h),n.drawFooter(),o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}console.log=s,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);Os("PROMPT: goto rowInput="+n._rowInput),e.prevRows=0,o(n._goto(n._rowInput)+an+"\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);o(n._goto(n._rowInput)+"\x1B[2K"),e.prevRows=0,n._cursorOnInputRow=!0,i(h,y=>{o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!1,n.drawFooter(),g(y)})};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,o(n._goto(n._rowInput)+an+"\x1B[2K");let h=n._cols,g=e._prompt||"",y=ab(g),w=h-y-1;n._inRefreshLine=!0;try{if(e.line.length<=w){Os("REFRESH: short line, len="+e.line.length),u();return}Os("REFRESH: long line, len="+e.line.length+", max="+w);let x=e.line,S=e.cursor,k=Math.max(1,w-1),v=Math.max(0,S-k),C=(v>0?"\xAB":"")+x.slice(v,v+k+(v>0?0:1));e.line=C,e.cursor=C.length,u(),e.line=x,e.cursor=S}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&&(Os("LINE: leaving input row"),n._cursorOnInputRow=!1,o(n._goto(n._rowInput)+"\x1B[2K"),o(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n.drawFooter())});let 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)&&(Os("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}}};cb.exports={StickyFooter:
|
|
1522
|
+
`)&&!/\x1b\[\d+A/.test(h)&&n._cursorOnInputRow&&(n.drawFooter(),n._origWrite(n._goto(n._rowInput)+"\x1B[2K")),y},this._origLog=console.log,this._origError=console.error;function s(...h){if(!n._active){n._origLog(...h);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origLog(...h),n.drawFooter(),o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}function r(...h){if(!n._active){n._origError(...h);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origError(...h),n.drawFooter(),o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}console.log=s,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);Os("PROMPT: goto rowInput="+n._rowInput),e.prevRows=0,o(n._goto(n._rowInput)+an+"\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);o(n._goto(n._rowInput)+"\x1B[2K"),e.prevRows=0,n._cursorOnInputRow=!0,i(h,y=>{o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!1,n.drawFooter(),g(y)})};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,o(n._goto(n._rowInput)+an+"\x1B[2K");let h=n._cols,g=e._prompt||"",y=ab(g),w=h-y-1;n._inRefreshLine=!0;try{if(e.line.length<=w){Os("REFRESH: short line, len="+e.line.length),u();return}Os("REFRESH: long line, len="+e.line.length+", max="+w);let x=e.line,S=e.cursor,k=Math.max(1,w-1),v=Math.max(0,S-k),C=(v>0?"\xAB":"")+x.slice(v,v+k+(v>0?0:1));e.line=C,e.cursor=C.length,u(),e.line=x,e.cursor=S}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&&(Os("LINE: leaving input row"),n._cursorOnInputRow=!1,o(n._goto(n._rowInput)+"\x1B[2K"),o(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n.drawFooter())});let 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)&&(Os("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}}};cb.exports={StickyFooter:Cf}});var fb=X((sj,db)=>{var{C:tt}=He(),{listProviders:jN,getActiveProviderName:DN,getActiveModelId:qN,setActiveModel:FN}=Xe();function ub(t,e,n={}){let{title:o="Select",hint:s="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=n;return new Promise(r=>{let i=e.map((w,x)=>w.isHeader?-1:x).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 v=0;v<p;v++)process.stdout.write(`\x1B[2K
|
|
1520
1523
|
`);process.stdout.write(`\x1B[${p}A`)}let w=[];w.push(` ${tt.bold}${tt.cyan}${o}${tt.reset}`),w.push(` ${tt.dim}${s}${tt.reset}`),w.push("");let{start:x,end:S}=f();x>0&&w.push(` ${tt.dim}\u2191 more${tt.reset}`);for(let v=x;v<S;v++){let C=e[v];if(C.isHeader){w.push(` ${tt.bold}${tt.dim}${C.label}${tt.reset}`);continue}let q=i[c]===v,D=q?`${tt.cyan}> `:" ",ee=C.isCurrent?` ${tt.yellow}<current>${tt.reset}`:"";q?w.push(`${D}${tt.bold}${C.label}${tt.reset}${ee}`):w.push(`${D}${tt.dim}${C.label}${tt.reset}${ee}`)}S<e.length&&w.push(` ${tt.dim}\u2193 more${tt.reset}`);let k=w.join(`
|
|
1521
1524
|
`);process.stdout.write(k+`
|
|
1522
|
-
`),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",y),process.stdin.isTTY&&h!==void 0&&process.stdin.setRawMode(h),t.resume()}function y(w,x){if(x){if(x.name==="up"||x.ctrl&&x.name==="p"){c>0&&(c--,m());return}if(x.name==="down"||x.ctrl&&x.name==="n"){c<i.length-1&&(c++,m());return}if(x.name==="return"){let S=e[i[c]];g(),r(S?S.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",y),m()})}async function
|
|
1525
|
+
`),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",y),process.stdin.isTTY&&h!==void 0&&process.stdin.setRawMode(h),t.resume()}function y(w,x){if(x){if(x.name==="up"||x.ctrl&&x.name==="p"){c>0&&(c--,m());return}if(x.name==="down"||x.ctrl&&x.name==="n"){c<i.length-1&&(c++,m());return}if(x.name==="return"){let S=e[i[c]];g(),r(S?S.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",y),m()})}async function BN(t){let e=jN(),n=DN(),o=qN(),s=[];for(let i of e)if(i.models.length!==0){s.push({label:i.provider,value:null,isHeader:!0});for(let a of i.models){let c=i.provider===n&&a.id===o;s.push({label:` ${a.name} (${i.provider}:${a.id})`,value:`${i.provider}:${a.id}`,isCurrent:c})}}let r=await ub(t,s,{title:"Select Model"});return r?(FN(r),console.log(`${tt.green}Switched to ${r}${tt.reset}`),!0):(console.log(`${tt.dim}Cancelled${tt.reset}`),!1)}db.exports={pickFromList:ub,showModelPicker:BN}});var Of=X((rj,bb)=>{var pb=require("fs"),UN=require("path"),{atomicWrite:WN,withFileLockSync:HN}=os(),{callChat:hb}=Xe(),{remember:GN,listMemories:oj,recall:YN}=Rn(),Af=4,zN=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
1523
1526
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
1524
1527
|
|
|
1525
1528
|
Return ONLY valid JSON in this exact format:
|
|
@@ -1547,13 +1550,13 @@ Rules:
|
|
|
1547
1550
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
1548
1551
|
- Return ONLY the JSON, no markdown, no explanation`;function mb(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(`
|
|
1549
1552
|
|
|
1550
|
-
`)}async function gb(t){if(t.filter(s=>s.role==="user").length<
|
|
1553
|
+
`)}async function gb(t){if(t.filter(s=>s.role==="user").length<Af)return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=mb(t);if(!n.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let o=[{role:"system",content:zN},{role:"user",content:`Conversation to analyze:
|
|
1551
1554
|
|
|
1552
|
-
${n}`}];try{let i=((await hb(o,[],{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(s){return{memories:[],nex_additions:[],summary:null,error:s.message}}}function yb(t){let e=[];for(let{key:n,value:o}of t||[]){if(!n||!o||typeof n!="string"||typeof o!="string")continue;let s=n.trim().replace(/\s+/g,"-").substring(0,60),r=o.trim().substring(0,200);if(!s||!r)continue;let i=
|
|
1555
|
+
${n}`}];try{let i=((await hb(o,[],{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(s){return{memories:[],nex_additions:[],summary:null,error:s.message}}}function yb(t){let e=[];for(let{key:n,value:o}of t||[]){if(!n||!o||typeof n!="string"||typeof o!="string")continue;let s=n.trim().replace(/\s+/g,"-").substring(0,60),r=o.trim().substring(0,200);if(!s||!r)continue;let i=YN(s);i!==r&&(GN(s,r),e.push({key:s,value:r,action:i?"updated":"added"}))}return e}function $b(t){if(!t||t.length===0)return[];let e=UN.join(process.cwd(),"NEX.md");return HN(e,()=>{let n="";try{pb.existsSync(e)&&(n=pb.readFileSync(e,"utf-8"))}catch{}let o=[],s=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)||(o.push(i),s=s?s.endsWith(`
|
|
1553
1556
|
`)?s+i:s+`
|
|
1554
1557
|
`+i:i)}return o.length>0&&(s.endsWith(`
|
|
1555
1558
|
`)||(s+=`
|
|
1556
|
-
`),
|
|
1559
|
+
`),WN(e,s)),o})}async function KN(t){let e=await gb(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};if(!Array.isArray(e.memories))return{applied:[],nexAdded:[],summary:null,error:"Invalid memories format"};let n=yb(e.memories),o=$b(e.nex_additions);return{applied:n,nexAdded:o,summary:e.summary}}var XN=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
1557
1560
|
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
1558
1561
|
|
|
1559
1562
|
Return ONLY valid JSON in this exact format:
|
|
@@ -1587,24 +1590,24 @@ Rules:
|
|
|
1587
1590
|
---
|
|
1588
1591
|
- Maximum 3 documents per session. Quality over quantity.
|
|
1589
1592
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
1590
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function wb(t){if(t.filter(s=>s.role==="user").length<
|
|
1593
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function wb(t){if(t.filter(s=>s.role==="user").length<Af)return{documents:[],skip_reason:"Session too short"};let n=mb(t);if(!n.trim())return{documents:[],skip_reason:"No usable content"};let o=[{role:"system",content:XN},{role:"user",content:`Conversation to analyze:
|
|
1591
1594
|
|
|
1592
|
-
${n}`}];try{let i=((await hb(o,[],{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(s){return{documents:[],error:s.message}}}async function
|
|
1595
|
+
${n}`}];try{let i=((await hb(o,[],{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(s){return{documents:[],error:s.message}}}async function VN(t){if(!Array.isArray(t))return{written:[],skipped:[],error:"messages must be an array"};let e=await wb(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:o}=Zr(),s=[],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=o(a);if(c.content){let d=`
|
|
1593
1596
|
|
|
1594
1597
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
1595
1598
|
|
|
1596
|
-
${i.content}`;n(a,c.content+d),s.push({name:a,reason:i.reason||"",action:"updated"})}else n(a,i.content),s.push({name:a,reason:i.reason||"",action:"created"})}return{written:s,skipped:r}}bb.exports={learnFromSession:
|
|
1599
|
+
${i.content}`;n(a,c.content+d),s.push({name:a,reason:i.reason||"",action:"updated"})}else n(a,i.content),s.push({name:a,reason:i.reason||"",action:"created"})}return{written:s,skipped:r}}bb.exports={learnFromSession:KN,learnBrainFromSession:VN,reflectOnSession:gb,reflectBrain:wb,applyMemories:yb,applyNexAdditions:$b,LEARN_MIN_MESSAGES:Af}});var Ms=X((ij,_b)=>{var{C:Ye}=He();function JN(t){return t.tree&&t.tree.branches?t.tree:{branches:{main:{messages:t.messages||[],parentBranch:null,forkIndex:0}},activeBranch:"main"}}function ZN(t){let e=t.branches[t.activeBranch];return e?e.messages:[]}function QN(t,e){let n=t.branches[t.activeBranch];n&&(n.messages=e)}function eP(t,e,n){let o=t.activeBranch,s=t.branches[o].messages;if(e<0||e>=s.length)throw new Error(`Fork index ${e} out of range (0-${s.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:s.slice(0,e+1),parentBranch:o,forkIndex:e},t.activeBranch=n,{tree:t,branchName:n}}function tP(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 nP(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 o=n.messages.length-(e+1);return n.messages=n.messages.slice(0,e+1),{tree:t,truncated:o}}function sP(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 oP(t){let e=[];e.push(`${Ye.bold}${Ye.cyan}Session Tree${Ye.reset}
|
|
1597
1600
|
`);let n=Object.keys(t.branches);for(let o of n){let s=t.branches[o],r=o===t.activeBranch,i=r?`${Ye.green}* `:" ",a=r?`${Ye.green}${Ye.bold}${o}${Ye.reset}`:`${Ye.cyan}${o}${Ye.reset}`,c=s.messages.length,u=s.parentBranch?` ${Ye.dim}(forked from ${s.parentBranch}@${s.forkIndex})${Ye.reset}`:"";e.push(`${i}${a} \u2014 ${c} messages${u}`);let f=s.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(` ${Ye.dim}> ${m}${m.length>=60?"...":""}${Ye.reset}`)}}return e.join(`
|
|
1598
|
-
`)}function
|
|
1601
|
+
`)}function rP(t,e=20){let n=t.branches[t.activeBranch];if(!n)return"No active branch.";let o=n.messages,s=[];s.push(`${Ye.bold}${Ye.cyan}Timeline: ${t.activeBranch}${Ye.reset} (${o.length} messages)
|
|
1599
1602
|
`);let r=Math.max(0,o.length-e);for(let i=r;i<o.length;i++){let a=o[i],c=a.role,u=c==="user"?Ye.green:c==="assistant"?Ye.cyan:c==="system"?Ye.yellow:Ye.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?` ${Ye.dim}[${a.tool_calls.length} tool calls]${Ye.reset}`:"";s.push(` ${Ye.dim}${String(i).padStart(3)}${Ye.reset} ${u}${c.padEnd(9)}${Ye.reset} ${d}${f}`)}return r>0&&s.splice(1,0,` ${Ye.dim}... ${r} earlier messages not shown${Ye.reset}`),s.join(`
|
|
1600
|
-
`)}_b.exports={initTree:
|
|
1603
|
+
`)}_b.exports={initTree:JN,getActiveMessages:ZN,setActiveMessages:QN,createBranch:eP,switchBranch:tP,gotoMessage:nP,deleteBranch:sP,renderTree:oP,renderTimeline:rP}});var Tb=X((aj,Eb)=>{var{spawn:iP}=require("child_process"),xb=require("path"),vb=require("fs"),aP=require("os"),Ns=new Map;function kb(t){return typeof t!="string"?t:t.replace(/\$\{([^}]+)\}/g,(e,n)=>process.env[n]!==void 0?process.env[n]:"")}function Sb(t){let e=t||process.env.NEX_MCP_CONFIG||null,n=e?[e]:[xb.join(process.cwd(),".nex","mcp.json"),xb.join(aP.homedir(),".nex","mcp.json")];for(let o of n)if(vb.existsSync(o))try{return JSON.parse(vb.readFileSync(o,"utf-8"))}catch{}return{servers:{}}}function tl(t,e,n={},o=1e4){return new Promise((s,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:n})+`
|
|
1601
1604
|
`,c="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},o);function d(p){c+=p.toString();let m=c.split(`
|
|
1602
|
-
`);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)}`)):s(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
|
|
1603
|
-
`):JSON.stringify(s)}function
|
|
1605
|
+
`);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)}`)):s(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 cP(t){let n=Sb(t).servers||{},o=[];for(let[s,r]of Object.entries(n)){if(Ns.has(s)){let d=Ns.get(s);o.push({name:s,tools:d.tools.length});continue}let i={};for(let[d,f]of Object.entries(r.env||{}))i[d]=kb(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=iP(r.command,r.args||[],{stdio:["pipe","pipe","pipe"],env:{...c,...i}})}catch(d){console.warn(`[mcp-client] Failed to spawn '${s}': ${d.message}`),o.push({name:s,tools:0,error:d.message});continue}try{await tl(u,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.4.8"}});let d=await tl(u,"tools/list",{}),f=d&&d.tools||[];Ns.set(s,{name:s,proc:u,tools:f,config:r}),o.push({name:s,tools:f.length})}catch(d){console.warn(`[mcp-client] Server '${s}' failed to initialize: ${d.message}`);try{u.kill()}catch{}o.push({name:s,tools:0,error:d.message})}}return o}async function lP(t,e,n={}){let o=Ns.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await tl(o.proc,"tools/call",{name:e,arguments:n});return s&&Array.isArray(s.content)?s.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
1606
|
+
`):JSON.stringify(s)}function uP(){let t=[];for(let[e,n]of Ns)for(let o of n.tools)t.push({type:"function",function:{name:`mcp_${e}_${o.name}`,description:`[MCP:${e}] ${o.description||""}`,parameters:o.inputSchema||{type:"object",properties:{}}}});return t}function dP(){for(let[t,e]of Ns){try{e.proc.kill()}catch{}Ns.delete(t)}}function fP(){let t=[];for(let[e,n]of Ns)t.push({name:e,connected:!0,toolCount:n.tools.length});return t}Eb.exports={loadMcpServers:cP,callMcpTool:lP,getMcpTools:uP,shutdownMcpServers:dP,listMcpServers:fP,_interpolateEnv:kb,_readConfig:Sb,_sendRequest:tl}});var Ob=X((lj,Ab)=>{var Wt=require("fs"),xr=require("path"),cj=require("os"),pP=require("readline"),{C:ye}=He(),Rb=".nex",Mf=null;function hP(t){Mf=t}function Ht(t,e=""){let n=e?` ${ye.dim}[${e}]${ye.reset}`:"",o=` ${ye.cyan}${t}${n}${ye.reset}: `;return new Promise(s=>{let r=i=>{let a=i.trim()||e;s(a)};if(Mf)Mf.question(o,r);else{let i=pP.createInterface({input:process.stdin,output:process.stdout});i.question(o,a=>{i.close(),r(a)})}})}function _r(t,e=!0){return Ht(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(o=>o.toLowerCase()!=="n"&&o.toLowerCase()!=="no")}async function Nf(t,e,n){let o=e.map((a,c)=>`${ye.dim}${c+1})${ye.reset} ${a}`).join(" ");console.log(` ${ye.cyan}${t}${ye.reset}`),console.log(` ${o}`);let s=n?e.indexOf(n)+1:1,r=await Ht("Enter number",String(s)),i=parseInt(r,10)-1;return e[Math.max(0,Math.min(i,e.length-1))]}async function mP(){let t=xr.join(process.cwd(),Rb),e=xr.join(t,"servers.json"),n={};if(Wt.existsSync(e))try{n=JSON.parse(Wt.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
1604
1607
|
${ye.bold}${ye.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${ye.reset}`),console.log(`${ye.bold}${ye.cyan}\u2551 nex-code Server Setup Wizard \u2551${ye.reset}`),console.log(`${ye.bold}${ye.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${ye.reset}
|
|
1605
1608
|
`);let o=Object.keys(n);if(o.length>0&&(console.log(`${ye.dim}Existing profiles: ${o.join(", ")}${ye.reset}`),!await _r("Add or update a server profile?",!0))){console.log(`${ye.dim}No changes made.${ye.reset}
|
|
1606
1609
|
`);return}let s={...n},r=!0;for(;r;){console.log(`
|
|
1607
|
-
${ye.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${ye.reset}`);let c=await Ht("Profile name (e.g. prod, staging, macbook)");if(!c){console.log(`${ye.red} Name is required.${ye.reset}`);continue}let u=await Ht("Host / IP address");if(!u){console.log(`${ye.red} Host is required.${ye.reset}`);continue}let d=await Ht("SSH user","root"),f=await Ht("SSH port","22"),p=parseInt(f,10)||22,m=await Ht("SSH key path (leave empty for SSH agent)",""),h=await
|
|
1610
|
+
${ye.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${ye.reset}`);let c=await Ht("Profile name (e.g. prod, staging, macbook)");if(!c){console.log(`${ye.red} Name is required.${ye.reset}`);continue}let u=await Ht("Host / IP address");if(!u){console.log(`${ye.red} Host is required.${ye.reset}`);continue}let d=await Ht("SSH user","root"),f=await Ht("SSH port","22"),p=parseInt(f,10)||22,m=await Ht("SSH key path (leave empty for SSH agent)",""),h=await Nf("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await _r("Allow sudo commands?",!0),y={host:u,user:d};p!==22&&(y.port=p),m&&(y.key=m),h!=="other"&&(y.os=h),g&&(y.sudo=!0),s[c]=y,console.log(`
|
|
1608
1611
|
${ye.green}\u2713${ye.reset} Profile "${c}" added: ${d}@${u}${p!==22?`:${p}`:""}${h!=="other"?` [${h}]`:""}`),r=await _r(`
|
|
1609
1612
|
Add another server?`,!1)}Wt.existsSync(t)||Wt.mkdirSync(t,{recursive:!0}),Wt.writeFileSync(e,JSON.stringify(s,null,2)+`
|
|
1610
1613
|
`,"utf-8"),console.log(`
|
|
@@ -1617,13 +1620,13 @@ ${ye.dim}Use /servers to list profiles, /servers ping to check connectivity.${ye
|
|
|
1617
1620
|
`)}async function Cb(t,e){let n=e||xr.join(process.cwd(),Rb),o=xr.join(n,"deploy.json"),s={};if(Wt.existsSync(o))try{s=JSON.parse(Wt.readFileSync(o,"utf-8"))}catch{}if(!t){let u=xr.join(n,"servers.json");if(Wt.existsSync(u))try{t=JSON.parse(Wt.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
1618
1621
|
${ye.bold}${ye.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${ye.reset}`),console.log(`${ye.bold}${ye.cyan}\u2551 Deploy Config Wizard \u2551${ye.reset}`),console.log(`${ye.bold}${ye.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${ye.reset}
|
|
1619
1622
|
`);let i=Object.keys(s);i.length>0&&console.log(`${ye.dim}Existing deploy configs: ${i.join(", ")}${ye.reset}`);let a={...s},c=!0;for(;c;){console.log(`
|
|
1620
|
-
${ye.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${ye.reset}`);let u=await Ht("Config name (e.g. prod, staging)");if(!u){console.log(`${ye.red} Name is required.${ye.reset}`);continue}let d;r.length>0?d=await
|
|
1623
|
+
${ye.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${ye.reset}`);let u=await Ht("Config name (e.g. prod, staging)");if(!u){console.log(`${ye.red} Name is required.${ye.reset}`);continue}let d;r.length>0?d=await Nf("Target server",r,r[0]):d=await Ht("Target server (profile name or user@host)");let f=await Nf("Deploy method",["rsync","git"],"rsync"),p="",m=[],h="";if(f==="rsync"){p=await Ht("Local path to sync (e.g. dist/ or ./build)","dist/");let k=await Ht("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env");m=k?k.split(",").map(v=>v.trim()).filter(Boolean):[]}else h=await Ht("Branch to pull (leave empty for current remote branch)","main");let g=await Ht(f==="git"?"Remote repo path (e.g. /home/deploy/my-app)":"Remote destination path (e.g. /var/www/app)");if(!g){console.log(`${ye.red} Remote path is required.${ye.reset}`);continue}let y=await Ht("Command to run on remote after deploy (leave empty to skip)",""),w=await Ht("Health check URL or remote command (leave empty to skip)",""),x={server:d,method:f,remote_path:g};f==="rsync"?(x.local_path=p,m.length>0&&(x.exclude=m)):h&&(x.branch=h),y&&(x.deploy_script=y),w&&(x.health_check=w),a[u]=x;let S=f==="git"?`${d}:${g}${h?` (${h})`:""}`:`${p.endsWith("/")?p:p+"/"} \u2192 ${d}:${g}`;console.log(`
|
|
1621
1624
|
${ye.green}\u2713${ye.reset} Deploy config "${u}": [${f}] ${S}`),y&&console.log(` ${ye.dim} Then: ${y}${ye.reset}`),w&&console.log(` ${ye.dim} Health: ${w}${ye.reset}`),c=await _r(`
|
|
1622
1625
|
Add another deploy config?`,!1)}Wt.existsSync(n)||Wt.mkdirSync(n,{recursive:!0}),Wt.writeFileSync(o,JSON.stringify(a,null,2)+`
|
|
1623
1626
|
`,"utf-8"),console.log(`
|
|
1624
1627
|
${ye.green}\u2713 Saved .nex/deploy.json (${Object.keys(a).length} config${Object.keys(a).length!==1?"s":""})${ye.reset}`),console.log(`${ye.dim}Use: deploy prod (or with explicit params)${ye.reset}
|
|
1625
|
-
`)}Ab.exports={runServerWizard:
|
|
1626
|
-
`);return`${
|
|
1628
|
+
`)}Ab.exports={runServerWizard:mP,runDeployWizard:Cb,setWizardRL:hP}});var kr=X((uj,Lb)=>{"use strict";var ol=require("os"),vr=require("path"),gt=require("fs"),gP=require("axios"),yP=require("https"),nl=vr.join(ol.homedir(),".nex-code","known-models.json"),$P="https://ollama.com/api/tags",wP=60,bP={"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 Lf(){try{if(gt.existsSync(nl))return JSON.parse(gt.readFileSync(nl,"utf-8"))}catch{}return{benchmarked:[],lastChecked:null}}function _P(t){let e=vr.dirname(nl);gt.existsSync(e)||gt.mkdirSync(e,{recursive:!0}),gt.writeFileSync(nl,JSON.stringify(t,null,2))}function xP(t){let e=Lf(),n=new Set(e.benchmarked);for(let o of t)n.add(o);e.benchmarked=[...n],e.lastChecked=new Date().toISOString(),_P(e)}async function Mb(){let t=process.env.OLLAMA_API_KEY;if(!t)throw new Error("OLLAMA_API_KEY not set");let e=new yP.Agent({keepAlive:!0});return((await gP.get($P,{headers:{Authorization:`Bearer ${t}`},timeout:15e3,httpsAgent:e})).data?.models||[]).map(o=>(o.name||o.model||"").replace(/:latest$/,"")).filter(Boolean)}async function vP(){let t=await Mb(),e=Lf(),n=new Set(e.benchmarked),o=t.filter(s=>!n.has(s));return{allCloud:t,newModels:o,store:e}}var If="<!-- nex-benchmark-start -->",sl="<!-- nex-benchmark-end -->",Nb="<!-- nex-routing-start -->",Pf="<!-- nex-routing-end -->",kP={"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 SP(t){return t?t>=25e4?"256K":t>=19e4?"200K":t>=128e3?"131K":t>=64e3?"64K":`${Math.round(t/1024)}K`:"?"}function Pb(t,e){let n=["\u{1F947}","\u{1F948}","\u{1F949}"],o=(e||new Date().toISOString()).split("T")[0],s=t.filter(r=>r.score>=wP).map((r,i)=>{let a=n[i]||"\u2014",c=SP(bP[r.model]),u=kP[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(`
|
|
1629
|
+
`);return`${If}
|
|
1627
1630
|
<!-- Updated: ${o} \u2014 run \`/benchmark --discover\` after new Ollama Cloud releases -->
|
|
1628
1631
|
|
|
1629
1632
|
| Rank | Model | Score | Avg Latency | Context | Best For |
|
|
@@ -1632,7 +1635,7 @@ ${s}
|
|
|
1632
1635
|
|
|
1633
1636
|
> Rankings are nex-code-specific: tool name accuracy, argument validity, schema compliance.
|
|
1634
1637
|
> Toolathon (Minimax SOTA) measures different task types \u2014 run \`/benchmark --discover\` after model releases.
|
|
1635
|
-
${sl}`}function
|
|
1638
|
+
${sl}`}function EP(t){let e=new Date().toISOString().split("T")[0],o=["coding","frontend","sysadmin","data","agentic","plan","verify"].filter(s=>t[s]&&t[s].score>0).map(s=>{let{model:r,score:i}=t[s];return`| ${s} | \`${r}\` | ${i}/100 |`}).join(`
|
|
1636
1639
|
`);return`${Nb}
|
|
1637
1640
|
<!-- Updated: ${e} -->
|
|
1638
1641
|
|
|
@@ -1641,22 +1644,22 @@ ${sl}`}function SP(t){let e=new Date().toISOString().split("T")[0],o=["coding","
|
|
|
1641
1644
|
| Category | Model | Score |
|
|
1642
1645
|
|---|---|---|
|
|
1643
1646
|
${o}
|
|
1644
|
-
${
|
|
1647
|
+
${Pf}`}function TP(t,e){if(!gt.existsSync(e))return!1;let n=gt.readFileSync(e,"utf-8"),o=n.indexOf(If),s=n.indexOf(sl);if(o===-1||s===-1)return!1;let r=n.slice(0,o),i=n.slice(s+sl.length),a=Pb(t);return gt.writeFileSync(e,r+a+i),!0}function RP(t){let e=vr.join(ol.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],o=gt.readFileSync(e,"utf-8"),r=o.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 o=o.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,o),{updated:!0,previousModel:r,newModel:n.model}}function CP(t){let{saveRoutingConfig:e}=Xn(),n=vr.join(ol.homedir(),".nex-code","models.env"),o=[],s=Object.entries(t).filter(([,c])=>c.score>0);if(s.length===0)return{saved:!1,envUpdated:!1,changes:[]};let r={};for(let[c,u]of s)r[c]=u.model,o.push(`${c}: ${u.model} (${u.score}/100)`);e(r);let i=!1;if(gt.existsSync(n)){let c=gt.readFileSync(n,"utf-8"),d=Object.entries({coding:"NEX_ROUTE_CODING",frontend:"NEX_ROUTE_FRONTEND",sysadmin:"NEX_ROUTE_SYSADMIN",data:"NEX_ROUTE_DATA",agentic:"NEX_ROUTE_AGENTIC"}).filter(([m])=>t[m]&&t[m].score>0).map(([m,h])=>`${h}=${t[m].model} # ${m} score: ${t[m].score}/100`).join(`
|
|
1645
1648
|
`),f="# \u2500\u2500 Task-type routing (auto-updated by /benchmark) \u2500\u2500",p="# \u2500\u2500 end routing \u2500\u2500";if(c.includes(f)){let m=c.indexOf(f),h=c.indexOf(p);h!==-1&&(c=c.slice(0,m)+`${f}
|
|
1646
1649
|
${d}
|
|
1647
1650
|
${p}`+c.slice(h+p.length))}else c+=`
|
|
1648
1651
|
${f}
|
|
1649
1652
|
${d}
|
|
1650
1653
|
${p}
|
|
1651
|
-
`;gt.writeFileSync(n,c),i=!0}let a=vr.join(process.cwd(),"README.md");if(gt.existsSync(a))try{let c=gt.readFileSync(a,"utf-8"),u=c.indexOf(Nb),d=c.indexOf(
|
|
1654
|
+
`;gt.writeFileSync(n,c),i=!0}let a=vr.join(process.cwd(),"README.md");if(gt.existsSync(a))try{let c=gt.readFileSync(a,"utf-8"),u=c.indexOf(Nb),d=c.indexOf(Pf);if(u!==-1&&d!==-1){let f=EP(t);c=c.slice(0,u)+f+c.slice(d+Pf.length),gt.writeFileSync(a,c)}}catch{}return{saved:!0,envUpdated:i,changes:o}}var AP=/thinking|reasoning|instruct|planner|orchestrat/i;function OP(t){return AP.test(t)}function MP(t){if(!t||t.length===0)return{updated:!1};let e=vr.join(ol.homedir(),".nex-code","models.env");if(!gt.existsSync(e))return{updated:!1};let n=gt.readFileSync(e,"utf-8"),o=n.match(/^NEX_ORCHESTRATOR_MODEL=(.+)$/m),s=o?o[1].trim():null,i=[...t].sort((d,f)=>f.overall-d.overall)[0],a=s?t.find(d=>d.model===s):null,c=a?a.overall:0;if(i.model===s)return{updated:!1};if(c>0&&i.overall<c*1.05)return{updated:!1};let u=`NEX_ORCHESTRATOR_MODEL=${i.model}`;return o?n=n.replace(/^NEX_ORCHESTRATOR_MODEL=.+$/m,u):n+=`
|
|
1652
1655
|
${u}
|
|
1653
|
-
`,gt.writeFileSync(e,n),{updated:!0,previousModel:s,newModel:i.model}}Lb.exports={findNewModels:xP,fetchCloudModels:Mb,loadKnownModels:Pf,markBenchmarked:_P,updateReadme:EP,updateModelsEnv:TP,updateRoutingConfig:RP,generateBenchmarkBlock:Pb,checkOrchestratorCandidate:AP,updateOrchestratorModel:OP,SENTINEL_START:Lf,SENTINEL_END:sl}});var Ls=X((uj,Xb)=>{"use strict";var{C:z}=He(),MP=Xe(),{TOOL_DEFINITIONS:Ib}=Sn(),{saveRoutingConfig:NP}=Xn();function Ps(t){let e=Array.isArray(t?.tasks)?t.tasks.flatMap(n=>typeof n=="string"?[n]:n&&typeof n=="object"?[n.title,n.task,n.description]:[]):[];return[t?.pattern,t?.query,t?.regex,t?.file_pattern,t?.include,t?.path,t?.command,t?.name,...e].filter(n=>typeof n=="string").join(" ")}function ms(t){return typeof t=="string"?t.toLowerCase():""}function PP(t,e=[]){let n=ms(t);return e.some(o=>n.includes(ms(o)))}function qf(t,e=[]){let n=ms(t);return e.every(o=>n.includes(ms(o)))}function qb(t=""){return/\b(test|jest|vitest|mocha|ava|pytest|cargo\s+test|go\s+test|rspec|phpunit|mix\s+test|npm\s+(run\s+)?test|pnpm\s+(run\s+)?test|yarn\s+test)\b/i.test(t)}function LP(t=""){return/\b(lint|eslint|prettier|ruff|flake8|rubocop|golangci-lint|tsc(?:\s|$)|npm\s+run\s+lint|pnpm\s+run\s+lint|yarn\s+lint)\b/i.test(t)}function IP(t=""){return/\b(build|compile|tsc(?:\s|$)|webpack|vite\s+build|next\s+build|npm\s+run\s+build|pnpm\s+run\s+build|yarn\s+build|cargo\s+build|go\s+build)\b/i.test(t)}function jb(t=""){return/\b(rg|grep|find|fd|ls|dir|sed|awk)\b/i.test(t)}function il(t,e=[]){return t?.action!=="create"||!Array.isArray(t.tasks)||t.tasks.length===0?!1:qf(Ps(t),e)}function Db(t,{pathIncludes:e=[],table:n="users",action:o="select",conditionTerms:s=[]}={}){if(!Ui(t)||!qf(t.path,e))return!1;let r=ms(t.content);return!r.includes(o)||!r.includes(n)?!1:s.every(i=>PP(r,i))}function jP(t,e=[]){let n=Ps(t);return qf(n,e)}function If(t,{pathIncludes:e=[],oldTexts:n=[],newTexts:o=[]}={}){if(typeof t?.path!="string"||!(e.length===0||e.some(f=>t.path.toLowerCase().includes(f.toLowerCase()))))return!1;let r=Array.isArray(t.patches)?t.patches.flatMap(f=>[f.old_text,f.new_text]).filter(f=>typeof f=="string"):[],i=typeof t.old_text=="string"?t.old_text:"",a=typeof t.new_text=="string"?t.new_text:"",c=[i,a,...r],u=n.length===0||n.some(f=>c.some(p=>p.includes(f))),d=o.length===0||o.some(f=>c.some(p=>p.includes(f)));return!u||!d?!1:i&&a?!0:Array.isArray(t.patches)&&t.patches.length>0}function Ui(t,{pathIncludes:e=[],contentIncludes:n=[]}={}){return typeof t?.path!="string"||typeof t?.content!="string"||!(e.length===0||e.some(s=>ms(t.path).includes(ms(s))))?!1:n.length===0||n.every(s=>ms(t.content).includes(ms(s)))}var Ff=[{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=>Ui(t,{pathIncludes:["nex-bench-test.txt"],contentIncludes:["benchmark run"]})},{id:"edit-file",category:"file-ops",prompt:'You already read src/config.js and confirmed it contains the exact text "debug: false". Replace that exact text with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>If(t,{pathIncludes:["config"],oldTexts:["debug: false"],newTexts:["debug: true"]})},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".js")},{id:"read-partial",category:"file-ops",prompt:"Read only lines 20 to 40 of src/index.js \u2014 I need to see that specific range.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("index")&&typeof t.line_start=="number"&&typeof t.line_end=="number"},{id:"glob-ts-defs",category:"file-ops",prompt:"Find all TypeScript type definition files (*.d.ts) anywhere in the project.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".d.ts")},{id:"write-gitignore",category:"file-ops",prompt:"Create a .gitignore file at the project root that ignores node_modules/ and dist/.",expectedTool:"write_file",validateArgs:t=>Ui(t,{pathIncludes:[".gitignore"],contentIncludes:["node_modules","dist"]})},{id:"edit-version-bump",category:"file-ops",prompt:'You already read package.json and confirmed it contains the exact snippet `"version": "1.0.0"`. Do not inspect the repo again. Update it directly to `"version": "1.1.0"`.',expectedTool:["edit_file","patch_file"],validateArgs:t=>If(t,{pathIncludes:["package.json"],oldTexts:["1.0.0",'"version": "1.0.0"','"version":"1.0.0"'],newTexts:["1.1.0",'"version": "1.1.0"','"version":"1.1.0"']})},{id:"grep-with-filter",category:"search",prompt:"Search for all calls to require() but only inside .js files in the cli/ directory.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("require")},{id:"no-tool-http-port",category:"reasoning",prompt:"What is the default port used by the HTTP protocol?",expectedTool:null,validateArgs:()=>!0},{id:"bash-node-version",category:"shell",prompt:"Check which version of Node.js is currently installed on this system.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("node")&&(t.command.includes("--version")||t.command.includes("-v"))},{id:"search-constant",category:"search",prompt:'Search for the string "DEFAULT_MODEL" across all files in the project.',expectedTool:["search_files","grep"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("DEFAULT_MODEL")},{id:"grep-function-def",category:"search",prompt:'Find where the function "callStream" is defined in the codebase.',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:t=>JSON.stringify(t).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:["bash","git_status"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("git"),!0)},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:["bash","git_status"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("git status"),!0)},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let n=e?.function?.parameters||{},o=n.required||[],s=Object.keys(n.properties||{});return o.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>s.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"You need to determine the current project version. What tool do you call first to inspect the most likely source file?",expectedTool:["read_file","glob","list_directory","search_files"],validateArgs:t=>!!(typeof t.path=="string"&&/package\.json|package|version/i.test(t.path)||typeof t.pattern=="string"&&/package\.json|package|version/i.test(t.pattern)||/package\.json|package|version/i.test(Ps(t)))},{id:"multi-step-count",category:"multi-step",prompt:"How many JavaScript files are in the cli/ directory? Count them.",expectedTool:["bash","glob","list_directory"],validateArgs:t=>!!(typeof t.command=="string"&&t.command.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli")||typeof t.path=="string"&&t.path.includes("cli"))},{id:"no-tool-reasoning",category:"reasoning",prompt:'What does the acronym "API" stand for?',expectedTool:null,validateArgs:()=>!0},{id:"frontend-find-hook",category:"frontend",prompt:"Find all files that import useState from React.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("useState")},{id:"frontend-create-component",category:"frontend",prompt:"There is no existing Button component and no need to inspect other files first. What tool call do you use first to create src/components/Button.jsx with a React functional Button component that accepts a label prop and renders a styled button element?",expectedTool:"write_file",validateArgs:t=>Ui(t,{pathIncludes:["button.","src/components"],contentIncludes:["Button","label","button"]})},{id:"frontend-edit-css",category:"frontend",prompt:"You already read src/styles.css and confirmed it contains the exact text `background-color: blue`. Change that exact value to `background-color: red`.",expectedTool:["edit_file","patch_file"],validateArgs:t=>If(t,{pathIncludes:[".css","styles"],oldTexts:["background-color: blue"],newTexts:["background-color: red"]})},{id:"frontend-glob-components",category:"frontend",prompt:"Find all JSX and TSX component files in the components/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&(t.pattern.includes(".jsx")||t.pattern.includes(".tsx")||t.pattern.includes("{jsx,tsx}"))},{id:"frontend-list-assets",category:"frontend",prompt:"List all files in the src/assets/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("assets")||typeof t.pattern=="string"&&t.pattern.includes("assets"))},{id:"sysadmin-port-check",category:"sysadmin",prompt:"Which process is currently listening on port 3000?",expectedTool:["bash","sysadmin"],validateArgs:t=>typeof t.command=="string"?t.command.includes("lsof")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("3000"):t.action==="network_status"},{id:"sysadmin-nginx-config",category:"sysadmin",prompt:"Create an nginx server block that proxies requests to localhost:3000. Save it to /etc/nginx/sites-available/myapp.",expectedTool:["write_file","bash"],validateArgs:t=>!!(t.path&&(t.path.includes("nginx")||t.path.includes("sites-available"))||t.command&&t.command.includes("nginx"))},{id:"sysadmin-service-status",category:"sysadmin",prompt:"Check the status of the nginx service and show if it is running.",expectedTool:["bash","service_manage","sysadmin"],validateArgs:t=>typeof t.command=="string"?t.command.includes("systemctl")||t.command.includes("service")||t.command.includes("nginx"):t.action==="status"&&typeof t.service=="string"?t.service.includes("nginx"):t.action==="service"&&t.service_action==="status"&&typeof t.service_name=="string"&&t.service_name.includes("nginx")},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:["bash","service_logs","sysadmin"],validateArgs:t=>typeof t.command=="string"?t.command.includes("tail")||t.command.includes("journalctl")||t.command.includes("nginx"):typeof t.service=="string"?t.service.includes("nginx"):t.action==="journalctl"&&typeof t.unit=="string"&&t.unit.includes("nginx")||t.action==="log_tail"&&typeof t.path=="string"&&/nginx|error/i.test(t.path)},{id:"sysadmin-docker-compose",category:"sysadmin",prompt:"Create a docker-compose.yml file for a Node.js application with a PostgreSQL database.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("docker-compose")&&typeof t.content=="string"},{id:"data-sql-query",category:"data",prompt:"Do not inspect the repo first. Write a SQL query to find all users who have not logged in for more than 30 days and save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:t=>Db(t,{pathIncludes:["queries","inactive-users.sql"],conditionTerms:[["last_login","last seen","last_seen","last_sign_in","last_signin","logged_in_at","login_at","last_active_at","lastactivity"],["30 day","30-day","interval '30 day'","interval '30 days'","date_sub","datetime('now', '-30 days')","current_date - 30","now() - interval","dateadd(day, -30","add_months","interval '1 month'"]]})},{id:"data-find-json-key",category:"data",prompt:'Find all JSON files in the project that contain the key "userId".',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("userId")},{id:"data-python-csv",category:"data",prompt:'There is no need to inspect the repo first. What tool call do you use first to create scripts/average_price.py with a Python script that reads data.csv and calculates the average of the "price" column?',expectedTool:"write_file",validateArgs:t=>Ui(t,{pathIncludes:["average_price.py","scripts"],contentIncludes:["data.csv","price"]})},{id:"data-find-migrations",category:"data",prompt:"Find all database migration files in this project.",expectedTool:["glob","search_files","grep"],validateArgs:t=>JSON.stringify(t).toLowerCase().includes("migrat")},{id:"data-find-schema",category:"data",prompt:"Find where the database schema or models are defined in this project.",expectedTool:["grep","glob","search_files","list_directory","bash"],validateArgs:t=>/schema|model|migration|prisma|dbml|typeorm|sequelize|orm|db|database|entity/i.test(Ps(t))},{id:"data-write-query",category:"data",prompt:"Do not inspect the repo first. Write a SQL query to find all users who registered in the last 30 days and save it to queries/recent-users.sql.",expectedTool:"write_file",validateArgs:t=>Db(t,{pathIncludes:["queries","recent-users.sql"],conditionTerms:[["created_at","registered_at","registered_on","signup_date","signed_up_at","joined_at","createdon","created_on"],["30 day","30-day","interval '30 day'","interval '30 days'","date_sub","datetime('now', '-30 days')","current_date - 30","now() - interval","dateadd(day, -30","add_months","interval '1 month'"]]})},{id:"data-read-env",category:"data",prompt:"Read the .env file to find the database connection string.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/\.env|env\./i.test(t.path)},{id:"resilience-edit-failed",category:"resilience",prompt:"Your edit_file call on server.js failed: old_string 'const PORT = 3000' was not found in the file. What do you do next to recover?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("server")},{id:"resilience-file-not-found",category:"resilience",prompt:"read_file returned 'file not found' for src/utils/helpers.js. You need to find where the helper functions are now. Use a discovery or search tool as your next step, not read_file again. What tool do you use first?",expectedTool:["glob","bash","search_files","list_directory"],validateArgs:t=>{let e=Ps(t);return/src|helper|util|helpers|\.js|find/i.test(e)}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. Use a search-oriented tool first instead of reading the whole file. What is the most efficient tool call?",expectedTool:["bash","grep","search_files","glob"],validateArgs:t=>typeof t.command=="string"&&jb(t.command)&&/authenticateuser|src\/api\.js/i.test(t.command)?!0:jP(t,["authenticateuser"])},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. Use a search or discovery tool first to find the new location. What tool do you use?",expectedTool:["glob","bash","search_files","grep","list_directory"],validateArgs:t=>{let e=Ps(t);return/config|rename|module|import|\.ts|\.js|find|src|path/i.test(e)}},{id:"resilience-bash-error-recover",category:"resilience",prompt:"The command 'npm test' failed with exit code 1. The output contains 'SyntaxError: Unexpected token' in src/parser.js:45. What is your next action?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("parser")},{id:"resilience-grep-no-match",category:"resilience",prompt:"grep returned zero matches for 'getUserById' in src/. The function exists but may have been renamed. Use a search tool to list exported function names in src/ and identify the current name. What tool call do you use first?",expectedTool:["bash","grep","search_files"],validateArgs:t=>typeof t.command=="string"?jb(t.command)&&/src|export|function|module\.exports|exports\./i.test(t.command):/getUserById|export|function|module\.exports|exports\.|src|public|def /i.test(Ps(t))},{id:"ssh-exec-log",category:"ssh",prompt:'Show the last 50 lines of /var/log/nginx/error.log on server "prod-1".',expectedTool:["ssh_exec","service_logs","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("tail")||t.command.includes("log"))&&typeof t.server=="string":typeof t.service=="string"?t.service.includes("nginx"):typeof t.server=="string"&&(t.action==="journalctl"&&typeof t.unit=="string"&&t.unit.includes("nginx")||t.action==="log_tail"&&typeof t.path=="string"&&/nginx|error/i.test(t.path))},{id:"ssh-exec-service",category:"ssh",prompt:'Restart the nginx service on server "prod-1".',expectedTool:["ssh_exec","service_manage","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("nginx")||t.command.includes("systemctl")||t.command.includes("restart"))&&typeof t.server=="string":t.action==="restart"&&typeof t.service=="string"&&t.service.includes("nginx")?!0:t.action==="service"&&t.service_action==="restart"&&typeof t.service_name=="string"&&t.service_name.includes("nginx")&&typeof t.server=="string"},{id:"ssh-exec-port",category:"ssh",prompt:'Check if port 8080 is listening on server "prod-1".',expectedTool:["ssh_exec","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("8080")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("lsof"))&&typeof t.server=="string":t.action==="network_status"&&typeof t.server=="string"},{id:"ssh-exec-processes",category:"ssh",prompt:'Show the top CPU-consuming processes on server "prod-1".',expectedTool:["ssh_exec","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("top")||t.command.includes("ps")||t.command.includes("htop"))&&typeof t.server=="string":t.action==="process_list"&&typeof t.server=="string"},{id:"git-diff-staged",category:"git",prompt:"Show all staged changes before committing.",expectedTool:["git_diff","bash"],validateArgs:t=>!!(t.staged===!0||t.staged==="true"||typeof t.command=="string"&&t.command.includes("diff"))},{id:"git-log-recent",category:"git",prompt:"Show the last 5 commit messages with their hashes.",expectedTool:["git_log","bash"],validateArgs:t=>!!(typeof t.count=="number"||typeof t.limit=="number"||typeof t.n=="number"||typeof t.command=="string"&&t.command.includes("log"))},{id:"git-status-check",category:"git",prompt:"Check if there are any uncommitted changes in the repository.",expectedTool:["git_status","bash"],validateArgs:t=>(Object.keys(t||{}).length===0||typeof t.command=="string"&&t.command.includes("status"),!0)},{id:"agentic-test-first",category:"agentic",prompt:"You need to run the full test suite first. Do not inspect files before that. If any tests fail after the run, identify the failing test file and read it to understand the issue. What is the first tool call?",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?qb(t.command):il(t,["test"])},{id:"agentic-read-then-act",category:"agentic",prompt:"Read the project README.md, find the TODO section, and list which items are completed.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("README")},{id:"agentic-build-deploy",category:"agentic",prompt:"Build the project with npm run build, then verify the output exists in the dist/ directory.",expectedTool:["bash","task_list"],validateArgs:t=>{if(typeof t.command=="string")return t.command.includes("build")||t.command.includes("npm");let e=Ps(t);return t.action==="create"&&/build|dist/i.test(e)}},{id:"agentic-spawn-parallel",category:"agentic",prompt:"Search for all TODO comments and all FIXME comments across the codebase in parallel using multiple agents.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2},{id:"agentic-multi-investigate",category:"agentic",prompt:"The app is crashing on startup. Spawn parallel agents to check: (1) recent git changes, (2) npm dependency issues, (3) the main entry file for syntax errors.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2}],Fb=[{id:"phase-plan-diagnosis",category:"phase-plan",prompt:"The server returns 500 on /api/users. The error log shows: TypeError: Cannot read property 'map' of undefined at routes/users.js:42. Read the relevant file to diagnose the root cause.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/users/i.test(t.path)},{id:"phase-plan-search",category:"phase-plan",prompt:"We're getting CORS errors in production. Search the codebase for where CORS middleware is configured.",expectedTool:["grep","search_files"],validateArgs:t=>{let e=t.pattern||t.query||t.regex||"";return/cors/i.test(e)}},{id:"phase-plan-context",category:"phase-plan",prompt:"The login page shows a blank screen after the last deploy. Check git log for recent changes that might have broken it.",expectedTool:["git_log","bash"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("log"),!0)},{id:"phase-verify-test",category:"phase-verify",prompt:"You are explicitly in the verify phase. Do not inspect files first. The first verification step is to run tests for a fix in src/utils.js. What tool call do you use first?",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?qb(t.command):il(t,["test"])},{id:"phase-verify-read",category:"phase-verify",prompt:"A patch was applied to config/database.js to fix the connection pool. Read the file to verify the changes look correct.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/database/i.test(t.path)},{id:"phase-verify-lint",category:"phase-verify",prompt:"You are explicitly in the verify phase. Do not inspect files first. The first verification step is to run linting after changes in src/components/Header.tsx. What tool call do you use first?",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?LP(t.command):il(t,["lint"])},{id:"phase-plan-git-blame",category:"phase-plan",prompt:"A production bug was introduced 2 days ago. Use git log to find commits from the last 2 days to identify what changed.",expectedTool:["git_log","bash"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("log"),!0)},{id:"phase-plan-error-trace",category:"phase-plan",prompt:"The error stack trace mentions src/middleware/auth.js line 87. Read the file around that line to understand the bug.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/auth/i.test(t.path)},{id:"phase-plan-grep-config",category:"phase-plan",prompt:"Users report the app is using wrong API keys in staging. Search for where API_KEY is loaded from environment.",expectedTool:["grep","search_files"],validateArgs:t=>{let e=t.pattern||t.query||t.regex||"";return/api.?key|env/i.test(e)}},{id:"phase-verify-build",category:"phase-verify",prompt:"You are in the verify phase. Do not inspect files first. The TypeScript source was modified, so run the build command to verify there are no compilation errors.",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?IP(t.command):il(t,["build"])},{id:"phase-verify-git-diff",category:"phase-verify",prompt:"Changes were just committed. Show the git diff of the last commit to verify only the intended files were modified.",expectedTool:["git_diff","bash"],validateArgs:t=>(t.command&&/git.*diff|diff.*HEAD/.test(t.command),!0)},{id:"phase-verify-read-config",category:"phase-verify",prompt:"The deployment config was updated. Read config/production.json to verify the changes are correct before deploying.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/config|production|deploy/i.test(t.path)}],cl=[...Ff,...Fb],jf=["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 DP(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return jf;let o=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(o)||o.length===0?jf:o.filter(s=>typeof s.score=="number"&&s.score>=60).sort((s,r)=>r.score-s.score).slice(0,12).map(s=>s.model)}catch{return jf}}var Bf=DP(),qP=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Bb=(()=>{let t=Bf.slice(0,3);return t.length>=3?t:qP})(),FP=14,rl={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},BP="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 Df(t,e){let n={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},o=[{role:"system",content:BP},{role:"user",content:t.prompt}],s=Date.now();try{let r=await MP.callChat(o,Ib,{provider:"ollama",model:e,temperature:0,timeout:9e4});n.latencyMs=Date.now()-s;let i=r.tool_calls||[];if(t.expectedTool===null){let a=i.length===0;n.producedToolCall=a,n.correctTool=a,n.validArgs=!0,n.schemaCompliant=!0}else if(i.length>0){n.producedToolCall=!0;let a=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool],c=-1,u=i[0].function?.name||"unknown",d=!1,f=!1,p=!1;for(let m of i){let h=m.function?.name||"unknown",g=m.function?.arguments||{},y=a.includes(h),w=!1,x=!1,S=0;if(y){let k=Ib.find(v=>v.function?.name===h);if(w=!!t.validateArgs(g,k),k){let v=k.function?.parameters||{},C=v.required||[],q=Object.keys(v.properties||{});x=C.every(D=>g[D]!==void 0)&&Object.keys(g).every(D=>q.includes(D))}S=(y?2:0)+(w?1:0)+(x?.5:0)}S>c&&(c=S,u=h,d=y,f=w,p=x)}n.toolCalled=d?u:i[0].function?.name||"unknown",n.correctTool=d,n.validArgs=f,n.schemaCompliant=p}}catch(r){n.latencyMs=Date.now()-s,n.error=r.message.slice(0,120)}return n}function Sr(t){return t.error?0:((t.producedToolCall?rl.producedToolCall:0)+(t.correctTool?rl.correctTool:0)+(t.validArgs?rl.validArgs:0)+(t.schemaCompliant?rl.schemaCompliant:0))*100}var Ub={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 Uf(t){return Object.entries(t).map(([e,n])=>{let o=n.map(Sr),s=o.reduce((a,c)=>a+c,0)/o.length,r=a=>Math.round(n.filter(a).length/n.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=n.filter(d=>Ub[d.category]===a);if(c.length===0)continue;let u=c.map(Sr).reduce((d,f)=>d+f,0)/c.length;i[a]=Math.round(u*10)/10}return{model:e,score:Math.round(s*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(n.reduce((a,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 Wb(t){return Hb(t)}function Hb(t){let e={};for(let r of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let i=t.filter(p=>p.categoryScores[r]!==void 0&&p.score>=65).sort((p,m)=>m.categoryScores[r]-p.categoryScores[r]);if(i.length===0||(i[0]?.results||[]).filter(p=>Ub[p.category]===r).length<4)continue;let u=i[0],f=i.filter(p=>u.categoryScores[r]-p.categoryScores[r]<=5).sort((p,m)=>p.avgLatency-m.avgLatency)[0];e[r]={model:f.model,score:f.categoryScores[r],avgLatency:f.avgLatency}}return e}function Gb(t,e){let n=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,o=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],s=o.reduce((d,f)=>d+f.width+1,0)+1,r="\u2500".repeat(s);console.log(`
|
|
1656
|
+
`,gt.writeFileSync(e,n),{updated:!0,previousModel:s,newModel:i.model}}Lb.exports={findNewModels:vP,fetchCloudModels:Mb,loadKnownModels:Lf,markBenchmarked:xP,updateReadme:TP,updateModelsEnv:RP,updateRoutingConfig:CP,generateBenchmarkBlock:Pb,checkOrchestratorCandidate:OP,updateOrchestratorModel:MP,SENTINEL_START:If,SENTINEL_END:sl}});var Ls=X((dj,Xb)=>{"use strict";var{C:z}=He(),NP=Xe(),{TOOL_DEFINITIONS:Ib}=Sn(),{saveRoutingConfig:PP}=Xn();function Ps(t){let e=Array.isArray(t?.tasks)?t.tasks.flatMap(n=>typeof n=="string"?[n]:n&&typeof n=="object"?[n.title,n.task,n.description]:[]):[];return[t?.pattern,t?.query,t?.regex,t?.file_pattern,t?.include,t?.path,t?.command,t?.name,...e].filter(n=>typeof n=="string").join(" ")}function ms(t){return typeof t=="string"?t.toLowerCase():""}function LP(t,e=[]){let n=ms(t);return e.some(o=>n.includes(ms(o)))}function Ff(t,e=[]){let n=ms(t);return e.every(o=>n.includes(ms(o)))}function qb(t=""){return/\b(test|jest|vitest|mocha|ava|pytest|cargo\s+test|go\s+test|rspec|phpunit|mix\s+test|npm\s+(run\s+)?test|pnpm\s+(run\s+)?test|yarn\s+test)\b/i.test(t)}function IP(t=""){return/\b(lint|eslint|prettier|ruff|flake8|rubocop|golangci-lint|tsc(?:\s|$)|npm\s+run\s+lint|pnpm\s+run\s+lint|yarn\s+lint)\b/i.test(t)}function jP(t=""){return/\b(build|compile|tsc(?:\s|$)|webpack|vite\s+build|next\s+build|npm\s+run\s+build|pnpm\s+run\s+build|yarn\s+build|cargo\s+build|go\s+build)\b/i.test(t)}function jb(t=""){return/\b(rg|grep|find|fd|ls|dir|sed|awk)\b/i.test(t)}function il(t,e=[]){return t?.action!=="create"||!Array.isArray(t.tasks)||t.tasks.length===0?!1:Ff(Ps(t),e)}function Db(t,{pathIncludes:e=[],table:n="users",action:o="select",conditionTerms:s=[]}={}){if(!Ui(t)||!Ff(t.path,e))return!1;let r=ms(t.content);return!r.includes(o)||!r.includes(n)?!1:s.every(i=>LP(r,i))}function DP(t,e=[]){let n=Ps(t);return Ff(n,e)}function jf(t,{pathIncludes:e=[],oldTexts:n=[],newTexts:o=[]}={}){if(typeof t?.path!="string"||!(e.length===0||e.some(f=>t.path.toLowerCase().includes(f.toLowerCase()))))return!1;let r=Array.isArray(t.patches)?t.patches.flatMap(f=>[f.old_text,f.new_text]).filter(f=>typeof f=="string"):[],i=typeof t.old_text=="string"?t.old_text:"",a=typeof t.new_text=="string"?t.new_text:"",c=[i,a,...r],u=n.length===0||n.some(f=>c.some(p=>p.includes(f))),d=o.length===0||o.some(f=>c.some(p=>p.includes(f)));return!u||!d?!1:i&&a?!0:Array.isArray(t.patches)&&t.patches.length>0}function Ui(t,{pathIncludes:e=[],contentIncludes:n=[]}={}){return typeof t?.path!="string"||typeof t?.content!="string"||!(e.length===0||e.some(s=>ms(t.path).includes(ms(s))))?!1:n.length===0||n.every(s=>ms(t.content).includes(ms(s)))}var Bf=[{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=>Ui(t,{pathIncludes:["nex-bench-test.txt"],contentIncludes:["benchmark run"]})},{id:"edit-file",category:"file-ops",prompt:'You already read src/config.js and confirmed it contains the exact text "debug: false". Replace that exact text with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>jf(t,{pathIncludes:["config"],oldTexts:["debug: false"],newTexts:["debug: true"]})},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".js")},{id:"read-partial",category:"file-ops",prompt:"Read only lines 20 to 40 of src/index.js \u2014 I need to see that specific range.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("index")&&typeof t.line_start=="number"&&typeof t.line_end=="number"},{id:"glob-ts-defs",category:"file-ops",prompt:"Find all TypeScript type definition files (*.d.ts) anywhere in the project.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".d.ts")},{id:"write-gitignore",category:"file-ops",prompt:"Create a .gitignore file at the project root that ignores node_modules/ and dist/.",expectedTool:"write_file",validateArgs:t=>Ui(t,{pathIncludes:[".gitignore"],contentIncludes:["node_modules","dist"]})},{id:"edit-version-bump",category:"file-ops",prompt:'You already read package.json and confirmed it contains the exact snippet `"version": "1.0.0"`. Do not inspect the repo again. Update it directly to `"version": "1.1.0"`.',expectedTool:["edit_file","patch_file"],validateArgs:t=>jf(t,{pathIncludes:["package.json"],oldTexts:["1.0.0",'"version": "1.0.0"','"version":"1.0.0"'],newTexts:["1.1.0",'"version": "1.1.0"','"version":"1.1.0"']})},{id:"grep-with-filter",category:"search",prompt:"Search for all calls to require() but only inside .js files in the cli/ directory.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("require")},{id:"no-tool-http-port",category:"reasoning",prompt:"What is the default port used by the HTTP protocol?",expectedTool:null,validateArgs:()=>!0},{id:"bash-node-version",category:"shell",prompt:"Check which version of Node.js is currently installed on this system.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("node")&&(t.command.includes("--version")||t.command.includes("-v"))},{id:"search-constant",category:"search",prompt:'Search for the string "DEFAULT_MODEL" across all files in the project.',expectedTool:["search_files","grep"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("DEFAULT_MODEL")},{id:"grep-function-def",category:"search",prompt:'Find where the function "callStream" is defined in the codebase.',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:t=>JSON.stringify(t).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:["bash","git_status"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("git"),!0)},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:["bash","git_status"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("git status"),!0)},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let n=e?.function?.parameters||{},o=n.required||[],s=Object.keys(n.properties||{});return o.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>s.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"You need to determine the current project version. What tool do you call first to inspect the most likely source file?",expectedTool:["read_file","glob","list_directory","search_files"],validateArgs:t=>!!(typeof t.path=="string"&&/package\.json|package|version/i.test(t.path)||typeof t.pattern=="string"&&/package\.json|package|version/i.test(t.pattern)||/package\.json|package|version/i.test(Ps(t)))},{id:"multi-step-count",category:"multi-step",prompt:"How many JavaScript files are in the cli/ directory? Count them.",expectedTool:["bash","glob","list_directory"],validateArgs:t=>!!(typeof t.command=="string"&&t.command.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli")||typeof t.path=="string"&&t.path.includes("cli"))},{id:"no-tool-reasoning",category:"reasoning",prompt:'What does the acronym "API" stand for?',expectedTool:null,validateArgs:()=>!0},{id:"frontend-find-hook",category:"frontend",prompt:"Find all files that import useState from React.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("useState")},{id:"frontend-create-component",category:"frontend",prompt:"There is no existing Button component and no need to inspect other files first. What tool call do you use first to create src/components/Button.jsx with a React functional Button component that accepts a label prop and renders a styled button element?",expectedTool:"write_file",validateArgs:t=>Ui(t,{pathIncludes:["button.","src/components"],contentIncludes:["Button","label","button"]})},{id:"frontend-edit-css",category:"frontend",prompt:"You already read src/styles.css and confirmed it contains the exact text `background-color: blue`. Change that exact value to `background-color: red`.",expectedTool:["edit_file","patch_file"],validateArgs:t=>jf(t,{pathIncludes:[".css","styles"],oldTexts:["background-color: blue"],newTexts:["background-color: red"]})},{id:"frontend-glob-components",category:"frontend",prompt:"Find all JSX and TSX component files in the components/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&(t.pattern.includes(".jsx")||t.pattern.includes(".tsx")||t.pattern.includes("{jsx,tsx}"))},{id:"frontend-list-assets",category:"frontend",prompt:"List all files in the src/assets/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("assets")||typeof t.pattern=="string"&&t.pattern.includes("assets"))},{id:"sysadmin-port-check",category:"sysadmin",prompt:"Which process is currently listening on port 3000?",expectedTool:["bash","sysadmin"],validateArgs:t=>typeof t.command=="string"?t.command.includes("lsof")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("3000"):t.action==="network_status"},{id:"sysadmin-nginx-config",category:"sysadmin",prompt:"Create an nginx server block that proxies requests to localhost:3000. Save it to /etc/nginx/sites-available/myapp.",expectedTool:["write_file","bash"],validateArgs:t=>!!(t.path&&(t.path.includes("nginx")||t.path.includes("sites-available"))||t.command&&t.command.includes("nginx"))},{id:"sysadmin-service-status",category:"sysadmin",prompt:"Check the status of the nginx service and show if it is running.",expectedTool:["bash","service_manage","sysadmin"],validateArgs:t=>typeof t.command=="string"?t.command.includes("systemctl")||t.command.includes("service")||t.command.includes("nginx"):t.action==="status"&&typeof t.service=="string"?t.service.includes("nginx"):t.action==="service"&&t.service_action==="status"&&typeof t.service_name=="string"&&t.service_name.includes("nginx")},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:["bash","service_logs","sysadmin"],validateArgs:t=>typeof t.command=="string"?t.command.includes("tail")||t.command.includes("journalctl")||t.command.includes("nginx"):typeof t.service=="string"?t.service.includes("nginx"):t.action==="journalctl"&&typeof t.unit=="string"&&t.unit.includes("nginx")||t.action==="log_tail"&&typeof t.path=="string"&&/nginx|error/i.test(t.path)},{id:"sysadmin-docker-compose",category:"sysadmin",prompt:"Create a docker-compose.yml file for a Node.js application with a PostgreSQL database.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("docker-compose")&&typeof t.content=="string"},{id:"data-sql-query",category:"data",prompt:"Do not inspect the repo first. Write a SQL query to find all users who have not logged in for more than 30 days and save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:t=>Db(t,{pathIncludes:["queries","inactive-users.sql"],conditionTerms:[["last_login","last seen","last_seen","last_sign_in","last_signin","logged_in_at","login_at","last_active_at","lastactivity"],["30 day","30-day","interval '30 day'","interval '30 days'","date_sub","datetime('now', '-30 days')","current_date - 30","now() - interval","dateadd(day, -30","add_months","interval '1 month'"]]})},{id:"data-find-json-key",category:"data",prompt:'Find all JSON files in the project that contain the key "userId".',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("userId")},{id:"data-python-csv",category:"data",prompt:'There is no need to inspect the repo first. What tool call do you use first to create scripts/average_price.py with a Python script that reads data.csv and calculates the average of the "price" column?',expectedTool:"write_file",validateArgs:t=>Ui(t,{pathIncludes:["average_price.py","scripts"],contentIncludes:["data.csv","price"]})},{id:"data-find-migrations",category:"data",prompt:"Find all database migration files in this project.",expectedTool:["glob","search_files","grep"],validateArgs:t=>JSON.stringify(t).toLowerCase().includes("migrat")},{id:"data-find-schema",category:"data",prompt:"Find where the database schema or models are defined in this project.",expectedTool:["grep","glob","search_files","list_directory","bash"],validateArgs:t=>/schema|model|migration|prisma|dbml|typeorm|sequelize|orm|db|database|entity/i.test(Ps(t))},{id:"data-write-query",category:"data",prompt:"Do not inspect the repo first. Write a SQL query to find all users who registered in the last 30 days and save it to queries/recent-users.sql.",expectedTool:"write_file",validateArgs:t=>Db(t,{pathIncludes:["queries","recent-users.sql"],conditionTerms:[["created_at","registered_at","registered_on","signup_date","signed_up_at","joined_at","createdon","created_on"],["30 day","30-day","interval '30 day'","interval '30 days'","date_sub","datetime('now', '-30 days')","current_date - 30","now() - interval","dateadd(day, -30","add_months","interval '1 month'"]]})},{id:"data-read-env",category:"data",prompt:"Read the .env file to find the database connection string.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/\.env|env\./i.test(t.path)},{id:"resilience-edit-failed",category:"resilience",prompt:"Your edit_file call on server.js failed: old_string 'const PORT = 3000' was not found in the file. What do you do next to recover?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("server")},{id:"resilience-file-not-found",category:"resilience",prompt:"read_file returned 'file not found' for src/utils/helpers.js. You need to find where the helper functions are now. Use a discovery or search tool as your next step, not read_file again. What tool do you use first?",expectedTool:["glob","bash","search_files","list_directory"],validateArgs:t=>{let e=Ps(t);return/src|helper|util|helpers|\.js|find/i.test(e)}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. Use a search-oriented tool first instead of reading the whole file. What is the most efficient tool call?",expectedTool:["bash","grep","search_files","glob"],validateArgs:t=>typeof t.command=="string"&&jb(t.command)&&/authenticateuser|src\/api\.js/i.test(t.command)?!0:DP(t,["authenticateuser"])},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. Use a search or discovery tool first to find the new location. What tool do you use?",expectedTool:["glob","bash","search_files","grep","list_directory"],validateArgs:t=>{let e=Ps(t);return/config|rename|module|import|\.ts|\.js|find|src|path/i.test(e)}},{id:"resilience-bash-error-recover",category:"resilience",prompt:"The command 'npm test' failed with exit code 1. The output contains 'SyntaxError: Unexpected token' in src/parser.js:45. What is your next action?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("parser")},{id:"resilience-grep-no-match",category:"resilience",prompt:"grep returned zero matches for 'getUserById' in src/. The function exists but may have been renamed. Use a search tool to list exported function names in src/ and identify the current name. What tool call do you use first?",expectedTool:["bash","grep","search_files"],validateArgs:t=>typeof t.command=="string"?jb(t.command)&&/src|export|function|module\.exports|exports\./i.test(t.command):/getUserById|export|function|module\.exports|exports\.|src|public|def /i.test(Ps(t))},{id:"ssh-exec-log",category:"ssh",prompt:'Show the last 50 lines of /var/log/nginx/error.log on server "prod-1".',expectedTool:["ssh_exec","service_logs","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("tail")||t.command.includes("log"))&&typeof t.server=="string":typeof t.service=="string"?t.service.includes("nginx"):typeof t.server=="string"&&(t.action==="journalctl"&&typeof t.unit=="string"&&t.unit.includes("nginx")||t.action==="log_tail"&&typeof t.path=="string"&&/nginx|error/i.test(t.path))},{id:"ssh-exec-service",category:"ssh",prompt:'Restart the nginx service on server "prod-1".',expectedTool:["ssh_exec","service_manage","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("nginx")||t.command.includes("systemctl")||t.command.includes("restart"))&&typeof t.server=="string":t.action==="restart"&&typeof t.service=="string"&&t.service.includes("nginx")?!0:t.action==="service"&&t.service_action==="restart"&&typeof t.service_name=="string"&&t.service_name.includes("nginx")&&typeof t.server=="string"},{id:"ssh-exec-port",category:"ssh",prompt:'Check if port 8080 is listening on server "prod-1".',expectedTool:["ssh_exec","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("8080")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("lsof"))&&typeof t.server=="string":t.action==="network_status"&&typeof t.server=="string"},{id:"ssh-exec-processes",category:"ssh",prompt:'Show the top CPU-consuming processes on server "prod-1".',expectedTool:["ssh_exec","sysadmin"],validateArgs:t=>typeof t.command=="string"?(t.command.includes("top")||t.command.includes("ps")||t.command.includes("htop"))&&typeof t.server=="string":t.action==="process_list"&&typeof t.server=="string"},{id:"git-diff-staged",category:"git",prompt:"Show all staged changes before committing.",expectedTool:["git_diff","bash"],validateArgs:t=>!!(t.staged===!0||t.staged==="true"||typeof t.command=="string"&&t.command.includes("diff"))},{id:"git-log-recent",category:"git",prompt:"Show the last 5 commit messages with their hashes.",expectedTool:["git_log","bash"],validateArgs:t=>!!(typeof t.count=="number"||typeof t.limit=="number"||typeof t.n=="number"||typeof t.command=="string"&&t.command.includes("log"))},{id:"git-status-check",category:"git",prompt:"Check if there are any uncommitted changes in the repository.",expectedTool:["git_status","bash"],validateArgs:t=>(Object.keys(t||{}).length===0||typeof t.command=="string"&&t.command.includes("status"),!0)},{id:"agentic-test-first",category:"agentic",prompt:"You need to run the full test suite first. Do not inspect files before that. If any tests fail after the run, identify the failing test file and read it to understand the issue. What is the first tool call?",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?qb(t.command):il(t,["test"])},{id:"agentic-read-then-act",category:"agentic",prompt:"Read the project README.md, find the TODO section, and list which items are completed.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("README")},{id:"agentic-build-deploy",category:"agentic",prompt:"Build the project with npm run build, then verify the output exists in the dist/ directory.",expectedTool:["bash","task_list"],validateArgs:t=>{if(typeof t.command=="string")return t.command.includes("build")||t.command.includes("npm");let e=Ps(t);return t.action==="create"&&/build|dist/i.test(e)}},{id:"agentic-spawn-parallel",category:"agentic",prompt:"Search for all TODO comments and all FIXME comments across the codebase in parallel using multiple agents.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2},{id:"agentic-multi-investigate",category:"agentic",prompt:"The app is crashing on startup. Spawn parallel agents to check: (1) recent git changes, (2) npm dependency issues, (3) the main entry file for syntax errors.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2}],Fb=[{id:"phase-plan-diagnosis",category:"phase-plan",prompt:"The server returns 500 on /api/users. The error log shows: TypeError: Cannot read property 'map' of undefined at routes/users.js:42. Read the relevant file to diagnose the root cause.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/users/i.test(t.path)},{id:"phase-plan-search",category:"phase-plan",prompt:"We're getting CORS errors in production. Search the codebase for where CORS middleware is configured.",expectedTool:["grep","search_files"],validateArgs:t=>{let e=t.pattern||t.query||t.regex||"";return/cors/i.test(e)}},{id:"phase-plan-context",category:"phase-plan",prompt:"The login page shows a blank screen after the last deploy. Check git log for recent changes that might have broken it.",expectedTool:["git_log","bash"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("log"),!0)},{id:"phase-verify-test",category:"phase-verify",prompt:"You are explicitly in the verify phase. Do not inspect files first. The first verification step is to run tests for a fix in src/utils.js. What tool call do you use first?",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?qb(t.command):il(t,["test"])},{id:"phase-verify-read",category:"phase-verify",prompt:"A patch was applied to config/database.js to fix the connection pool. Read the file to verify the changes look correct.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/database/i.test(t.path)},{id:"phase-verify-lint",category:"phase-verify",prompt:"You are explicitly in the verify phase. Do not inspect files first. The first verification step is to run linting after changes in src/components/Header.tsx. What tool call do you use first?",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?IP(t.command):il(t,["lint"])},{id:"phase-plan-git-blame",category:"phase-plan",prompt:"A production bug was introduced 2 days ago. Use git log to find commits from the last 2 days to identify what changed.",expectedTool:["git_log","bash"],validateArgs:t=>(typeof t.command=="string"&&t.command.includes("log"),!0)},{id:"phase-plan-error-trace",category:"phase-plan",prompt:"The error stack trace mentions src/middleware/auth.js line 87. Read the file around that line to understand the bug.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/auth/i.test(t.path)},{id:"phase-plan-grep-config",category:"phase-plan",prompt:"Users report the app is using wrong API keys in staging. Search for where API_KEY is loaded from environment.",expectedTool:["grep","search_files"],validateArgs:t=>{let e=t.pattern||t.query||t.regex||"";return/api.?key|env/i.test(e)}},{id:"phase-verify-build",category:"phase-verify",prompt:"You are in the verify phase. Do not inspect files first. The TypeScript source was modified, so run the build command to verify there are no compilation errors.",expectedTool:["bash","task_list"],validateArgs:t=>typeof t.command=="string"?jP(t.command):il(t,["build"])},{id:"phase-verify-git-diff",category:"phase-verify",prompt:"Changes were just committed. Show the git diff of the last commit to verify only the intended files were modified.",expectedTool:["git_diff","bash"],validateArgs:t=>(t.command&&/git.*diff|diff.*HEAD/.test(t.command),!0)},{id:"phase-verify-read-config",category:"phase-verify",prompt:"The deployment config was updated. Read config/production.json to verify the changes are correct before deploying.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/config|production|deploy/i.test(t.path)}],cl=[...Bf,...Fb],Df=["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 qP(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return Df;let o=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(o)||o.length===0?Df:o.filter(s=>typeof s.score=="number"&&s.score>=60).sort((s,r)=>r.score-s.score).slice(0,12).map(s=>s.model)}catch{return Df}}var Uf=qP(),FP=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Bb=(()=>{let t=Uf.slice(0,3);return t.length>=3?t:FP})(),BP=14,rl={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},UP="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 qf(t,e){let n={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},o=[{role:"system",content:UP},{role:"user",content:t.prompt}],s=Date.now();try{let r=await NP.callChat(o,Ib,{provider:"ollama",model:e,temperature:0,timeout:9e4});n.latencyMs=Date.now()-s;let i=r.tool_calls||[];if(t.expectedTool===null){let a=i.length===0;n.producedToolCall=a,n.correctTool=a,n.validArgs=!0,n.schemaCompliant=!0}else if(i.length>0){n.producedToolCall=!0;let a=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool],c=-1,u=i[0].function?.name||"unknown",d=!1,f=!1,p=!1;for(let m of i){let h=m.function?.name||"unknown",g=m.function?.arguments||{},y=a.includes(h),w=!1,x=!1,S=0;if(y){let k=Ib.find(v=>v.function?.name===h);if(w=!!t.validateArgs(g,k),k){let v=k.function?.parameters||{},C=v.required||[],q=Object.keys(v.properties||{});x=C.every(D=>g[D]!==void 0)&&Object.keys(g).every(D=>q.includes(D))}S=(y?2:0)+(w?1:0)+(x?.5:0)}S>c&&(c=S,u=h,d=y,f=w,p=x)}n.toolCalled=d?u:i[0].function?.name||"unknown",n.correctTool=d,n.validArgs=f,n.schemaCompliant=p}}catch(r){n.latencyMs=Date.now()-s,n.error=r.message.slice(0,120)}return n}function Sr(t){return t.error?0:((t.producedToolCall?rl.producedToolCall:0)+(t.correctTool?rl.correctTool:0)+(t.validArgs?rl.validArgs:0)+(t.schemaCompliant?rl.schemaCompliant:0))*100}var Ub={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 Wf(t){return Object.entries(t).map(([e,n])=>{let o=n.map(Sr),s=o.reduce((a,c)=>a+c,0)/o.length,r=a=>Math.round(n.filter(a).length/n.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=n.filter(d=>Ub[d.category]===a);if(c.length===0)continue;let u=c.map(Sr).reduce((d,f)=>d+f,0)/c.length;i[a]=Math.round(u*10)/10}return{model:e,score:Math.round(s*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(n.reduce((a,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 Wb(t){return Hb(t)}function Hb(t){let e={};for(let r of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let i=t.filter(p=>p.categoryScores[r]!==void 0&&p.score>=65).sort((p,m)=>m.categoryScores[r]-p.categoryScores[r]);if(i.length===0||(i[0]?.results||[]).filter(p=>Ub[p.category]===r).length<4)continue;let u=i[0],f=i.filter(p=>u.categoryScores[r]-p.categoryScores[r]<=5).sort((p,m)=>p.avgLatency-m.avgLatency)[0];e[r]={model:f.model,score:f.categoryScores[r],avgLatency:f.avgLatency}}return e}function Gb(t,e){let n=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,o=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],s=o.reduce((d,f)=>d+f.width+1,0)+1,r="\u2500".repeat(s);console.log(`
|
|
1654
1657
|
${z.bold}${n}${z.reset}`),console.log(r);let i=o.map(d=>d.label.padEnd(d.width)).join(" ");if(console.log(`${z.dim}${i}${z.reset}`),console.log(r),t.forEach((d,f)=>{let p=String(f+1).padEnd(o[0].width),m=d.model.slice(0,o[1].width).padEnd(o[1].width),h=String(d.score).padEnd(o[2].width),g=`${d.toolCallRate}%`.padEnd(o[3].width),y=`${d.correctRate}%`.padEnd(o[4].width),w=`${d.validArgsRate}%`.padEnd(o[5].width),x=`${d.schemaRate}%`.padEnd(o[6].width),S=`${(d.avgLatency/1e3).toFixed(1)}s`.padEnd(o[7].width),k=d.errorCount>0?`${z.red}${d.errorCount}${z.reset}`:`${z.dim}0${z.reset}`,v=d.score>=80?z.green:d.score>=60?z.yellow:z.red,C=f===0?`${z.yellow}${p}${z.reset}`:`${z.dim}${p}${z.reset}`;console.log(`${C} ${v}${m}${z.reset} ${z.bold}${v}${h}${z.reset} ${g} ${y} ${w} ${x} ${z.dim}${S}${z.reset} ${k}`)}),console.log(r),t.length>0){let d=t[0];if(console.log(`
|
|
1655
1658
|
${z.bold}${z.green}Winner: ${d.model}${z.reset} score ${d.score}/100`),t.length>1){let f=(d.score-t[1].score).toFixed(1);console.log(`${z.dim}+${f} pts over ${t[1].model}${z.reset}`)}}let a=t.filter(d=>d.results.some(f=>!f.error&&(!f.correctTool||!f.validArgs)));if(a.length>0){console.log(`${z.bold}Failing tasks:${z.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`${z.dim}${h.taskId}${z.reset} ${z.red}\u2192${g}${z.reset}`}return`${z.dim}${h.taskId}${z.reset} ${z.yellow}bad-args${z.reset}`});console.log(` ${z.dim}${p.padEnd(22)}${z.reset} ${m.join(" ")}`)}console.log()}if(t.length>=3){let d={},f={};for(let h of t)for(let g of h.results)g.error||(f[g.taskId]=(f[g.taskId]||0)+1,(!g.correctTool||!g.validArgs)&&(d[g.taskId]=(d[g.taskId]||0)+1));let p=Math.ceil(t.length*.5),m=Object.entries(d).filter(([h,g])=>g>=p&&f[h]>=3).sort((h,g)=>g[1]-h[1]);if(m.length>0){console.log(`
|
|
1656
1659
|
${z.bold}Systemic failures${z.reset} ${z.dim}(>50% of models fail \u2014 may indicate benchmark design issues)${z.reset}`);for(let[h,g]of m){let y=f[h],w=Math.round(g/y*100),x=w>=80?z.red:z.yellow;console.log(` ${x}${w}%${z.reset} ${z.dim}fail${z.reset} ${h}`)}console.log()}}let c=["coding","frontend","sysadmin","data","agentic","plan","verify"];if(t.some(d=>Object.keys(d.categoryScores).length>1)){console.log(`
|
|
1657
|
-
${z.bold}Best model per task type:${z.reset}`);let d=Hb(t);for(let f of c){let p=d[f];if(!p)continue;let m=p.score,h=m>=80?z.green:m>=60?z.yellow:z.red,g=t.filter(w=>w.categoryScores[f]!==void 0).sort((w,x)=>x.categoryScores[f]-w.categoryScores[f])[0],y=g&&g.model!==p.model?`${z.dim} raw leader: ${g.model} (${g.categoryScores[f]}/100)${z.reset}`:"";console.log(` ${z.dim}${f.padEnd(10)}${z.reset} ${h}${p.model}${z.reset} ${z.dim}${m}/100${z.reset}${y}`)}console.log(`${z.dim} Winners use the same conservative routing criteria as auto-update (overall-score floor plus latency tiebreak band).${z.reset}`)}console.log()}function Yb(t){if(!(!t||t.length<2))try{let e=Wb(t),{loadRoutingConfig:n}=Xn(),o=n(),s={...o},r=[],i=new Set(["plan","verify"]);for(let[a,{model:c,score:u}]of Object.entries(e)){let d=i.has(a),f=d?o.phases&&o.phases[a]:o[a];f&&f!==c&&!t.find(m=>m.model===f)||(d?(s.phases||(s.phases={}),s.phases[a]!==c&&(s.phases[a]=c,r.push(`phase:${a}\u2192${c}`))):s[a]!==c&&(s[a]=c,r.push(`${a}\u2192${c}`)))}r.length>0&&(
|
|
1660
|
+
${z.bold}Best model per task type:${z.reset}`);let d=Hb(t);for(let f of c){let p=d[f];if(!p)continue;let m=p.score,h=m>=80?z.green:m>=60?z.yellow:z.red,g=t.filter(w=>w.categoryScores[f]!==void 0).sort((w,x)=>x.categoryScores[f]-w.categoryScores[f])[0],y=g&&g.model!==p.model?`${z.dim} raw leader: ${g.model} (${g.categoryScores[f]}/100)${z.reset}`:"";console.log(` ${z.dim}${f.padEnd(10)}${z.reset} ${h}${p.model}${z.reset} ${z.dim}${m}/100${z.reset}${y}`)}console.log(`${z.dim} Winners use the same conservative routing criteria as auto-update (overall-score floor plus latency tiebreak band).${z.reset}`)}console.log()}function Yb(t){if(!(!t||t.length<2))try{let e=Wb(t),{loadRoutingConfig:n}=Xn(),o=n(),s={...o},r=[],i=new Set(["plan","verify"]);for(let[a,{model:c,score:u}]of Object.entries(e)){let d=i.has(a),f=d?o.phases&&o.phases[a]:o[a];f&&f!==c&&!t.find(m=>m.model===f)||(d?(s.phases||(s.phases={}),s.phases[a]!==c&&(s.phases[a]=c,r.push(`phase:${a}\u2192${c}`))):s[a]!==c&&(s[a]=c,r.push(`${a}\u2192${c}`)))}r.length>0&&(PP(s),console.log(`
|
|
1658
1661
|
${z.dim} Routing updated: ${r.join(", ")}${z.reset}`),console.log(`
|
|
1659
|
-
${z.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${z.reset}`))}catch{}}async function
|
|
1662
|
+
${z.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${z.reset}`))}catch{}}async function WP({models:t,quick:e=!1,onProgress:n,parallelModels:o=1}={}){let s=e?Bf.slice(0,BP):cl,r=t?.length>0?t:e?Bb:Uf,i={};for(let c of r)i[c]=[];if(o<=1)for(let c of r)for(let u of s){n?.({model:c,task:u.id,done:!1});let d=await qf(u,c);i[c].push(d),n?.({model:c,task:u.id,done:!0,score:Sr(d),error:d.error})}else{let c=Math.min(o,r.length),u=[...r],d=Array.from({length:c},async()=>{for(;u.length>0;){let f=u.shift();if(!f)break;for(let p of s){n?.({model:f,task:p.id,done:!1});let m=await qf(p,f);i[f].push(m),n?.({model:f,task:p.id,done:!0,score:Sr(m),error:m.error})}}});await Promise.all(d)}let a=Wf(i);return Gb(a,s.length),Yb(a),a}async function HP({newModels:t,existingRanking:e=[],onProgress:n}={}){if(!t||t.length===0)return e;let o={};for(let i of t){o[i]=[];for(let a of cl){n?.({model:i,task:a.id,done:!1});let c=await qf(a,i);o[i].push(c),n?.({model:i,task:a.id,done:!0,score:Sr(c),error:c.error})}}let r=[...Wf(o)];for(let i of e)r.find(a=>a.model===i.model)||r.push(i);return r.sort((i,a)=>a.score-i.score),Gb(r,cl.length),Yb(r),r}var al=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function zb(t){let e=require("fs"),o=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(o))return console.log(`${z.yellow}No scenarios configured.${z.reset} Create ${z.dim}.nex/benchmark-config.json${z.reset} to define your benchmark scenarios.
|
|
1660
1663
|
Example:
|
|
1661
1664
|
{
|
|
1662
1665
|
"scenarios": [
|
|
@@ -1671,31 +1674,31 @@ ${z.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will
|
|
|
1671
1674
|
}
|
|
1672
1675
|
`),al;try{let s=JSON.parse(e.readFileSync(o,"utf-8"));return!Array.isArray(s.scenarios)||s.scenarios.length===0?(console.log(`${z.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${z.reset}
|
|
1673
1676
|
`),al):s.scenarios}catch(s){return console.log(`${z.yellow}Failed to parse benchmark-config.json: ${s.message}${z.reset}
|
|
1674
|
-
`),al}}function Kb(t,e){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=vc(),r=n(t),i=r.score,a=[],c=s(t).toLowerCase();e.successCriteria.every(p=>c.includes(p.toLowerCase()))&&(i=Math.min(10,i+1),a.push("+1.0 all success criteria met"));let d=o(t);d.length<e.maxTurns/2&&(i=Math.min(10,i+.5),a.push(`+0.5 efficient (${d.length} tool calls < ${e.maxTurns/2})`)),i=Math.round(i*10)/10;let f=i>=9?"A":i>=8?"B":i>=7?"C":i>=6?"D":"F";return{score:i,grade:f,issues:r.issues,summary:r.summary,bonuses:a}}async function
|
|
1677
|
+
`),al}}function Kb(t,e){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=vc(),r=n(t),i=r.score,a=[],c=s(t).toLowerCase();e.successCriteria.every(p=>c.includes(p.toLowerCase()))&&(i=Math.min(10,i+1),a.push("+1.0 all success criteria met"));let d=o(t);d.length<e.maxTurns/2&&(i=Math.min(10,i+.5),a.push(`+0.5 efficient (${d.length} tool calls < ${e.maxTurns/2})`)),i=Math.round(i*10)/10;let f=i>=9?"A":i>=8?"B":i>=7?"C":i>=6?"D":"F";return{score:i,grade:f,issues:r.issues,summary:r.summary,bonuses:a}}async function GP(t,e={}){let{spawn:n}=require("child_process"),o=require("fs"),s=require("path"),r=require("os"),i=s.join(r.tmpdir(),`nex-bench-${t.id}-${Date.now()}.txt`);o.writeFileSync(i,t.prompt,"utf-8");let a=s.resolve(__dirname,"..","bin","nex-code.js"),c=e.cwd||process.cwd(),u=[a,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(t.maxTurns)];return e.model&&u.push("--model",e.model),new Promise(d=>{let f=n(process.execPath,u,{cwd:c,stdio:["ignore","pipe","pipe"],env:{...process.env}}),p=t.maxTurns*60*1e3,m=!1,h=setTimeout(()=>{m=!0;try{f.kill("SIGTERM")}catch{}},p);f.on("close",g=>{clearTimeout(h);try{o.unlinkSync(i)}catch{}let y=s.join(c,".nex","sessions","_autosave.json"),w=[];if(o.existsSync(y))try{w=JSON.parse(o.readFileSync(y,"utf-8")).messages||[]}catch{}d({messages:w,exitCode:g||0,timedOut:m})}),f.stdout.resume(),f.stderr.resume()})}function YP(t,e,n){let o=t.length>0?Math.round(t.reduce((c,u)=>c+u.score,0)/t.length*10)/10:0,s=o>=9?"A":o>=8?"B":o>=7?"C":o>=6?"D":"F",r=57,i="\u2500".repeat(r);console.log(`
|
|
1675
1678
|
\u250C\u2500 Benchmark Results ${"\u2500".repeat(r-19)}\u2510`);for(let c of t){let u=c.id.padEnd(20),d=c.name.substring(0,26).padEnd(26),f=`${c.score}/10`.padStart(6),p=c.grade.padStart(2);console.log(`\u2502 ${u} ${d} ${f} ${p} \u2502`)}console.log(`\u2502 ${" ".repeat(r-2)} \u2502`);let a=`Overall: ${o}/10 (${s}) \xB7 v${e} \xB7 ${n}`;console.log(`\u2502 ${a.substring(0,r-4).padEnd(r-4)} \u2502`),console.log(`\u2514${"\u2500".repeat(r+1)}\u2518
|
|
1676
|
-
`)}function
|
|
1679
|
+
`)}function zP(t=10){let e=require("fs"),o=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(o)){console.log(`${z.yellow}No score history yet. Run a session first.${z.reset}
|
|
1677
1680
|
`);return}let s=[];try{s=JSON.parse(e.readFileSync(o,"utf-8"))}catch{s=[]}if(!Array.isArray(s)||s.length===0){console.log(`${z.yellow}Score history is empty.${z.reset}
|
|
1678
1681
|
`);return}let r=s.slice(-t);console.log(`
|
|
1679
|
-
${z.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${z.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?`${z.yellow}\u26A0 ${i.issues.slice(0,2).map(h=>h.substring(0,30)).join(", ")}${z.reset}`:`${z.green}\u2713${z.reset}`,m=i.score>=8?z.green:i.score>=6?z.yellow:z.red;console.log(` ${z.dim}${a}${z.reset} ${z.dim}v${c}${z.reset} ${z.dim}${u}${z.reset} ${m}${d} ${f}${z.reset} ${p}`)}console.log()}async function
|
|
1682
|
+
${z.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${z.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?`${z.yellow}\u26A0 ${i.issues.slice(0,2).map(h=>h.substring(0,30)).join(", ")}${z.reset}`:`${z.green}\u2713${z.reset}`,m=i.score>=8?z.green:i.score>=6?z.yellow:z.red;console.log(` ${z.dim}${a}${z.reset} ${z.dim}v${c}${z.reset} ${z.dim}${u}${z.reset} ${m}${d} ${f}${z.reset} ${p}`)}console.log()}async function KP({dryRun:t=!1,model:e,cwd:n,onProgress:o}={}){let s=Po(),r=zb(n);if(t){console.log(`
|
|
1680
1683
|
${z.bold}Scenario Benchmark \u2014 Scenarios (dry-run):${z.reset}
|
|
1681
1684
|
`);for(let c of r)console.log(` ${z.cyan}${c.id.padEnd(20)}${z.reset} ${z.dim}${c.name}${z.reset} maxTurns=${c.maxTurns}`),console.log(` ${z.dim}${c.prompt.substring(0,80)}${z.reset}`);return console.log(),[]}let i=(()=>{if(e)return typeof e=="object"?e.id||"unknown":e;try{let{getActiveModel:c}=Uo(),u=c?c():null;return u?typeof u=="object"?u.id||"unknown":u:"unknown"}catch{return"unknown"}})(),a=[];for(let c of r){o?.({id:c.id,name:c.name,done:!1}),console.log(`
|
|
1682
|
-
${z.dim}Running scenario: ${c.name}...${z.reset}`);let{messages:u,timedOut:d}=await
|
|
1683
|
-
`).filter(Boolean).map(dl).filter(Boolean):[]}function Wi(t=process.cwd()){let e=ul(t);return Mt.existsSync(e)?Mt.readdirSync(e).filter(n=>/^reallife-.*\.json$/.test(n)).map(n=>{let o=cn.join(e,n);return{name:n,fullPath:o,mtimeMs:Mt.statSync(o).mtimeMs}}).sort((n,o)=>o.mtimeMs-n.mtimeMs):[]}function Jb(t=process.cwd()){let e=Wi(t)[0];if(!e)return null;let n=dl(Mt.readFileSync(e.fullPath,"utf8"));return n?{...n,__file:e.fullPath}:null}function Zb(t){if(!t)return!1;let e=t.metrics?.timeoutRate||0,n=t.finalScore||0,o=Array.isArray(t.results)?t.results:[];return e>0||n<90?!1:o.length===0?!0:o.every(s=>Er(s)==="healthy")}function
|
|
1684
|
-
`)}function e_(t=process.cwd()){return cn.join(ul(t),"prio")}function
|
|
1685
|
-
`),h=m.pop();for(let g of m)p(g);return h}r.stdout.on("data",f=>{let p=f.toString("utf8");i+=p,c+=p,c=d(c,m=>{n.onStdoutLine&&n.onStdoutLine(m)})}),r.stderr.on("data",f=>{let p=f.toString("utf8");a+=p,u+=p,u=d(u,m=>{n.onStderrLine&&n.onStderrLine(m)})}),r.on("error",s),r.on("close",(f,p)=>{c&&n.onStdoutLine&&n.onStdoutLine(c),u&&n.onStderrLine&&n.onStderrLine(u),o({status:f,signal:p,stdout:i,stderr:a})})})}function
|
|
1686
|
-
`)}async function
|
|
1687
|
-
`),r&&r({phase:"done",percent:100,message:`Saved verification bundle to ${c}`}),{bundleDir:c,summary:k,selectedTaskIds:i,selectedTests:a,tests:f,benchmark:w,verifiedRun:S}}function
|
|
1688
|
-
`)}s_.exports={buildCodexPrompt:Qb,buildOptimizationReport:
|
|
1685
|
+
${z.dim}Running scenario: ${c.name}...${z.reset}`);let{messages:u,timedOut:d}=await GP(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=Kb(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),o?.({id:c.id,name:c.name,done:!0,score:f.score,grade:f.grade});try{let{appendScoreHistory:m}=vc();m(f.score,{version:s.version,model:i,sessionName:`bench:${c.id}`,issues:f.issues})}catch{}}return YP(a,s.version,i),a}Xb.exports={runBenchmark:WP,runDiscoverBenchmark:HP,buildSummary:Wf,buildCategoryWinners:Wb,TASKS:Bf,PHASE_TASKS:Fb,ALL_TASKS:cl,scoreResult:Sr,DEFAULT_MODELS:Uf,QUICK_MODELS:Bb,runScenarioBenchmark:KP,showScoreTrend:zP,loadScenarios:zb,DEFAULT_SCENARIOS:al,scoreScenario:Kb}});var o_=X((fj,s_)=>{"use strict";var{spawn:XP,spawnSync:VP}=require("child_process"),Mt=require("fs"),cn=require("path");function ul(t=process.cwd()){return cn.join(t,"scripts","benchmark-results")}function dl(t){try{return JSON.parse(t)}catch{return null}}function JP(t=process.cwd()){let e=cn.join(ul(t),"reallife-history.jsonl");return Mt.existsSync(e)?Mt.readFileSync(e,"utf8").split(`
|
|
1686
|
+
`).filter(Boolean).map(dl).filter(Boolean):[]}function Wi(t=process.cwd()){let e=ul(t);return Mt.existsSync(e)?Mt.readdirSync(e).filter(n=>/^reallife-.*\.json$/.test(n)).map(n=>{let o=cn.join(e,n);return{name:n,fullPath:o,mtimeMs:Mt.statSync(o).mtimeMs}}).sort((n,o)=>o.mtimeMs-n.mtimeMs):[]}function Jb(t=process.cwd()){let e=Wi(t)[0];if(!e)return null;let n=dl(Mt.readFileSync(e.fullPath,"utf8"));return n?{...n,__file:e.fullPath}:null}function Zb(t){if(!t)return!1;let e=t.metrics?.timeoutRate||0,n=t.finalScore||0,o=Array.isArray(t.results)?t.results:[];return e>0||n<90?!1:o.length===0?!0:o.every(s=>Er(s)==="healthy")}function ZP(t=process.cwd()){let e=Wi(t);for(let n of e){let o=dl(Mt.readFileSync(n.fullPath,"utf8"));if(!o)continue;let s={...o,__file:n.fullPath};if(!Zb(s))return s}return Jb(t)}function Hf(t){return`${Math.round(t||0)}%`}function ll(t={}){let e=t.input||0,n=t.output||0;return`${e.toLocaleString()} in / ${n.toLocaleString()} out`}function Er(t){let e=t.completionReason==="timeout",n=t.toolCalls||0,o=t.tokens?.input||0,s=t.score??0,r=t.category==="docs"||t.category==="understanding";return e&&n>=20?"over-exploration":e&&r?"late finalization":e&&n===0?"tool underuse":e&&s>=60?"useful but unfinished":s<50&&o>=3e5?"high-cost weak result":n>=12&&s<70?"tool thrash":s>=80?"healthy":"quality gap"}function QP(t){switch(t){case"over-exploration":return"The agent keeps gathering evidence after enough context exists.";case"late finalization":return"The task likely has enough information, but the final deliverable starts too late.";case"tool underuse":return"The task finishes with little or no tool support, suggesting poor action selection.";case"useful but unfinished":return"The work is mostly correct, but the run exits before a clean final answer.";case"high-cost weak result":return"The task burns a large amount of tokens without converting that work into score.";case"tool thrash":return"The agent spends many tool calls for a middling result, suggesting loopiness.";case"quality gap":return"The task finishes, but output quality still needs improvement.";default:return"The task looks healthy compared with the rest of the run."}}function eL(t,e){if(!e?.runId||t.length<2)return null;let n=t.findIndex(s=>s.runId===e.runId);if(n<=0)return null;let o=t[n-1];return o?{previous:o,scoreDelta:(e.finalScore||0)-(o.finalScore||0),timeoutDelta:(e.metrics?.timeoutRate||0)-(o.metrics?.timeoutRate||0),toolDelta:(e.metrics?.avgToolCalls||0)-(o.metrics?.avgToolCalls||0)}:null}function tL(t=[],e){let n=new Map;for(let s of t){let r=Er(s);n.set(r,(n.get(r)||0)+1)}let o=[];return(n.get("over-exploration")||0)>0&&o.push("Reduce repeated read/search loops once enough evidence exists for a synthesis pass."),(n.get("late finalization")||0)>0&&o.push("Trigger earlier final deliverable generation for docs and understanding tasks."),(n.get("useful but unfinished")||0)>0&&o.push("Tighten headless completion criteria so strong partial work exits as a finished answer."),(n.get("tool thrash")||0)>0&&o.push("Cap redundant verification or repeated edits when score is not improving."),(e?.metrics?.timeoutRate||0)>=70&&o.push("Prioritize timeout reduction before raising quality bars or widening the benchmark slice."),o.slice(0,3)}function Qb(t,e){let n=t?.metrics?.timeoutRate||0,o=t?.metrics?.avgToolCalls||0;return["The benchmark harness is healthy and measuring correctly.","","Current benchmark evidence:",`- Final weighted score: ${t?.finalScore||0}/100`,`- Timeout rate: ${n}%`,`- Avg tool calls: ${o}`,`- Tokens: ${ll(t?.totalTokens)}`,"","Biggest bottleneck task:",`- ${e.id}: ${e.score}/100`,`- category: ${e.category}`,`- completionReason: ${e.completionReason||"unknown"}`,`- toolCalls: ${e.toolCalls||0}`,`- tokens: ${ll(e.tokens)}`,`- likely issue: ${Er(e)}`,"","Your task:","Implement exactly one focused systemic fix in cli/ code that addresses this dominant bottleneck pattern.","","Constraints:","- Do not modify benchmark files or benchmark task definitions.","- Do not add task-specific hacks.","- Keep the patch focused and small.","- Preserve the working tool/token telemetry path.","","What I want:","1. Identify the main reason this pattern still happens.","2. Implement one fix only.","3. Run the most relevant focused tests.","4. Explain why this should improve completion rate broadly."].join(`
|
|
1687
|
+
`)}function e_(t=process.cwd()){return cn.join(ul(t),"prio")}function nL(t){return Mt.mkdirSync(t,{recursive:!0}),t}function sL(t=new Date){return t.toISOString().replace(/[:.]/g,"-")}function t_(t,e=4){return(Array.isArray(t?.results)?t.results:[]).map(o=>({...o,pattern:Er(o)})).sort((o,s)=>{let r=o.completionReason==="timeout"?1:0,i=s.completionReason==="timeout"?1:0;return i!==r?i-r:(o.score||0)!==(s.score||0)?(o.score||0)-(s.score||0):(s.toolCalls||0)!==(o.toolCalls||0)?(s.toolCalls||0)-(o.toolCalls||0):(s.tokens?.input||0)-(o.tokens?.input||0)}).slice(0,e).map(o=>o.id)}function Vb(t,e,n={}){return VP(t,e,{cwd:n.cwd||process.cwd(),env:n.env||process.env,encoding:"utf8",maxBuffer:n.maxBuffer||20*1024*1024})}function oL(t,e,n={}){return new Promise((o,s)=>{let r=XP(t,e,{cwd:n.cwd||process.cwd(),env:n.env||process.env,stdio:["ignore","pipe","pipe"]}),i="",a="",c="",u="";function d(f,p){let m=f.split(`
|
|
1688
|
+
`),h=m.pop();for(let g of m)p(g);return h}r.stdout.on("data",f=>{let p=f.toString("utf8");i+=p,c+=p,c=d(c,m=>{n.onStdoutLine&&n.onStdoutLine(m)})}),r.stderr.on("data",f=>{let p=f.toString("utf8");a+=p,u+=p,u=d(u,m=>{n.onStderrLine&&n.onStderrLine(m)})}),r.on("error",s),r.on("close",(f,p)=>{c&&n.onStdoutLine&&n.onStdoutLine(c),u&&n.onStderrLine&&n.onStderrLine(u),o({status:f,signal:p,stdout:i,stderr:a})})})}function rL(t){return!t||!Mt.existsSync(t)?null:dl(Mt.readFileSync(t,"utf8"))}function iL(t,e=[]){let n=new Set(e),o=Wi(t).find(s=>!n.has(s.fullPath));return o?o.fullPath:null}function n_({sourceRun:t,verifiedRun:e,taskIds:n,tests:o,bundleDir:s}){let r=[],i=o.status===0?"passed":`failed (exit ${o.status})`,a=e?.finalScore??0,c=e?a-(t?.finalScore||0):null,u=e?(e.metrics?.timeoutRate||0)-(t?.metrics?.timeoutRate||0):null,d=e?(e.metrics?.avgToolCalls||0)-(t?.metrics?.avgToolCalls||0):null;return r.push(""),r.push("Harness Optimization Verification"),r.push(`- Source run: ${t?.runId||"unknown"}`),r.push(`- Focus tasks: ${n.join(", ")}`),r.push(`- Tests: ${i}`),e?(r.push(`- Verified run: ${e.runId||"unknown"}`),r.push(`- Score: ${a}/100${c===null?"":` (${c>=0?"+":""}${c})`}`),r.push(`- Timeout rate: ${Hf(e.metrics?.timeoutRate)}${u===null?"":` (${u>=0?"+":""}${u} pts)`}`),r.push(`- Avg tool calls: ${Math.round(e.metrics?.avgToolCalls||0)}${d===null?"":` (${d>=0?"+":""}${d})`}`),r.push(`- Tokens: ${ll(e.totalTokens)}`)):r.push("- Verified run: not found"),r.push(`- Artifacts: ${s}`),r.push(""),r.push("Next Step"),o.status!==0?r.push("- Fix the failing tests before trusting the benchmark slice."):e?(e.metrics?.timeoutRate||0)>=70?r.push("- Timeout pressure is still high. Use the updated report and Codex prompt before running a full benchmark."):r.push("- This slice looks healthier. Re-run a broader slice or the full benchmark before updating the gate baseline."):r.push("- The benchmark slice did not produce a new result file. Inspect the captured logs."),r.join(`
|
|
1689
|
+
`)}async function aL({rootDir:t=process.cwd(),latestRun:e,taskIds:n,testFiles:o,runner:s=Vb,onProgress:r}={}){if(!e)throw new Error("No latest benchmark run available for verification.");let i=Array.isArray(n)&&n.length>0?n:t_(e),a=Array.isArray(o)&&o.length>0?o:["tests/agent.test.js","tests/headless.test.js","tests/benchmark-reallife.test.js"],c=nL(cn.join(e_(t),sL())),u=Wi(t).map(C=>C.fullPath);r&&r({phase:"tests",percent:5,message:`Running focused tests (${a.length} files)`});let d=cn.join(t,"node_modules","jest","bin","jest.js"),f=await Promise.resolve(s(process.execPath,[d,...a,"--runInBand"],{cwd:t}));Mt.writeFileSync(cn.join(c,"tests.stdout.log"),f.stdout||""),Mt.writeFileSync(cn.join(c,"tests.stderr.log"),f.stderr||""),r&&r({phase:"tests",percent:20,message:f.status===0?"Focused tests passed":`Focused tests failed (exit ${f.status})`});let p=0,m=20,h=Math.max(1,i.length),g=s===Vb?oL:s,y=[process.execPath,cn.join(t,"scripts","benchmark-reallife.js"),"--tasks",i.join(",")];r&&r({phase:"benchmark",percent:25,message:`Running priority benchmark slice (${i.join(", ")})`});let w=await Promise.resolve(g(process.execPath,y.slice(1),{cwd:t,onStdoutLine(C){if(!r)return;let q=C.match(/Running ([\w-]+)\.\.\./);if(!q)return;p+=1;let ue=Math.min(95,20+Math.round(p/h*75));ue>m&&(m=ue,r({phase:"benchmark",percent:ue,message:`Running benchmark task ${p}/${h}: ${q[1]}`}))}}));Mt.writeFileSync(cn.join(c,"benchmark.stdout.log"),w.stdout||""),Mt.writeFileSync(cn.join(c,"benchmark.stderr.log"),w.stderr||""),r&&r({phase:"finalize",percent:97,message:"Writing verification artifacts"});let x=iL(t,u),S=rL(x),k=n_({sourceRun:e,verifiedRun:S,taskIds:i,tests:f,bundleDir:c}),v={createdAt:new Date().toISOString(),sourceRunId:e.runId||null,taskIds:i,testFiles:a,tests:{status:f.status,signal:f.signal},benchmark:{status:w.status,signal:w.signal,resultPath:x},summary:k};return Mt.writeFileSync(cn.join(c,"verification.json"),JSON.stringify(v,null,2)),Mt.writeFileSync(cn.join(c,"SUMMARY.md"),`${k}
|
|
1690
|
+
`),r&&r({phase:"done",percent:100,message:`Saved verification bundle to ${c}`}),{bundleDir:c,summary:k,selectedTaskIds:i,selectedTests:a,tests:f,benchmark:w,verifiedRun:S}}function cL({latestRun:t,history:e,lastN:n=5,includePrompt:o=!1}={}){if(!t)return"No real-life benchmark results found. Run `npm run benchmark:reallife` first.";let s=Array.isArray(t.results)?t.results:[],r=e.slice(-Math.max(1,n)),i=eL(e,t),a=Object.entries(t.categoryMetrics||{}).sort((p,m)=>{let h=(p[1]?.avgScore||0)-(m[1]?.avgScore||0);return h!==0?h:(m[1]?.timeoutRate||0)-(p[1]?.timeoutRate||0)}).slice(0,3),c=s.map(p=>({...p,pattern:Er(p)})).sort((p,m)=>{let h=p.completionReason==="timeout"?1:0,g=m.completionReason==="timeout"?1:0;return g!==h?g-h:(p.score||0)!==(m.score||0)?(p.score||0)-(m.score||0):(m.toolCalls||0)!==(p.toolCalls||0)?(m.toolCalls||0)-(p.toolCalls||0):(m.tokens?.input||0)-(p.tokens?.input||0)}).slice(0,3),u=tL(s,t),d=c[0],f=[];if(f.push(""),f.push("Harness Optimization Report"),f.push(`- Run: ${t.runId||"unknown"}`),f.push(`- Score: ${t.finalScore||0}/100`),f.push(`- Timeout rate: ${Hf(t.metrics?.timeoutRate)}`),f.push(`- Avg tool calls: ${Math.round(t.metrics?.avgToolCalls||0)}`),f.push(`- Tokens: ${ll(t.totalTokens)}`),f.push(`- Tasks: ${t.taskCount||s.length}`),i&&f.push(`- Trend vs previous: score ${i.scoreDelta>=0?"+":""}${i.scoreDelta}, timeout ${i.timeoutDelta>=0?"+":""}${i.timeoutDelta} pts, tools ${i.toolDelta>=0?"+":""}${i.toolDelta}`),r.length>1){let p=r.map(h=>h.finalScore||0),m=Math.round(p.reduce((h,g)=>h+g,0)/p.length);f.push(`- Recent average (${r.length} runs): ${m}/100`)}return f.push(""),f.push("Top Bottlenecks"),c.length===0?f.push("- No task-level details found in the latest run."):c.forEach((p,m)=>{f.push(`${m+1}. ${p.id} \u2014 ${p.score}/100, ${p.toolCalls||0} tools, ${p.completionReason||"unknown"}, ${p.pattern}`),f.push(` ${QP(p.pattern)}`)}),f.push(""),f.push("Weakest Categories"),a.length===0?f.push("- No category metrics found."):a.forEach(([p,m])=>{f.push(`- ${p}: ${m.avgScore}/100 avg, ${Hf(m.timeoutRate)} timeout, ${Math.round(m.avgToolCalls||0)} avg tools`)}),f.push(""),f.push("Recommendations"),u.length===0?f.push("- The latest run looks healthy. Re-run a larger slice before changing agent behavior."):u.forEach(p=>{f.push(`- ${p}`)}),o&&d&&(f.push(""),f.push("Suggested Codex Prompt"),f.push("```text"),f.push(Qb(t,d)),f.push("```")),f.join(`
|
|
1691
|
+
`)}s_.exports={buildCodexPrompt:Qb,buildOptimizationReport:cL,buildVerificationReport:n_,classifyTask:Er,getPriorityDir:e_,getResultsDir:ul,isHealthyRun:Zb,listResultFiles:Wi,readHistory:JP,readLatestResult:Jb,readLatestProblematicResult:ZP,selectPriorityTasks:t_,verifyHarnessOptimization:aL}});var p_=X((pj,f_)=>{"use strict";var lL=require("os"),a_=require("path"),Gf=require("fs"),{callWithRetry:r_}=ac(),{parseModelSpec:uL}=Xe(),{extractJSON:i_,DECOMPOSE_PROMPT:dL,SYNTHESIZE_PROMPT:fL}=yi(),{C:ln}=He(),fl=a_.join(lL.homedir(),".nex-code","orchestrator-bench.json"),c_=[{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 l_(t,e){if(!Array.isArray(t))return 0;let n=0;n+=1.5;let o=Math.abs(t.length-e.expectedSubTasks);o===0?n+=3:o===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 u_(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 o=Array.isArray(t.conflicts)?t.conflicts:[];return e.expectedConflicts===0&&o.length===0||e.expectedConflicts>0&&o.length>0?n+=2.5:e.expectedConflicts>0&&o.length===0&&(n+=0),Array.isArray(t.filesChanged)&&t.filesChanged.length>0&&(n+=2),Math.min(10,Math.round(n*10)/10)}async function d_(t,e){let n={};if(e){let s=uL(e);s.provider&&(n.provider=s.provider),s.model&&(n.model=s.model)}let o=Date.now();try{if(t.type==="decompose"){let s=dL.replace("{maxSubTasks}",String(t.maxSubTasks)).replace("{prompt}",t.prompt),r=await r_([{role:"system",content:s},{role:"user",content:t.prompt}],[],n),i=i_(r.content||""),a=Date.now()-o;return{score:l_(i,t),latencyMs:a}}if(t.type==="synthesize"){let s=t.subResults.map((d,f)=>{let p=d.status==="done"?"SUCCESS":"FAILED";return`--- Agent ${f+1} [${p}] ---
|
|
1689
1692
|
Task: ${d.task}
|
|
1690
1693
|
Result: ${d.result}
|
|
1691
1694
|
Tools: ${d.toolsUsed.join(", ")}`}).join(`
|
|
1692
1695
|
|
|
1693
|
-
`),r=
|
|
1696
|
+
`),r=fL.replace("{prompt}",t.prompt).replace("{results}",s),i=await r_([{role:"system",content:r},{role:"user",content:"Synthesize the sub-agent results above."}],[],n),a=i_(i.content||""),c=Date.now()-o;return{score:u_(a,t),latencyMs:c}}return{score:0,latencyMs:0,error:`Unknown scenario type: ${t.type}`}}catch(s){return{score:0,latencyMs:Date.now()-o,error:s.message}}}async function pL(t={}){let e=t.models||["kimi-k2.5","qwen3.5:397b","minimax-m2.7:cloud"],n=t.onProgress||(()=>{}),o=[];for(let r of e){let i={model:r,scores:[],latencies:[]},a=[],c=[];for(let m of c_){n({model:r,scenario:m.id,done:!1});let h=await d_(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;o.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})}o.sort((r,i)=>i.overall-r.overall);let s=a_.dirname(fl);return Gf.existsSync(s)||Gf.mkdirSync(s,{recursive:!0}),Gf.writeFileSync(fl,JSON.stringify({date:new Date().toISOString().slice(0,10),results:o},null,2)),o}function hL(t){console.log(`
|
|
1694
1697
|
${ln.bold}${ln.cyan}Orchestrator Model Benchmark${ln.reset}
|
|
1695
1698
|
`);let e=` ${"Model".padEnd(25)} ${"Decompose".padEnd(10)} ${"Synthesize".padEnd(11)} ${"Speed".padEnd(8)} ${"Score".padEnd(8)}`;console.log(`${ln.dim}${e}${ln.reset}`),console.log(` ${ln.dim}${"\u2500".repeat(65)}${ln.reset}`);for(let n of t){let o=t.indexOf(n)===0?"\u{1F947}":t.indexOf(n)===1?"\u{1F948}":t.indexOf(n)===2?"\u{1F949}":" ",s=`${(n.avgLatency/1e3).toFixed(1)}s`;console.log(`${o} ${n.model.padEnd(25)} ${(n.decompose+"/10").padEnd(10)} ${(n.synthesize+"/10").padEnd(11)} ${s.padEnd(8)} ${ln.bold}${n.overall}/10${ln.reset}`)}t.length>0&&(console.log(`
|
|
1696
1699
|
${ln.green}Best orchestrator: ${t[0].model} (${t[0].overall}/10)${ln.reset}`),console.log(` ${ln.dim}Saved to ${fl}${ln.reset}
|
|
1697
|
-
`))}f_.exports={runOrchestratorBenchmark:
|
|
1698
|
-
`),m=(y=f)=>` ${ce.dim}${"\u2500".repeat(y)}${ce.reset}`,h=y=>{p(""),p(` ${ce.bold}${ce.white}${y}${ce.reset}`),p(m())};process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),p(""),p(m()),p(` ${ce.bold}${ce.primary} Agent powering down. Goodbye!${ce.reset}`+(a>0?` ${ce.dim}${
|
|
1700
|
+
`))}f_.exports={runOrchestratorBenchmark:pL,ORCHESTRATOR_SCENARIOS:c_,scoreDecompose:l_,scoreSynthesize:u_,runScenario:d_,printResults:hL,RESULTS_PATH:fl}});var g_=X((hj,m_)=>{var mL=require("axios"),Hi=require("fs"),h_=require("path"),gL="nex-code",Yf=h_.join(process.cwd(),".nex"),zf=h_.join(Yf,"last-version-check");Hi.existsSync(Yf)||Hi.mkdirSync(Yf,{recursive:!0});async function yL(){try{let t=wL(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};bL(e);let n=$L(),s=(await mL.get(`https://registry.npmjs.org/${gL}/latest`,{timeout:5e3})).data.version,r=_L(s,n);return{hasNewVersion:r,latestVersion:r?s:void 0,currentVersion:r?n:void 0}}catch{return{hasNewVersion:!1}}}function $L(){return Po().version}function wL(){try{if(Hi.existsSync(zf)){let t=Hi.readFileSync(zf,"utf8");return parseInt(t,10)}}catch{}return null}function bL(t){try{Hi.writeFileSync(zf,t.toString())}catch{}}function _L(t,e){try{let n=t.split(".").map(Number),o=e.split(".").map(Number);return n[0]>o[0]?!0:n[0]<o[0]?!1:n[1]>o[1]?!0:n[1]<o[1]?!1:n[2]>o[2]}catch{return!1}}m_.exports={checkForNewVersion:yL}});var $_=X((mj,y_)=>{"use strict";var{C:ce}=He();function Kf(t){let e=Math.floor(t/1e3);if(e<60)return`${e}s`;let n=Math.floor(e/60),o=e%60;if(n<60)return`${n}m ${o<10?"0":""}${o}s`;let s=Math.floor(n/60),r=n%60;return`${s}h ${r<10?"0":""}${r}m ${o<10?"0":""}${o}s`}function Gi(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function Yi(t,e){let n=String(t);return n.length>=e?n.slice(0,e):n+" ".repeat(e-n.length)}function Vt(t,e){let n=String(t);return n.length>=e?n.slice(0,e):" ".repeat(e-n.length)+n}function xL(t,e,n=18){if(e===0)return"\u2591".repeat(n);let o=Math.round(t/e*n);return ce.primary+"\u2588".repeat(o)+ce.dim+"\u2591".repeat(n-o)+ce.reset}function vL({startTime:t,sessionId:e,messages:n}){if(!process.stdout.isTTY)return;let{extractSessionStats:o}=Qc(),{getSessionCosts:s}=xs(),r=o(n),i=s(),a=t?Date.now()-t:0,c=r!==null,u=i.breakdown.length>0;if(!c&&!u&&a<5e3)return;let f=Math.min(process.stdout.columns||72,80)-4,p=(y="")=>process.stdout.write(y+`
|
|
1701
|
+
`),m=(y=f)=>` ${ce.dim}${"\u2500".repeat(y)}${ce.reset}`,h=y=>{p(""),p(` ${ce.bold}${ce.white}${y}${ce.reset}`),p(m())};process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),p(""),p(m()),p(` ${ce.bold}${ce.primary} Agent powering down. Goodbye!${ce.reset}`+(a>0?` ${ce.dim}${Kf(a)}${ce.reset}`:"")),p(m()),h("Interaction Summary");let g=(y,w,x="")=>{p(` ${ce.dim}${Yi(y+":",24)}${ce.reset} ${ce.white}${w}${ce.reset}${x}`)};if(g("Session ID",e),c){let y=r.totalToolCalls-r.totalErrors,w=r.totalToolCalls>0?(y/r.totalToolCalls*100).toFixed(1):"\u2014",x=`${r.totalToolCalls} ${ce.dim}(${ce.success}\u2713 ${y}${ce.reset}`+(r.totalErrors>0?`${ce.dim} ${ce.error}\u2717 ${r.totalErrors}${ce.reset}${ce.dim}`:"")+`${ce.dim})${ce.reset}`;g("Tool Calls",x),g("Success Rate",`${w}%`),g("User Messages",String(r.userMessages));let S=Object.keys(r.filesModified||{}),k=Object.keys(r.filesAccessed||{});if(S.length>0){let v=S.slice(0,2).map(q=>{let D=q.split("/").pop();return`${ce.dim}${D}${ce.reset}`}).join(` ${ce.dim}\xB7${ce.reset} `),C=S.length>2?` ${ce.dim}+${S.length-2} more${ce.reset}`:"";g("Files Modified",String(S.length),` ${ce.dim}\xB7${ce.reset} ${v}${C}`)}k.length>0&&g("Files Read",String(k.length))}if(c&&a>0&&(h("Performance"),g("Wall Time",Kf(a)),g("Turns (user / assistant)",`${r.userMessages} ${ce.dim}/${ce.reset} ${r.assistantMessages}`),r.userMessages>0&&r.totalToolCalls>0)){let y=(r.totalToolCalls/r.userMessages).toFixed(1);g("Tools per User Message",y)}if(u){h("Token Usage");let y=34,w=6,x=10,S=9;p(` ${ce.dim}`+Yi("Model",y)+Vt("Reqs",w)+Vt("Input",x)+Vt("Output",x)+Vt("Cost",S)+ce.reset),p(m());let k=0,v=0,C=0,q=0;for(let D of i.breakdown){let ee=`${D.provider} \xB7 ${D.model}`,ue=ee.length>y-1?ee.slice(0,y-2)+"\u2026":ee,le=D.cost>0?`$${D.cost.toFixed(4)}`:"free";k+=D.requests||0,v+=D.input,C+=D.output,q+=D.cost,p(` ${ce.cyan}${Yi(ue,y)}${ce.reset}${ce.dim}${Vt(D.requests||"\u2014",w)}${ce.reset} ${ce.dim}${Vt(Gi(D.input),x-2)}${ce.reset} ${ce.dim}${Vt(Gi(D.output),x-2)}${ce.reset} ${D.cost>0?ce.yellow:ce.success}${Vt(le,S-2)}${ce.reset}`)}if(i.breakdown.length>1){p(m());let D=q>0?`$${q.toFixed(4)}`:"free";p(` ${ce.bold}${Yi("Total",y)}${ce.reset}${ce.dim}${Vt(k||"\u2014",w)}${ce.reset} ${ce.dim}${Vt(Gi(v),x-2)}${ce.reset} ${ce.dim}${Vt(Gi(C),x-2)}${ce.reset} ${q>0?ce.yellow:ce.success}${ce.bold}${Vt(D,S-2)}${ce.reset}`)}if(u&&v>0){let D=i.breakdown.reduce((ee,ue)=>ee+(ue.cacheRead||0),0);if(D>0){let ee=(D/(v+D)*100).toFixed(1);p(""),p(` ${ce.dim}Cache savings: ${ce.success}${Gi(D)}${ce.reset}${ce.dim} tokens (${ee}%) served from cache${ce.reset}`)}}}if(c&&r.totalToolCalls>0){let y=Object.entries(r.toolCalls).sort(([,w],[,x])=>x-w).slice(0,6);if(y.length>0){h("Top Tools");let w=y[0][1],x=r.totalToolCalls;for(let[S,k]of y){let v=(k/x*100).toFixed(0),C=Yi(S,22),q=Vt(String(k),4),D=Vt(`${v}%`,5);p(` ${ce.cyan}${C}${ce.reset} ${xL(k,w,16)} ${ce.white}${q}${ce.reset} ${ce.dim}${D}${ce.reset}`)}}}if(c){let y=Object.entries(r.filesModified||{});if(y.length>0){h("Modified Files");for(let[w,x]of y.slice(0,5)){let S=f-6,k=w.length>S?"\u2026"+w.slice(-(S-1)):w,v=x>1?` ${ce.dim}(${x}\xD7)${ce.reset}`:"";p(` ${ce.success}\u270E${ce.reset} ${ce.white}${k}${ce.reset}${v}`)}y.length>5&&p(` ${ce.dim} \u2026 and ${y.length-5} more${ce.reset}`)}}p(""),p(m()),p(` ${ce.dim}Resume last session:${ce.reset} ${ce.cyan}nex-code --resume${ce.reset}`),p(m()),p("")}y_.exports={showGoodbyeScreen:vL,formatDuration:Kf}});var op=X((yj,A_)=>{var kL=require("readline"),Rt=require("fs"),xt=require("path"),{C:l,banner:SL,cleanupTerminal:w_}=He(),{isDark:EL}=Lt(),{listProviders:Zf,getActiveProviderName:ko,listAllModels:gj,setFallbackChain:TL,getFallbackChain:RL,getProvider:CL}=Xe(),{flushAutoSave:b_}=Mn(),{writeDreamLog:AL,shouldConsolidate:OL,consolidate:ML}=Qc(),{isDebug:NL}=Sa(),{getActiveModel:gs,setActiveModel:Qf}=Uo(),{printContext:x_}=_c(),{loadAllSkills:PL,getSkillCommands:hl,handleSkillCommand:LL}=is(),{setReadlineInterface:IL,setAutoConfirm:jL,getAutoConfirm:Vf,setAllowAlwaysHandler:DL}=It(),{StickyFooter:qL}=lb(),Nt=process.cwd(),ze=null,Fn=null,__=null,Xf=null;function v_(){return Fn?.signal??null}var Vi=[{cmd:"/help",desc:"Show full help"},{cmd:"/model",desc:"Show/switch model"},{cmd:"/routing",desc:"Show active model routing (per task category)"},{cmd:"/providers",desc:"List providers and models"},{cmd:"/fallback",desc:"Show/set fallback chain"},{cmd:"/tokens",desc:"Token usage and context budget"},{cmd:"/costs",desc:"Session token costs"},{cmd:"/budget",desc:"Show/set cost limits per provider"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/context",desc:"Show project context"},{cmd:"/tree [depth]",desc:"Show project file tree (default depth 3)"},{cmd:"/autoconfirm",desc:"Toggle auto-confirm"},{cmd:"/save",desc:"Save session"},{cmd:"/load",desc:"Load a saved session"},{cmd:"/sessions",desc:"List saved sessions"},{cmd:"/resume",desc:"Resume last session"},{cmd:"/branches",desc:"Show session tree (all branches)"},{cmd:"/timeline",desc:"Show message timeline of current branch"},{cmd:"/goto <index>",desc:"Jump to a message index (truncates after)"},{cmd:"/fork [index]",desc:"Create branch at index (default: current)"},{cmd:"/switch-branch <name>",desc:"Switch to a different conversation branch"},{cmd:"/delete-branch <name>",desc:"Delete a conversation branch"},{cmd:"/remember",desc:"Save a memory"},{cmd:"/forget",desc:"Delete a memory"},{cmd:"/memory",desc:"Show all memories"},{cmd:"/brain",desc:"Manage knowledge base"},{cmd:"/brain add",desc:"Add document: /brain add <name> [content]"},{cmd:"/brain list",desc:"List all brain documents"},{cmd:"/brain search",desc:"Search brain: /brain search <query>"},{cmd:"/brain show",desc:"Show document: /brain show <name>"},{cmd:"/brain remove",desc:"Remove document: /brain remove <name>"},{cmd:"/brain rebuild",desc:"Rebuild keyword index"},{cmd:"/brain embed",desc:"Build/rebuild embedding index"},{cmd:"/brain status",desc:"Show brain status (docs, index, embeddings)"},{cmd:"/brain review",desc:"Review pending brain changes (git diff)"},{cmd:"/brain undo",desc:"Undo last brain write"},{cmd:"/learn",desc:"Reflect on session and update memory"},{cmd:"/optimize",desc:"Show optimization opportunities"},{cmd:"/permissions",desc:"Show tool permissions"},{cmd:"/allow",desc:"Auto-allow a tool"},{cmd:"/deny",desc:"Block a tool"},{cmd:"/plan",desc:"Plan mode (analyze before executing)"},{cmd:"/plan edit",desc:"Open current plan in $EDITOR"},{cmd:"/plans",desc:"List saved plans"},{cmd:"/auto",desc:"Set autonomy level"},{cmd:"/commit",desc:"Smart commit (diff + message)"},{cmd:"/diff",desc:"Show current diff"},{cmd:"/review [--strict] [file]",desc:"Deep code review with score table and diff suggestions (--strict: force \u22653 critical findings)"},{cmd:"/branch",desc:"Create feature branch"},{cmd:"/mcp",desc:"MCP servers and tools"},{cmd:"/mcp list",desc:"List connected MCP servers and their tools"},{cmd:"/mcp status",desc:"Show which MCP servers are running"},{cmd:"/hooks",desc:"Show configured hooks"},{cmd:"/skills",desc:"List, enable, disable skills"},{cmd:"/install-skill <url>",desc:"Install a skill from git URL or user/repo"},{cmd:"/search-skill <query>",desc:"Search for skills on GitHub"},{cmd:"/remove-skill <name>",desc:"Remove an installed skill"},{cmd:"/tasks",desc:"Show task list"},{cmd:"/servers",desc:"List server profiles / ping"},{cmd:"/docker",desc:"List containers across all servers"},{cmd:"/deploy",desc:"List deploy configs / run named deploy"},{cmd:"/benchmark [--quick] [--models=a,b]",desc:"Rank Ollama Cloud models on nex-code tool-calling tasks (--history for nightly log)"},{cmd:"/bench [--dry-run] [--model=<spec>]",desc:"Run scenario benchmark (5 agentic tasks)"},{cmd:"/trend [n]",desc:"Show score history trend (default: last 10 sessions)"},{cmd:"/harness-optimization [--last N] [--prompt] [--verify]",desc:"Analyze recent real-life benchmark runs and optionally verify a priority slice"},{cmd:"/init",desc:"Interactive setup wizard (.nex/)"},{cmd:"/setup",desc:"Configure provider and API keys"},{cmd:"/retry [--model <id>]",desc:"Retry last user turn (optionally with a different model)"},{cmd:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/snapshot [name]",desc:"Create a named git snapshot of current changes"},{cmd:"/restore [name|last]",desc:"Restore a previously created snapshot"},{cmd:"/orchestrate <prompt>",desc:"Decompose prompt into parallel sub-tasks, run, synthesize"},{cmd:"/bench-orchestrator",desc:"Benchmark models for orchestrator role"},{cmd:"/audit",desc:"Show tool execution audit log"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function k_(){let t=hl(),e=[...Vi,...t],n=Math.max(...e.map(o=>o.cmd.length));console.log("");for(let{cmd:o,desc:s}of Vi)console.log(` ${l.cyan}${o.padEnd(n+2)}${l.reset}${l.dim}${s}${l.reset}`);for(let{cmd:o,desc:s}of t)console.log(` ${l.cyan}${o.padEnd(n+2)}${l.reset}${l.dim}${s} ${l.yellow}[skill]${l.reset}`);console.log(`
|
|
1699
1702
|
${l.dim}Type /help for detailed usage${l.reset}
|
|
1700
1703
|
`)}function S_(t){try{let e,n;t.endsWith("/")||t.endsWith(xt.sep)?(e=t,n=""):(e=xt.dirname(t),n=xt.basename(t)),e.startsWith("~")&&(e=xt.join(require("os").homedir(),e.slice(1)));let o=xt.isAbsolute(e)?e:xt.resolve(Nt,e);if(!Rt.existsSync(o)||!Rt.statSync(o).isDirectory())return[];let s=Rt.readdirSync(o,{withFileTypes:!0}),r=[];for(let i of s){if(i.name.startsWith(".")||i.name==="node_modules"||n&&!i.name.startsWith(n))continue;let a=t.endsWith("/")||t.endsWith(xt.sep)?t:xt.dirname(t)+"/",c=a==="./"&&!t.startsWith("./")?i.name:a+i.name;r.push(i.isDirectory()?c+"/":c)}return r}catch{return[]}}function E_(t){if(t.startsWith("/")){let o=[...Vi,...hl()],s=o.map(r=>r.cmd).filter(r=>r.startsWith(t));return[s.length?s:o.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("~"))?[S_(n),n]:[[],t]}function T_(){console.log(`
|
|
1701
1704
|
${l.bold}${l.cyan}Commands:${l.reset}
|
|
@@ -1771,25 +1774,25 @@ ${l.bold}${l.cyan}Undo / Redo:${l.reset}
|
|
|
1771
1774
|
${l.cyan}/benchmark --all --parallel=N${l.reset}${l.dim} Override concurrency (default 3)${l.reset}
|
|
1772
1775
|
|
|
1773
1776
|
${l.cyan}/exit${l.reset} ${l.dim}Quit${l.reset}
|
|
1774
|
-
`)}function R_(t){let n=Math.round(t/100*30),o=30-n;return` ${t>80?l.red:t>50?l.yellow:l.green}${"\u2588".repeat(n)}${l.dim}${"\u2591".repeat(o)}${l.reset} ${t}%`}function
|
|
1775
|
-
${l.bold}${l.cyan}Providers:${l.reset}`);for(let o of t){let s=o.provider===e,r=o.configured?`${l.green}\u2713${l.reset}`:`${l.red}\u2717${l.reset}`,i=s?` ${l.cyan}(active)${l.reset}`:"";console.log(` ${r} ${l.bold}${o.provider}${l.reset}${i}`);for(let a of o.models){let c=a.id===n.id&&s?` ${l.yellow}\u25C4${l.reset}`:"";console.log(` ${l.dim}${a.id}${l.reset} \u2014 ${a.name}${c}`)}}console.log()}async function Xi(t,e){let[n,...o]=t.split(/\s+/);switch(n){case"/help":return T_(),!0;case"/model":{let s=o.join(" ").trim();if(!s){if(e){let{showModelPicker:r}=fb();await r(e)}else{let r=gs(),i=ko();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(s==="list")return
|
|
1777
|
+
`)}function R_(t){let n=Math.round(t/100*30),o=30-n;return` ${t>80?l.red:t>50?l.yellow:l.green}${"\u2588".repeat(n)}${l.dim}${"\u2591".repeat(o)}${l.reset} ${t}%`}function Jf(){let t=Zf(),e=ko(),n=gs();console.log(`
|
|
1778
|
+
${l.bold}${l.cyan}Providers:${l.reset}`);for(let o of t){let s=o.provider===e,r=o.configured?`${l.green}\u2713${l.reset}`:`${l.red}\u2717${l.reset}`,i=s?` ${l.cyan}(active)${l.reset}`:"";console.log(` ${r} ${l.bold}${o.provider}${l.reset}${i}`);for(let a of o.models){let c=a.id===n.id&&s?` ${l.yellow}\u25C4${l.reset}`:"";console.log(` ${l.dim}${a.id}${l.reset} \u2014 ${a.name}${c}`)}}console.log()}async function Xi(t,e){let[n,...o]=t.split(/\s+/);switch(n){case"/help":return T_(),!0;case"/model":{let s=o.join(" ").trim();if(!s){if(e){let{showModelPicker:r}=fb();await r(e)}else{let r=gs(),i=ko();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(s==="list")return Jf(),!0;if(Qf(s)){let r=gs(),i=ko();console.log(`${l.green}Switched to ${i}:${r.id} (${r.name})${l.reset}`)}else console.log(`${l.red}Unknown model: ${s}${l.reset}`),console.log(`${l.gray}Use /providers to see available models${l.reset}`);return!0}case"/routing":{let{loadRoutingConfig:s}=Xn(),r=s(),i=require("os"),a=require("path").join(i.homedir(),".nex-code","model-routing.json");console.log(`
|
|
1776
1779
|
${l.bold}${l.cyan}Model Routing${l.reset} ${l.dim}(${a})${l.reset}
|
|
1777
1780
|
`);let c=["coding","frontend","sysadmin","data","agentic","plan","verify"];for(let d of c){let f=r[d];f&&console.log(` ${l.dim}${d.padEnd(12)}${l.reset} ${l.green}${f}${l.reset}`)}let u=r.phases;if(u&&Object.keys(u).length>0){console.log(`
|
|
1778
1781
|
${l.bold}${l.dim}Phases:${l.reset}`);for(let[d,f]of Object.entries(u))console.log(` ${l.dim}${d.padEnd(12)}${l.reset} ${l.cyan}${f}${l.reset}`)}return console.log(`
|
|
1779
1782
|
${l.dim}Run /benchmark --all to update routing${l.reset}
|
|
1780
|
-
`),!0}case"/providers":return
|
|
1783
|
+
`),!0}case"/providers":return Jf(),!0;case"/fallback":{let s=o.join(" ").trim();if(!s){let i=RL();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=s.split(",").map(i=>i.trim()).filter(Boolean);return TL(r),console.log(`${l.green}Fallback chain: ${r.join(" \u2192 ")}${l.reset}`),!0}case"/tokens":{let{getConversationMessages:s}=Ee(),{getUsage:r}=en(),{TOOL_DEFINITIONS:i}=Sn(),a=s(),c=r(a,i),u=gs(),d=ko();console.log(`
|
|
1781
1784
|
${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=R_(c.percentage);return console.log(` ${f}`),console.log(`
|
|
1782
1785
|
${l.dim}Breakdown:${l.reset}`),console.log(` System prompt: ${c.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${c.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${c.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${c.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${c.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:s,resetCosts:r}=xs();return o.join(" ").trim()==="reset"?(r(),console.log(`${l.green}Cost tracking reset${l.reset}`),!0):(console.log(`
|
|
1783
1786
|
${s()}
|
|
1784
|
-
`),!0)}case"/budget":{let{getCostLimits:s,getProviderSpend:r,checkBudget:i,removeCostLimit:a,saveCostLimits:c,setCostLimit:u}=xs(),d=o[0];if(!d){let m=s(),h=
|
|
1785
|
-
${l.bold}${l.cyan}Cost Limits:${l.reset}`);let g=!1;for(let y of h){let w=r(y.provider),x=m[y.provider];if(x!==void 0){g=!0;let S=Math.min(100,Math.round(w/x*100)),k=10,v=Math.round(S/100*k),C=k-v,D=`${S>=100?l.red:S>=80?l.yellow:l.green}${"\u2588".repeat(v)}${l.dim}${"\u2591".repeat(C)}${l.reset}`;console.log(` ${l.bold}${y.provider}:${l.reset} $${w.toFixed(2)} / $${x.toFixed(2)} (${S}%) ${D}`)}else y.provider==="ollama"||y.provider==="local"?console.log(` ${l.bold}${y.provider}:${l.reset} ${l.dim}free (no limit)${l.reset}`):w>0&&console.log(` ${l.bold}${y.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=o[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:s,getConversationMessages:r}=Ee(),{clearHistory:i}=rs(),a=r();if(a.filter(d=>d.role==="user").length>=4){process.stdout.write(`${l.dim}Reflecting on session...${l.reset} `);let{learnFromSession:d}=
|
|
1787
|
+
`),!0)}case"/budget":{let{getCostLimits:s,getProviderSpend:r,checkBudget:i,removeCostLimit:a,saveCostLimits:c,setCostLimit:u}=xs(),d=o[0];if(!d){let m=s(),h=Zf();console.log(`
|
|
1788
|
+
${l.bold}${l.cyan}Cost Limits:${l.reset}`);let g=!1;for(let y of h){let w=r(y.provider),x=m[y.provider];if(x!==void 0){g=!0;let S=Math.min(100,Math.round(w/x*100)),k=10,v=Math.round(S/100*k),C=k-v,D=`${S>=100?l.red:S>=80?l.yellow:l.green}${"\u2588".repeat(v)}${l.dim}${"\u2591".repeat(C)}${l.reset}`;console.log(` ${l.bold}${y.provider}:${l.reset} $${w.toFixed(2)} / $${x.toFixed(2)} (${S}%) ${D}`)}else y.provider==="ollama"||y.provider==="local"?console.log(` ${l.bold}${y.provider}:${l.reset} ${l.dim}free (no limit)${l.reset}`):w>0&&console.log(` ${l.bold}${y.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=o[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:s,getConversationMessages:r}=Ee(),{clearHistory:i}=rs(),a=r();if(a.filter(d=>d.role==="user").length>=4){process.stdout.write(`${l.dim}Reflecting on session...${l.reset} `);let{learnFromSession:d}=Of();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}
|
|
1786
1789
|
`)}else process.stdout.write(`${l.dim}nothing new${l.reset}
|
|
1787
1790
|
`)}).catch(()=>process.stdout.write(`
|
|
1788
1791
|
`))}s(),i(),ze=null;let{deleteSession:u}=Mn();return u("_autosave"),console.log(`${l.green}Conversation cleared${l.reset}`),!0}case"/retry":{let{getConversationMessages:s,setConversationMessages:r,processInput:i}=Ee(),a=s(),c=a.map(g=>g.role).lastIndexOf("user");if(c===-1)return console.log(`${l.yellow}Nothing to retry \u2014 no user message found.${l.reset}`),!0;let u=o.indexOf("--model"),d=u!==-1&&o[u+1]?o[u+1]:null;if(d){let{setActiveModel:g}=Xe();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(`
|
|
1789
1792
|
`):p=String(f.content),r(a.slice(0,c));let{resetSessionTracking:m}=Ee();m();let h=d||"current model";return console.log(`${l.cyan}Retrying with ${h}...${l.reset}`),await i(p),!0}case"/context":return await x_(Nt),!0;case"/tree":{let{generateFileTree:s}=_c(),r=parseInt(o.join(" ").trim(),10),i=!isNaN(r)&&r>0?Math.min(r,8):3,a=s(Nt,{maxDepth:i,maxFiles:300});return console.log(`
|
|
1790
1793
|
${l.bold}${l.cyan}Project tree${l.reset}${l.dim} (depth ${i})${l.reset}
|
|
1791
1794
|
`),console.log(`${l.dim}${a}${l.reset}
|
|
1792
|
-
`),!0}case"/autoconfirm":{let s=!
|
|
1795
|
+
`),!0}case"/autoconfirm":{let s=!Vf();return jL(s),console.log(`${l.green}Auto-confirm: ${s?"ON":"OFF"}${l.reset}`),s&&console.log(`${l.yellow} \u26A0 File changes will be applied without confirmation${l.reset}`),zi(),!0}case"/save":{let{saveSession:s}=Mn(),{getConversationMessages:r}=Ee(),i=o.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=gs(),u=ko();return s(i,a,{model:c.id,provider:u}),console.log(`${l.green}Session saved: ${i} (${a.length} messages)${l.reset}`),!0}case"/load":{let{loadSession:s}=Mn(),{setConversationMessages:r}=Ee(),i=o.join(" ").trim();if(!i)return console.log(`${l.red}Usage: /load <name>${l.reset}`),!0;let a=s(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:s}=Mn(),r=s();if(r.length===0)return console.log(`${l.dim}No saved sessions${l.reset}`),!0;console.log(`
|
|
1793
1796
|
${l.bold}${l.cyan}Sessions:${l.reset}`);for(let i of r){let a=i.updatedAt?new Date(i.updatedAt).toLocaleString():"?",c=i.name==="_autosave"?` ${l.dim}(auto)${l.reset}`:"",u=i.score!=null?` \xB7 score ${i.score}/10${i.scoreGrade?` (${i.scoreGrade})`:""}`:"";console.log(` ${l.cyan}${i.name}${l.reset}${c} \u2014 ${i.messageCount} msgs, ${a}${l.dim}${u}${l.reset}`)}return console.log(),!0}case"/resume":{let{getLastSession:s}=Mn(),{setConversationMessages:r}=Ee(),i=s();return i?(r(i.messages),console.log(`${l.green}Resumed: ${i.name} (${i.messageCount} messages)${l.reset}`),!0):(console.log(`${l.yellow}No session to resume${l.reset}`),!0)}case"/branches":{let{initTree:s,renderTree:r}=Ms(),{getConversationMessages:i}=Ee(),a=i();return a.length===0?(console.log(`${l.yellow}No conversation yet${l.reset}`),!0):(ze||(ze=s({messages:a})),console.log(r(ze)),console.log(),!0)}case"/timeline":{let{initTree:s,renderTimeline:r}=Ms(),{getConversationMessages:i}=Ee(),a=i();if(a.length===0)return console.log(`${l.yellow}No conversation yet${l.reset}`),!0;ze||(ze=s({messages:a})),Ms().setActiveMessages(ze,a);let u=parseInt(o[0],10)||20;return console.log(r(ze,u)),console.log(),!0}case"/goto":{let s=Ms(),{getConversationMessages:r,setConversationMessages:i}=Ee(),a=r();if(a.length===0)return console.log(`${l.yellow}No conversation yet${l.reset}`),!0;let c=parseInt(o[0],10);if(isNaN(c))return console.log(`${l.red}Usage: /goto <message-index>${l.reset}`),console.log(`${l.dim}Use /timeline to see message indices${l.reset}`),!0;ze||(ze=s.initTree({messages:a})),s.setActiveMessages(ze,a);try{let{truncated:u}=s.gotoMessage(ze,c),d=s.getActiveMessages(ze);i(d),console.log(`${l.green}Jumped to message ${c}. Removed ${u} later messages.${l.reset}`),console.log(`${l.dim}Conversation now has ${d.length} messages. Continue chatting from here.${l.reset}`)}catch(u){console.log(`${l.red}${u.message}${l.reset}`)}return!0}case"/fork":{let s=Ms(),{getConversationMessages:r,setConversationMessages:i}=Ee(),a=r();if(a.length===0)return console.log(`${l.yellow}No conversation yet${l.reset}`),!0;ze||(ze=s.initTree({messages:a})),s.setActiveMessages(ze,a);let c=o[0]?parseInt(o[0],10):a.length-1,u=o[1]||void 0;if(isNaN(c))return console.log(`${l.red}Usage: /fork [message-index] [branch-name]${l.reset}`),!0;try{let{branchName:d}=s.createBranch(ze,c,u),f=s.getActiveMessages(ze);i(f),console.log(`${l.green}Created branch "${d}" forking at message ${c}${l.reset}`),console.log(`${l.dim}Now on branch "${d}" with ${f.length} messages. Continue chatting.${l.reset}`)}catch(d){console.log(`${l.red}${d.message}${l.reset}`)}return!0}case"/switch-branch":{let s=Ms(),{getConversationMessages:r,setConversationMessages:i}=Ee();if(!ze){let c=r();ze=s.initTree({messages:c})}s.setActiveMessages(ze,r());let a=o.join(" ").trim();if(!a)return console.log(`${l.red}Usage: /switch-branch <name>${l.reset}`),console.log(`${l.dim}Available: ${Object.keys(ze.branches).join(", ")}${l.reset}`),!0;try{s.switchBranch(ze,a);let c=s.getActiveMessages(ze);i(c),console.log(`${l.green}Switched to branch "${a}" (${c.length} messages)${l.reset}`)}catch(c){console.log(`${l.red}${c.message}${l.reset}`)}return!0}case"/delete-branch":{let s=Ms();if(!ze){let{getConversationMessages:i}=Ee();ze=s.initTree({messages:i()})}let r=o.join(" ").trim();if(!r)return console.log(`${l.red}Usage: /delete-branch <name>${l.reset}`),!0;try{s.deleteBranch(ze,r),console.log(`${l.green}Deleted branch "${r}"${l.reset}`)}catch(i){console.log(`${l.red}${i.message}${l.reset}`)}return!0}case"/remember":{let{remember:s}=Rn(),r=o.join(" ").trim();if(!r)return console.log(`${l.red}Usage: /remember <key>=<value> or /remember <text>${l.reset}`),!0;let i=r.indexOf("="),a,c;return i>0?(a=r.substring(0,i).trim(),c=r.substring(i+1).trim()):(a=r.substring(0,40).replace(/\s+/g,"-"),c=r),s(a,c),console.log(`${l.green}Remembered: ${a}${l.reset}`),!0}case"/forget":{let{forget:s}=Rn(),r=o.join(" ").trim();return r?(s(r)?console.log(`${l.green}Forgotten: ${r}${l.reset}`):console.log(`${l.red}Memory not found: ${r}${l.reset}`),!0):(console.log(`${l.red}Usage: /forget <key>${l.reset}`),!0)}case"/memory":{let{listMemories:s}=Rn(),r=s();if(r.length===0)return console.log(`${l.dim}No memories saved${l.reset}`),!0;console.log(`
|
|
1794
1797
|
${l.bold}${l.cyan}Memory:${l.reset}`);for(let i of r)console.log(` ${l.cyan}${i.key}${l.reset} = ${i.value}`);return console.log(),!0}case"/brain":{let{listDocuments:s,readDocument:r,writeDocument:i,removeDocument:a,buildIndex:c,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=Zr(),p=o[0],m=o.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}
|
|
1795
1798
|
|
|
@@ -1807,7 +1810,7 @@ ${l.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \
|
|
|
1807
1810
|
`);else{console.log(`
|
|
1808
1811
|
${l.bold}${l.cyan}Brain: ${h.length} document(s)${l.reset}`);for(let g of h){let{frontmatter:y}=r(g.name),w=Array.isArray(y.tags)?` [${y.tags.join(", ")}]`:"";console.log(` ${l.cyan}${g.name}${l.reset}${l.dim}${w}${l.reset}`)}console.log(`
|
|
1809
1812
|
${l.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${l.reset}
|
|
1810
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:s,learnBrainFromSession:r}=
|
|
1813
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:s,learnBrainFromSession:r}=Of(),{getConversationMessages:i}=Ee(),a=i(),c=a.filter(u=>u.role==="user").length;if(c<4)return console.log(`${l.yellow}Session too short to learn from (need 4+ user messages, have ${c})${l.reset}`),!0;console.log(`${l.dim}Analyzing session for learnings...${l.reset}`);try{let[u,d]=await Promise.all([s(a),r(a)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${l.dim}Session too short${l.reset}`),!0;u.error&&console.log(`${l.red}Reflection error: ${u.error}${l.reset}`),console.log(""),u.summary&&(console.log(`${l.bold}Session:${l.reset} ${l.dim}${u.summary}${l.reset}`),console.log(""));let f=u.applied&&u.applied.length>0,p=u.nexAdded&&u.nexAdded.length>0,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:y}of u.applied){let w=y==="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:y}of d.written){let w=y==="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:s}=Ee(),{getUsage:r}=en(),{TOOL_DEFINITIONS:i}=Sn(),{listMemories:a}=Rn(),c=s(),u=r(c,i),d=gs(),f=ko(),p=a();console.log(`
|
|
1811
1814
|
${l.bold}${l.cyan}Optimization Report${l.reset}
|
|
1812
1815
|
`);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(`
|
|
1813
1816
|
${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 S=[...p].sort((C,q)=>new Date(q.updatedAt)-new Date(C.updatedAt))[0],k=S?Math.round((Date.now()-new Date(S.updatedAt))/6e4):null,v=k!==null?k<60?`${k}m ago`:`${Math.round(k/60)}h ago`:"?";console.log(` ${l.dim}Latest update: ${v}${l.reset}`),p.length>30&&console.log(` ${l.yellow}\u2192 Many memories (${p.length}) \u2014 consider pruning with /forget${l.reset}`)}console.log(`
|
|
@@ -1916,7 +1919,7 @@ ${l.dim}No deploy configs. Run /init to create .nex/deploy.json${l.reset}
|
|
|
1916
1919
|
`),!0;console.log(`
|
|
1917
1920
|
${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(`
|
|
1918
1921
|
${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}
|
|
1919
|
-
`),!0}case"/init":{let{runServerWizard:s,runDeployWizard:r,setWizardRL:i}=Ob();return i(e),o[0]==="deploy"?await r():await s(),!0}case"/setup":{let{runSetupWizard:s}=
|
|
1922
|
+
`),!0}case"/init":{let{runServerWizard:s,runDeployWizard:r,setWizardRL:i}=Ob();return i(e),o[0]==="deploy"?await r():await s(),!0}case"/setup":{let{runSetupWizard:s}=Sf();return await s({rl:e,force:!0}),!0}case"/benchmark":{try{let y=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(Rt.existsSync(y)){let w=(Date.now()-Rt.statSync(y).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}
|
|
1920
1923
|
`)}}catch{}if(o.includes("--history")){let y=require("os"),w=process.env.NEX_BENCHMARK_HISTORY_DIR||xt.join(y.homedir(),"Coding","nex-code-benchmarks","results");if(!Rt.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 x=Rt.readdirSync(w).filter(k=>k.endsWith(".json")).sort().slice(-7);if(x.length===0){console.log(`${l.yellow}No result files found${l.reset}`);break}console.log(`
|
|
1921
1924
|
${l.bold}${l.cyan}OpenClaw Nightly Results (${x.length}-day trend)${l.reset}
|
|
1922
1925
|
`),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 S=[];for(let k of x)try{let v=JSON.parse(Rt.readFileSync(xt.join(w,k),"utf-8")),C=k.replace(".json",""),q=v.tasks?.length||v.total||0,D=v.tasks?.filter(de=>de.passed||de.score>=.7)?.length||v.passed||0,ee=v.score??v.overall_score??(q>0?Math.round(D/q*100):"N/A"),ue=v.model||v.config?.model||"unknown";S.push({date:C,model:ue,total:q,passed:D,score:ee});let le=typeof ee=="number"?ee>=80?l.green:ee>=60?l.yellow:l.red:l.dim;console.log(` ${C.padEnd(12)} ${ue.substring(0,24).padEnd(25)} ${le}${String(ee).padEnd(8)}${l.reset} ${D}/${q}`)}catch{}if(S.length>=2){let k=S[0].score,v=S[S.length-1].score;if(typeof k=="number"&&typeof v=="number"){let C=v-k,q=C>0?`${l.green}\u25B2 +${C}`:C<0?`${l.red}\u25BC ${C}`:`${l.dim}\u2192 stable`;console.log(`
|
|
@@ -1941,58 +1944,58 @@ ${l.bold}Scenario Benchmark${l.reset} ${l.dim}5 agentic scenarios \xB7 each run
|
|
|
1941
1944
|
`)}}}),!0}case"/trend":{let{showScoreTrend:s}=Ls(),r=parseInt(o[0],10)||10;return s(r),!0}case"/harness-optimization":{let{buildOptimizationReport:s,readHistory:r,readLatestResult:i,readLatestProblematicResult:a,verifyHarnessOptimization:c}=o_(),u=o.indexOf("--last"),d=u!==-1?Math.max(1,parseInt(o[u+1],10)||5):5,f=o.includes("--prompt"),p=r(Nt),m=i(Nt),h=s({latestRun:m,history:p,lastN:d,includePrompt:f});if(console.log(h),o.includes("--verify")){let g=a(Nt);console.log(`${l.dim}Running focused tests and a priority benchmark slice...${l.reset}
|
|
1942
1945
|
`),g?.runId&&g.runId!==m?.runId&&console.log(`${l.dim}Using latest problematic run for verification: ${g.runId}${l.reset}`);let y=-1,w=await c({rootDir:Nt,latestRun:g,onProgress(x){let S=Math.max(0,Math.min(100,Math.round(x.percent||0)));S===y&&x.phase!=="done"||(y=S,console.log(`${l.dim}${String(S).padStart(3)}%${l.reset} ${x.message}`))}});console.log(w.summary)}return console.log(""),!0}case"/orchestrate":{let s=o.join(" ").trim();if(!s)return console.log(`${l.yellow}Usage: /orchestrate <prompt>${l.reset}`),console.log(`${l.dim}Example: /orchestrate fix login bug, update docs, add dark mode${l.reset}`),!0;let{runOrchestrated:r}=yi();return await r(s),!0}case"/bench-orchestrator":{let{runOrchestratorBenchmark:s,printResults:r}=p_(),i=o.find(u=>u.startsWith("--models=")),a=i?i.replace("--models=","").split(",").map(u=>u.trim()):void 0,c=await s({models:a,onProgress:({model:u,scenario:d,done:f,score:p,error:m})=>{f?m?process.stdout.write(` ${l.red}ERR${l.reset}
|
|
1943
1946
|
`):process.stdout.write(` ${l.green}${p}/10${l.reset}
|
|
1944
|
-
`):process.stdout.write(`${l.dim} \u2192 ${u}: ${d}...${l.reset}`)}});return r(c),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:{let s=
|
|
1945
|
-
`).filter(Boolean).slice(-
|
|
1946
|
-
`)}catch{}}function un(){return`${l.bold}${l.cyan}\u203A${l.reset} `}function zi(){if(!global._nexFooter)return;let{isPlanMode:t,getAutonomyLevel:e}=Nn(),{getAutoConfirm:n}=It(),o=[];t()&&o.push("plan");let s=e();s==="semi-auto"&&o.push("semi"),s==="autonomous"&&o.push("auto"),n()&&o.push("always"),global._nexFooter.setStatusInfo({mode:o.join(" \xB7 ")})}var
|
|
1947
|
+
`):process.stdout.write(`${l.dim} \u2192 ${u}: ${d}...${l.reset}`)}});return r(c),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:{let s=LL(t);if(s)return s.agentPrompt&&(Xi._pendingAgentPrompt=s.agentPrompt),!0;{let r=[...Vi,...hl()].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},(y,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 ep=1e3;function tp(){return xt.join(process.cwd(),".nex","repl_history")}function C_(){try{let t=tp();if(Rt.existsSync(t))return Rt.readFileSync(t,"utf-8").split(`
|
|
1948
|
+
`).filter(Boolean).slice(-ep)}catch{}return[]}function pl(t){try{let e=tp(),n=xt.dirname(e);Rt.existsSync(n)||Rt.mkdirSync(n,{recursive:!0}),Rt.appendFileSync(e,t+`
|
|
1949
|
+
`)}catch{}}function un(){return`${l.bold}${l.cyan}\u203A${l.reset} `}function zi(){if(!global._nexFooter)return;let{isPlanMode:t,getAutonomyLevel:e}=Nn(),{getAutoConfirm:n}=It(),o=[];t()&&o.push("plan");let s=e();s==="semi-auto"&&o.push("semi"),s==="autonomous"&&o.push("auto"),n()&&o.push("always"),global._nexFooter.setStatusInfo({mode:o.join(" \xB7 ")})}var np="\x1B[200~",sp="\x1B[201~";function FL(t){return typeof t=="string"&&t.includes(np)}function BL(t){return typeof t=="string"&&t.includes(sp)}function Ki(t){return typeof t!="string"?t:t.split(np).join("").split(sp).join("")}async function UL(){if(!CL("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"),Qf("local:llama3"),!0}catch{return!1}}async function WL(){__=Date.now();try{let{randomBytes:O}=require("crypto");Xf=O(4).toString("hex")}catch{Xf=Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")}let{setAbortSignalGetter:t,getConversationLength:e,processInput:n}=Ee();t(v_);let s=Zf().some(O=>O.configured),r=(async()=>{PL();let O=gs(),R=ko();return{model:O,providerName:R}})(),i=(async()=>s?!0:await UL()?(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}
|
|
1947
1950
|
`),!0):!1)(),a=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:O}=g_();return await O()}catch{return{hasNewVersion:!1}}})(),[c,u,d]=await Promise.all([r,i,a]);!u&&!s&&(console.error(`
|
|
1948
1951
|
${l.red}\u2717 No provider configured and no local Ollama detected.${l.reset}
|
|
1949
|
-
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:p}=rs();f().then(O=>{}),p().catch(()=>{});let m=C_(),h=
|
|
1952
|
+
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:p}=rs();f().then(O=>{}),p().catch(()=>{});let m=C_(),h=kL.createInterface({input:process.stdin,output:process.stdout,prompt:un(),completer:E_,history:m,historySize:ep});IL(h);let{setAskUserHandler:g}=Sn();g(async(O,R)=>{let{T:Q}=Lt(),N=Q.reset,U=Q.bold,F=Q.dim,pe=Q.cyan,qe=Q.yellow;return process.stdout.write(`
|
|
1950
1953
|
${U}${qe}\u2753${N} ${U}${O}${N}
|
|
1951
1954
|
|
|
1952
1955
|
`),R.forEach((Ie,Pt)=>{process.stdout.write(` ${pe}${Pt+1}${N} ${Ie}
|
|
1953
1956
|
`)}),process.stdout.write(` ${F}${R.length+1}${N} ${F}Eigene Antwort\u2026${N}
|
|
1954
1957
|
`),process.stdout.write(`
|
|
1955
|
-
${pe}[1-${R.length+1}]${N} \u203A `),new Promise(Ie=>{h.resume(),h.once("line",Pt=>{let Je=Pt.trim(),
|
|
1956
|
-
`),Ie(R[
|
|
1958
|
+
${pe}[1-${R.length+1}]${N} \u203A `),new Promise(Ie=>{h.resume(),h.once("line",Pt=>{let Je=Pt.trim(),ot=parseInt(Je);ot>=1&&ot<=R.length?(process.stdout.write(`
|
|
1959
|
+
`),Ie(R[ot-1])):ot===R.length+1||Je===""?(process.stdout.write(` ${pe}\u203A${N} `),h.once("line",Pe=>{process.stdout.write(`
|
|
1957
1960
|
`),Ie(Pe.trim()||"")})):(process.stdout.write(`
|
|
1958
|
-
`),Ie(Je))})})});let y=new
|
|
1959
|
-
`),await x_(Nt),setTimeout(()=>{try{if(
|
|
1960
|
-
`)}}catch{}},2e3);let x=!1,S=0,k=!1,v=null;function C(){b_();let O=[];try{let{getConversationMessages:R}=Ee();O=R(),
|
|
1961
|
+
`),Ie(Je))})})});let y=new qL;y.activate(h),global._nexFooter=y,global._nexRawWrite=O=>y.rawWrite(O),DL(()=>zi()),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}`;SL(w,Nt,{yolo:Vf(),gemini:!!process.env.NEX_FORCE_MODEL&&c.providerName==="gemini"});{y.setStatusInfo({model:w,branch:"",project:xt.basename(Nt)});let{execFile:O}=require("child_process");O("git",["rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"},(R,Q)=>{!R&&Q&&y.setStatusInfo({model:w,branch:Q.trim(),project:xt.basename(Nt)})})}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}
|
|
1962
|
+
`),await x_(Nt),setTimeout(()=>{try{if(OL()){let{insights:O}=ML();O.length>0&&NL()&&process.stdout.write(`${l.dim}\u{1F4AD} Dream consolidated ${O.length} insight(s) from recent sessions${l.reset}
|
|
1963
|
+
`)}}catch{}},2e3);let x=!1,S=0,k=!1,v=null;function C(){b_();let O=[];try{let{getConversationMessages:R}=Ee();O=R(),AL(O)}catch{}y.deactivate(),w_(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l");try{let{showGoodbyeScreen:R}=$_();R({startTime:__,sessionId:Xf||"--------",messages:O})}catch{process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J")}process.exit(0)}process.on("SIGTERM",C),process.on("exit",()=>{b_()}),h.on("SIGINT",()=>{if(w_(),S++,S>=2){C();return}if(x){Fn&&Fn.abort();let{cancelPendingAskUser:O}=Sn();O(),console.log(`
|
|
1961
1964
|
${l.yellow} Task cancelled. Press Ctrl+C again to exit.${l.reset}`),x=!1,h.setPrompt(un()),h.prompt()}else console.log(`${l.dim} (Press Ctrl+C again to exit)${l.reset}`),h.setPrompt(un()),h.prompt(),v&&clearTimeout(v),v=setTimeout(()=>{S=0,v=null},2e3)}),process.on("SIGINT",()=>{process.stdin.isTTY?(S++,S>=2&&C()):C()});let q=!1,D=[],ee=0,ue={},le=!1;function de(){let O=D.join(`
|
|
1962
1965
|
`).replace(/\r/g,"").trim();if(D=[],q=!1,!O)return!0;ee++,le=!0;let R=ee;ue[R]=O;let Q=O.split(`
|
|
1963
|
-
`).length,N=Q>1?`[Pasted content #${R} \u2014 ${Q} lines]`:`[Pasted content #${R}]`,U=h.line||"",F=U&&!U.endsWith(" ")?" ":"",pe=U+F+N;return h.setPrompt(un()),h.prompt(),h.line=pe,h.cursor=pe.length,h._refreshLine(),!0}function M(O){return O.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(R,Q)=>ue[Number(Q)]||"")}function G(){ee=0,ue={},le=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let O=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(R,...Q){if(R!=="data")return O.call(process.stdin,R,...Q);let N=Q[0];if(Buffer.isBuffer(N)&&(N=N.toString("utf8")),typeof N!="string")return O.call(process.stdin,R,...Q);let U=N.includes(
|
|
1966
|
+
`).length,N=Q>1?`[Pasted content #${R} \u2014 ${Q} lines]`:`[Pasted content #${R}]`,U=h.line||"",F=U&&!U.endsWith(" ")?" ":"",pe=U+F+N;return h.setPrompt(un()),h.prompt(),h.line=pe,h.cursor=pe.length,h._refreshLine(),!0}function M(O){return O.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(R,Q)=>ue[Number(Q)]||"")}function G(){ee=0,ue={},le=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let O=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(R,...Q){if(R!=="data")return O.call(process.stdin,R,...Q);let N=Q[0];if(Buffer.isBuffer(N)&&(N=N.toString("utf8")),typeof N!="string")return O.call(process.stdin,R,...Q);let U=N.includes(np),F=N.includes(sp);if(U&&F){let pe=Ki(N);return pe&&D.push(...pe.split(`
|
|
1964
1967
|
`)),de()}if(U){q=!0,D=[];let pe=Ki(N);return pe&&D.push(...pe.split(`
|
|
1965
1968
|
`)),!0}if(F){let pe=Ki(N);return pe&&D.push(...pe.split(`
|
|
1966
1969
|
`)),de()}if(q){let pe=Ki(N);return pe&&D.push(...pe.split(`
|
|
1967
1970
|
`)),!0}return N.includes(`
|
|
1968
1971
|
`)&&N.length>40&&!q?(D.push(...N.replace(/\r/g,"").split(`
|
|
1969
|
-
`)),de()):O.call(process.stdin,R,...Q)}}let te=0,ge=-1,xe=[],Ne="";function Ae(){if(te>0){let O=y._scrollEnd,R="\x1B7";for(let Q=0;Q<te;Q++)R+=`\x1B[${O-te+1+Q};1H\x1B[2K`;R+="\x1B8",y.rawWrite(R),te=0}}function ke(){Ae(),ge=-1,xe=[],Ne=""}function E(O,R=-1){let Q=[...Vi,...hl()].filter(Je=>Je.cmd.startsWith(O));if(!Q.length||Q.length===1&&Q[0].cmd===O&&R<0)return;let N=y._scrollEnd,U=Math.min(10,N-2);if(U<1)return;let F=Q.slice(0,U),pe=Math.max(...F.map(Je=>Je.cmd.length));te=F.length,xe=Q,Ne=O,Q.length>U&&te++;let qe=N-te+1,Ie="\x1B7",Pt=(y._cols||80)-1;for(let Je=0;Je<F.length;Je++){let{cmd:
|
|
1972
|
+
`)),de()):O.call(process.stdin,R,...Q)}}let te=0,ge=-1,xe=[],Ne="";function Ae(){if(te>0){let O=y._scrollEnd,R="\x1B7";for(let Q=0;Q<te;Q++)R+=`\x1B[${O-te+1+Q};1H\x1B[2K`;R+="\x1B8",y.rawWrite(R),te=0}}function ke(){Ae(),ge=-1,xe=[],Ne=""}function E(O,R=-1){let Q=[...Vi,...hl()].filter(Je=>Je.cmd.startsWith(O));if(!Q.length||Q.length===1&&Q[0].cmd===O&&R<0)return;let N=y._scrollEnd,U=Math.min(10,N-2);if(U<1)return;let F=Q.slice(0,U),pe=Math.max(...F.map(Je=>Je.cmd.length));te=F.length,xe=Q,Ne=O,Q.length>U&&te++;let qe=N-te+1,Ie="\x1B7",Pt=(y._cols||80)-1;for(let Je=0;Je<F.length;Je++){let{cmd:ot,desc:Pe}=F[Je],Tr=Math.max(0,pe-ot.length+2),Ji=2+ot.length+Tr,Ze=Pe;if(Ji+Pe.length>Pt){let Ro=Math.max(0,Pt-Ji-3);Ro>0?Ze=Pe.substring(0,Ro)+"...":(Ze="",Tr=1)}let Zi=" ".repeat(Tr);if(Je===R)Ie+=`\x1B[${qe+Je};1H\x1B[2K \x1B[7m ${l.bold}${ot}${l.reset}\x1B[7m${Zi}${Ze}\x1B[27m${l.reset}`;else{let Ro=ot.substring(0,O.length),Qi=ot.substring(O.length);Ie+=`\x1B[${qe+Je};1H\x1B[2K ${l.cyan}${Ro}${l.reset}${l.dim}${Qi}${Zi}${Ze}${l.reset}`}}Q.length>U&&(Ie+=`\x1B[${qe+F.length};1H\x1B[2K ${l.dim}\u2026 +${Q.length-U} more${l.reset}`),Ie+="\x1B8",y.rawWrite(Ie)}if(process.stdin.isTTY){let O=h._ttyWrite.bind(h),R=!1;h._ttyWrite=function(Q,N){if(R)return O(Q,N);if(te>0&&N&&!N.ctrl&&!N.meta){let U=Math.min(xe.length,10)-1;if(N.name==="down"){ge=Math.min(ge+1,U),R=!0,h.write(null,{ctrl:!0,name:"u"}),h.write(ge>=0?xe[ge].cmd:Ne),R=!1,Ae(),E(Ne,ge);return}if(N.name==="up"){if(ge===-1)ge=Math.min(xe.length,10)-1;else if(ge>0)ge--;else{ge=-1,R=!0,h.write(null,{ctrl:!0,name:"u"}),h.write(Ne),R=!1,Ae(),E(Ne,-1);return}R=!0,h.write(null,{ctrl:!0,name:"u"}),h.write(xe[ge].cmd),R=!1,Ae(),E(Ne,ge);return}}return O(Q,N)},process.stdin.on("keypress",(Q,N)=>{te>0&&N&&(N.name==="down"||N.name==="up")||(ke(),!(N&&(N.name==="tab"||N.name==="return"))&&setImmediate(()=>{h.line&&h.line.startsWith("/")&&E(h.line,-1)}))})}let P=null,W=`${l.dim}...${l.reset} `;function oe(O){return(O.match(/[^\s\d](\d{1,2})\.\s+\S/g)||[]).length<2?O:O.replace(/([^\s\d])(\d{1,2})\.\s+/g,(Q,N,U)=>`${N}
|
|
1970
1973
|
${U}. `).trim()}h.setPrompt(un()),h.prompt(),h.on("line",async O=>{if(ke(),Object.keys(ue).length>0&&(O=M(O),G(),h.setPrompt(un())),x){let U=O.trim();if(U){let{injectMidRunNote:F}=Ee();F(U),process.stdout.write(`${l.cyan} \u270E Queued \u2014 will be applied in the next step${l.reset}
|
|
1971
1974
|
`),h.prompt()}return}if(P!==null){if(P._mode==="triple"){if(O.trim()==='"""'){let U=P.join(`
|
|
1972
1975
|
`).trim();if(P=null,U){pl(U.replace(/\n/g,"\\n")),x=!0,h.prompt(),S=0,k=!1,v&&(clearTimeout(v),v=null),Fn=new AbortController;try{await n(U)}catch(pe){if(!Fn?.signal?.aborted){let qe=pe.message?.split(`
|
|
1973
1976
|
`)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${qe}${l.reset}`)}}x=!1;let F=Q();F>0&&process.stdout.write(`${l.gray}[${F} messages] ${l.reset}`)}h.setPrompt(un()),h.prompt();return}P.push(O),h.setPrompt(W),h.prompt();return}if(O.endsWith("\\"))P.push(O.slice(0,-1));else{P.push(O);let U=P.join(`
|
|
1974
1977
|
`).trim();if(P=null,U){pl(U.replace(/\n/g,"\\n")),x=!0,h.prompt(),S=0,k=!1,v&&(clearTimeout(v),v=null),Fn=new AbortController;try{await n(U)}catch(qe){if(!Fn?.signal?.aborted){let Ie=qe.message?.split(`
|
|
1975
1978
|
`)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${Ie}${l.reset}`)}}let{getConversationLength:F}=Ee();x=!1;let pe=F();pe>0&&process.stdout.write(`${l.gray}[${pe} messages] ${l.reset}`)}h.setPrompt(un()),h.prompt();return}h.setPrompt(W),h.prompt();return}if(O.trim()==='"""'||O.trim().startsWith('"""')){let U=O.trim().substring(3);P=U?[U]:[],P._mode="triple",h.setPrompt(W),h.prompt();return}if(O.endsWith("\\")){P=[O.slice(0,-1)],P._mode="backslash",h.setPrompt(W),h.prompt();return}let R=oe(O.trim());if(!R){h.setPrompt(un()),h.prompt();return}if(pl(R),R==="/"){k_(),h.setPrompt(un()),h.prompt();return}if(R.startsWith("/")){await Xi(R,h);let U=Xi._pendingAgentPrompt;if(U){Xi._pendingAgentPrompt=null;try{let{isPlanMode:F,setPlanMode:pe}=Nn(),{invalidateSystemPromptCache:qe}=Ee();F()&&(pe(!1),qe())}catch{}x=!0,h.prompt(),S=0,k=!1,v&&(clearTimeout(v),v=null),Fn=new AbortController;try{await n(U,null,{autoOrchestrate:!1,skipPhaseRouting:!0,skillLoop:!0,maxIterations:200})}catch(F){if(!Fn?.signal?.aborted){let pe=F.message?.split(`
|
|
1976
|
-
`)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${pe}${l.reset}`)}}x=!1}h.setPrompt(un()),h.prompt();return}{let U=
|
|
1977
|
-
`);process.stdout.isTTY&&process.stdout.write(`\x1B[${pe.length}A`),pe.forEach((qe,Ie)=>{let Pt=Ie===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",Je=2+qe.length,
|
|
1978
|
-
`)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${F}${l.reset}`)}}x=!1;let{getConversationLength:Q}=Ee(),N=Q();N>0&&process.stdout.write(`${l.gray}[${N} messages] ${l.reset}`),h.setPrompt(un()),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)})}A_.exports={startREPL:
|
|
1979
|
-
`)}function
|
|
1980
|
-
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=It(),n=new Map,o=0;e((a,c)=>{let u="cfm-"+ ++o,d=c?.toolName||"",f=!1;try{let{isCritical:p}=It();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 s=null,r={onToken(a){s&&So({type:"token",id:s,text:a})},onThinkingToken(){},onToolStart(a,c){s&&So({type:"tool_start",id:s,tool:a,args:c||{}})},onToolEnd(a,c,u){s&&So({type:"tool_end",id:s,tool:a,summary:c||"",ok:!!u})}},i=
|
|
1979
|
+
`)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${pe}${l.reset}`)}}x=!1}h.setPrompt(un()),h.prompt();return}{let U=EL?"\x1B[48;5;237m":"\x1B[48;2;220;225;235m",F=process.stdout.columns||80,pe=R.split(`
|
|
1980
|
+
`);process.stdout.isTTY&&process.stdout.write(`\x1B[${pe.length}A`),pe.forEach((qe,Ie)=>{let Pt=Ie===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",Je=2+qe.length,ot=" ".repeat(Math.max(0,F-Je));console.log(`\x1B[2K${U}${Pt} ${qe}${ot}\x1B[0m`)}),console.log()}if(process.env.NEX_AUTO_PLAN!=="0"&&!Vf()){let{isPlanMode:U,setPlanMode:F}=Nn(),{invalidateSystemPromptCache:pe}=Ee(),qe=/\b(implement|refactor|migrate|redesign)\b/i,Ie=/\b(create|build|add|write|develop|set\s+up)\b/i,Pt=/^(how|what|why|when|where|which|explain|show|list|tell|describe|can\s+you|could\s+you|do\s+you)\b/i,Je=/^(hi|hello|hey|yo)\b/i.test(R)||/\b(introduce yourself|who are you|what can you do|tell me about yourself)\b/i.test(R),ot=/\b(spawn[_\s]?agents?|swarm)\b/i;!Je&&!Pt.test(R)&&!ot.test(R)&&(qe.test(R)||Ie.test(R)&&R.split(/\s+/).length>=5)&&!U()&&(F(!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:U}=Ee();if(U()===0)try{let{detectCategory:F,getModelForCategory:pe}=Xn(),qe=F(R);if(qe&&qe.id!=="coding"){let Ie=pe(qe.id),Pt=gs();if(Ie&&Ie!==Pt?.id&&Qf(Ie)){let Je=gs();console.log(`${l.dim}\u21B3 ${qe.icon} ${qe.label} task \u2014 routing to ${Je?.name||Ie}${l.reset}`),global._nexFooter&&global._nexFooter.setStatusInfo({model:Je?.name||Ie})}}}catch{}}x=!0,h.prompt(),S=0,k=!1,v&&(clearTimeout(v),v=null),Fn=new AbortController;try{await n(R)}catch(U){if(!Fn?.signal?.aborted){let F=U.message?.split(`
|
|
1981
|
+
`)[0]||"An unexpected error occurred";console.log(`${l.red}Error: ${F}${l.reset}`)}}x=!1;let{getConversationLength:Q}=Ee(),N=Q();N>0&&process.stdout.write(`${l.gray}[${N} messages] ${l.reset}`),h.setPrompt(un()),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)})}A_.exports={startREPL:WL,getPrompt:un,loadHistory:C_,appendHistory:pl,getHistoryPath:tp,HISTORY_MAX:ep,showCommandList:k_,completer:E_,completeFilePath:S_,handleSlashCommand:Xi,showProviders:Jf,showHelp:T_,renderBar:R_,hasPasteStart:FL,hasPasteEnd:BL,stripPasteSequences:Ki,getAbortSignal:v_}});var M_=X(($j,O_)=>{"use strict";var HL=require("readline");function So(t){process.stdout.write(JSON.stringify(t)+`
|
|
1982
|
+
`)}function GL(){process.env.NEX_SERVER="1";let t=(...a)=>process.stderr.write(a.map(String).join(" ")+`
|
|
1983
|
+
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=It(),n=new Map,o=0;e((a,c)=>{let u="cfm-"+ ++o,d=c?.toolName||"",f=!1;try{let{isCritical:p}=It();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 s=null,r={onToken(a){s&&So({type:"token",id:s,text:a})},onThinkingToken(){},onToolStart(a,c){s&&So({type:"tool_start",id:s,tool:a,args:c||{}})},onToolEnd(a,c,u){s&&So({type:"tool_end",id:s,tool:a,summary:c||"",ok:!!u})}},i=HL.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();s=d;let{processInput:f}=Ee();try{await f(u.text,r),So({type:"done",id:d})}catch(p){So({type:"error",id:d,message:p?.message||String(p)})}finally{s=null}break}case"confirm":{let d=n.get(u.id);d&&(n.delete(u.id),d(!!u.answer));break}case"cancel":{for(let[d,f]of n)n.delete(d),f(!1);break}case"clear":{let{clearConversation:d}=Ee();d();for(let[f,p]of n)n.delete(f),p(!1);break}default:break}}),i.on("close",()=>{process.exit(0)})}O_.exports={startServerMode:GL}});var j_=X((wj,I_)=>{"use strict";var Eo=require("fs"),rp=require("path"),YL=require("https"),{execSync:ip}=require("child_process"),zL=5*1024*1024;function N_(t){let e=t.match(/^\*\/(\d+) \* \* \* \*$/);if(e){let o=parseInt(e[1],10);if(o>0)return{intervalMs:o*60*1e3,initialDelayMs:0}}let n=t.match(/^0 (\d+) \* \* \*$/);if(n){let o=parseInt(n[1],10),s=new Date,r=new Date;return r.setHours(o,0,0,0),r<=s&&r.setDate(r.getDate()+1),{intervalMs:1440*60*1e3,initialDelayMs:r.getTime()-s.getTime()}}return null}function ap(t,e){return t.replace(/\{(\w+)\}/g,(n,o)=>e[o]!==void 0?e[o]:n)}function P_(t,e){if(t)try{let n=rp.resolve(t),o=rp.dirname(n);Eo.existsSync(o)||Eo.mkdirSync(o,{recursive:!0});try{Eo.statSync(n).size>zL&&Eo.truncateSync(n,0)}catch{}Eo.appendFileSync(n,JSON.stringify(e)+`
|
|
1981
1984
|
`,"utf-8")}catch(n){process.stderr.write(`[daemon] log write error: ${n.message}
|
|
1982
|
-
`)}}function
|
|
1983
|
-
`)}finally{i()}let d=Date.now()-a;P_(n,{ts:new Date().toISOString(),trigger:s,task:t.slice(0,200),status:c,error:u,durationMs:d});let f=c==="ok"?`Task completed in ${d}ms`:`Task failed: ${u}`;
|
|
1984
|
-
`),null}}function
|
|
1985
|
-
`),null;let{intervalMs:i,initialDelayMs:a}=r,c=async()=>{await
|
|
1985
|
+
`)}}function KL(t,e){if(process.platform==="darwin")try{let n=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),o=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');ip(`osascript -e 'display notification "${n}" with title "${o}"'`,{stdio:"ignore"})}catch{}}function L_(t){let e=process.env.NEX_MATRIX_URL,n=process.env.NEX_MATRIX_TOKEN,o=process.env.NEX_MATRIX_ROOM;if(!(!e||!n||!o))try{let s=JSON.stringify({msgtype:"m.text",body:t}),r=Date.now(),i=`${e}/_matrix/client/r0/rooms/${encodeURIComponent(o)}/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(s)}},u=YL.request(c);u.on("error",()=>{}),u.write(s),u.end()}catch{}}function XL(t,e,n){Array.isArray(t)&&(t.includes("desktop")&&KL(e,n),t.includes("matrix")&&L_(`[nex daemon] ${e}: ${n}`))}async function cp(t,e,n,o,s){let{processInput:r,clearConversation:i}=Ee(),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 (${s}): ${p.message}
|
|
1986
|
+
`)}finally{i()}let d=Date.now()-a;P_(n,{ts:new Date().toISOString(),trigger:s,task:t.slice(0,200),status:c,error:u,durationMs:d});let f=c==="ok"?`Task completed in ${d}ms`:`Task failed: ${u}`;XL(o,`nex daemon (${s})`,f)}function VL(t,e){let n=t.replace(/\\/g,"/");return e.some(o=>{let s=o.replace(/^\.\//,"");if(s.endsWith("/**")){let r=s.slice(0,-3);return n===r||n.startsWith(r+"/")}if(s.startsWith("**/")){let r=s.slice(3);return n===r||n.endsWith("/"+r)}return n===s})}function JL(t,e,n){let{ignore:o=[],task:s,debounceMs:r=2e3,auto:i=!0}=t,a=new Set,c=null,u=async()=>{let f=[...a];a.clear();let p=ap(s,{changedFile:f[0]||"",changedFiles:f.join(", ")});await cp(p,i,e.logFile,e.notify,"file-change")},d=(f,p)=>{if(!p)return;let m=p.replace(/\\/g,"/");VL(m,o)||(a.add(m),clearTimeout(c),c=setTimeout(u,r))};try{return Eo.watch(n,{recursive:!0},d)}catch(f){return process.stderr.write(`[daemon] file-change watcher error: ${f.message}
|
|
1987
|
+
`),null}}function ZL(t,e,n){let{task:o,debounceMs:s=0,auto:r=!0}=t,i=()=>{try{return ip("git log --format=%H -1",{cwd:n,encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}},a=()=>{try{return ip("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=ap(o,{commitHash:d,commitMessage:f});await cp(m,r,e.logFile,e.notify,"git-commit")};s>0?setTimeout(p,s):await p()},1e4)}function QL(t,e){let{cron:n,task:o,auto:s=!0}=t,r=N_(n);if(!r)return process.stderr.write(`[daemon] unsupported cron syntax: "${n}" \u2014 skipping
|
|
1988
|
+
`),null;let{intervalMs:i,initialDelayMs:a}=r,c=async()=>{await cp(o,s,e.logFile,e.notify,"schedule")};return a>0?setTimeout(()=>{c(),setInterval(c,i)},a):setInterval(c,i)}async function eI(t,e={}){let n=e.cwd||process.cwd(),o=rp.resolve(n,t),s;try{let u=Eo.readFileSync(o,"utf-8");s=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: ${o}
|
|
1986
1989
|
|
|
1987
1990
|
Create .nex/daemon.json with this example:
|
|
1988
1991
|
${d}
|
|
1989
1992
|
`),new Error(`Config file not found: ${o}`)}throw new Error(`Failed to load daemon config: ${u.message}`)}if(!s.triggers||!Array.isArray(s.triggers))throw new Error("daemon.json must have a 'triggers' array");let r={"file-change":0,"git-commit":0,schedule:0};for(let u of s.triggers)u.on in r&&r[u.on]++;let i=[];r["file-change"]>0&&i.push(`${r["file-change"]} file-change trigger${r["file-change"]>1?"s":""}`),r["git-commit"]>0&&i.push(`${r["git-commit"]} git-commit trigger${r["git-commit"]>1?"s":""}`),r.schedule>0&&i.push(`${r.schedule} schedule trigger${r.schedule>1?"s":""}`),process.stdout.write(`nex daemon started \xB7 config: ${t}
|
|
1990
1993
|
watching: ${i.join(", ")||"no triggers"}
|
|
1991
1994
|
press Ctrl+C to stop
|
|
1992
|
-
`);let a=[];for(let u of s.triggers){let d=null;switch(u.on){case"file-change":d=
|
|
1995
|
+
`);let a=[];for(let u of s.triggers){let d=null;switch(u.on){case"file-change":d=JL(u,s,n);break;case"git-commit":d=ZL(u,s,n);break;case"schedule":d=QL(u,s);break;default:process.stderr.write(`[daemon] unknown trigger type: ${u.on}
|
|
1993
1996
|
`)}d&&a.push(d)}let c=()=>{process.stdout.write(`
|
|
1994
1997
|
[daemon] shutting down...
|
|
1995
|
-
`);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(()=>{})}I_.exports={startDaemon:
|
|
1998
|
+
`);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(()=>{})}I_.exports={startDaemon:eI,parseCronToMs:N_,expandTemplate:ap,appendLog:P_,notifyMatrix:L_}});var q_=X((bj,D_)=>{D_.exports=op()});var yl=require("path"),tI=require("os");require("dotenv").config({path:yl.join(__dirname,"..",".env")});require("dotenv").config({path:yl.join(tI.homedir(),".nex-code",".env"),override:!0});require("dotenv").config();var _e=process.argv.slice(2),fp=_e.includes("--json");(_e.includes("--help")||_e.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
1996
1999
|
|
|
1997
2000
|
Options:
|
|
1998
2001
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -2019,11 +2022,11 @@ Options:
|
|
|
2019
2022
|
--mcp-config <path> Path to MCP server config (default: .nex/mcp.json)
|
|
2020
2023
|
-h, --help Show this help
|
|
2021
2024
|
-v, --version Show version
|
|
2022
|
-
`),process.exit(0));if(_e.includes("-v")||_e.includes("--version")){let t=Po();console.log(t.version),process.exit(0)}var U_=_e.includes("--yolo")||_e.includes("-yolo");if(U_){let{setAutoConfirm:t}=It();t(!0)}if(!U_)try{let t=require("fs"),e=yl.join(process.cwd(),".nex","config.json");if(t.existsSync(e)&&JSON.parse(t.readFileSync(e,"utf-8")).yolo===!0){let{setAutoConfirm:o}=It();o(!0)}}catch{}var
|
|
2023
|
-
`));var
|
|
2024
|
-
`)}var gl=_e.indexOf("--max-turns");if(gl!==-1&&_e[gl+1]){let t=parseInt(_e[gl+1],10);if(t>0){let{setMaxIterations:e}=Ee();e(t)}}else try{let t=require("fs"),e=yl.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let n=JSON.parse(t.readFileSync(e,"utf-8")),o=parseInt(n.maxIterations,10);if(o>0){let{setMaxIterations:s}=Ee();s(o)}}}catch{}var
|
|
2025
|
-
`)}function
|
|
2026
|
-
`).map(n=>n.trim()).filter(Boolean);return e.length===0?"":e[0].replace(/^[│↩]\s*/,"").replace(/\s+/g," ").trim()}function
|
|
2025
|
+
`),process.exit(0));if(_e.includes("-v")||_e.includes("--version")){let t=Po();console.log(t.version),process.exit(0)}var U_=_e.includes("--yolo")||_e.includes("-yolo");if(U_){let{setAutoConfirm:t}=It();t(!0)}if(!U_)try{let t=require("fs"),e=yl.join(process.cwd(),".nex","config.json");if(t.existsSync(e)&&JSON.parse(t.readFileSync(e,"utf-8")).yolo===!0){let{setAutoConfirm:o}=It();o(!0)}}catch{}var nI=_e.indexOf("--gemini-model"),sI=_e.includes("--gemini")||_e.includes("-gemini")||nI!==-1,pp=!sI&&(_e.includes("--flatrate")||!!process.env.OLLAMA_API_KEY&&!process.env.NEX_NO_FLATRATE);pp&&(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"),fp||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
|
|
2026
|
+
`));var lp=_e.indexOf("--model");if(lp!==-1&&_e[lp+1]){let{setActiveModel:t}=Xe();t(_e[lp+1])}var ml=_e.indexOf("--gemini-model"),W_=_e.includes("--gemini")||_e.includes("-gemini")||ml!==-1;if(W_){!process.env.GEMINI_API_KEY&&!process.env.GOOGLE_API_KEY&&(console.error("\x1B[31mError:\x1B[0m --gemini requires GEMINI_API_KEY (or GOOGLE_API_KEY) to be set."),process.exit(1));let t=ml!==-1&&_e[ml+1]?_e[ml+1]:"gemini-3.1-pro-preview";process.env.NEX_FORCE_MODEL=t,process.env.NEX_PHASE_ROUTING="0",process.env.DEFAULT_PROVIDER="gemini",process.env.DEFAULT_MODEL=t,process.env.NEX_FALLBACK_MODEL=t;for(let o of["NEX_ROUTE_CODING","NEX_ROUTE_FRONTEND","NEX_ROUTE_SYSADMIN","NEX_ROUTE_DATA","NEX_ROUTE_AGENTIC","NEX_PHASE_PLAN_MODEL","NEX_PHASE_IMPLEMENT_MODEL","NEX_PHASE_VERIFY_MODEL","OLLAMA_FALLBACK_CHAIN"])delete process.env[o];let{setActiveModel:e}=Xe();e(`gemini:${t}`)||(console.error(`\x1B[31mError:\x1B[0m Unknown Gemini model '${t}'.`),process.exit(1)),fp||process.stderr.write(`\x1B[38;2;138;180;248m\u25C6\x1B[0m \x1B[1mGemini mode\x1B[0m\x1B[2m \u2014 provider=gemini \xB7 model=${t} \xB7 routing locked\x1B[0m
|
|
2027
|
+
`)}var gl=_e.indexOf("--max-turns");if(gl!==-1&&_e[gl+1]){let t=parseInt(_e[gl+1],10);if(t>0){let{setMaxIterations:e}=Ee();e(t)}}else try{let t=require("fs"),e=yl.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let n=JSON.parse(t.readFileSync(e,"utf-8")),o=parseInt(n.maxIterations,10);if(o>0){let{setMaxIterations:s}=Ee();s(o)}}}catch{}var up=_e.indexOf("--mcp-config");up!==-1&&_e[up+1]&&(process.env.NEX_MCP_CONFIG=_e[up+1]);function dp(){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 oI(){let{runSetupWizard:t}=Sf();await t()}function To(t,e=process.stdout.write.bind(process.stdout)){e(JSON.stringify(t)+`
|
|
2028
|
+
`)}function rI(t){return String(t||"").replace(/\x1B\[[0-9;]*m/g,"")}function iI(t){let e=rI(t||"").split(`
|
|
2029
|
+
`).map(n=>n.trim()).filter(Boolean);return e.length===0?"":e[0].replace(/^[│↩]\s*/,"").replace(/\s+/g," ").trim()}function aI(t){return Array.isArray(t)?t.reduce((e,n)=>!n||n.role!=="assistant"?e:Array.isArray(n.tool_calls)?e+n.tool_calls.length:Array.isArray(n.content)?e+n.content.filter(o=>o&&o.type==="tool_use").length:e,0):0}function cI(){process.env.NEX_SERVER="1";let t=process.stdout.write.bind(process.stdout),e={log:console.log,warn:console.warn,info:console.info,error:console.error},n=process.stdout.write,o=process.stderr.write;function s(r,i,a){let c=a;return typeof i=="function"&&(c=i),typeof c=="function"&&c(),!0}return process.stdout.write=s,process.stderr.write=s,console.log=()=>{},console.warn=()=>{},console.info=()=>{},console.error=()=>{},{hooks:{onToken(r){To({type:"token",text:r},t)},onThinkingToken(){To({type:"thinking"},t)},onToolStart(r,i){To({type:"tool_start",tool:r,args:i||{}},t)},onToolEnd(r,i,a){To({type:"tool_end",tool:r,summary:iI(i||""),ok:!!a},t)}},restore(){process.stdout.write=n,process.stderr.write=o,console.log=e.log,console.warn=e.warn,console.info=e.info,console.error=e.error}}}function F_(t){if(_e.includes("--auto")){let{setAutoConfirm:f}=It();f(!0)}if(pp&&gl===-1){let{setMaxIterations:f}=Ee();f(100)}if(!(_e.includes("--model")||W_)){let{setActiveModel:f}=Xe(),p=process.env.HEADLESS_MODEL||"devstral-small-2:24b";f(p)}let n=!_e.includes("--no-auto-orchestrate")&&process.env.NEX_AUTO_ORCHESTRATE!=="false",o=_e.indexOf("--orchestrator-model"),s=o!==-1?_e[o+1]:void 0,r=fp?cI():null,i=r?r.hooks:null;function a(f){if(!r){process.exit(0);return}let{getSessionCosts:p}=xs(),m=f(),h=m.filter(y=>y.role==="assistant").pop(),g=p();r.restore(),To({type:"done",success:!0,response:h?.content||"",usage:{input:g.totalInput||0,output:g.totalOutput||0,cacheRead:g.totalCacheRead||0},toolCalls:aI(m)}),process.exit(0)}function c(f){if(!r){console.error(f.message),process.exit(1);return}r.restore(),To({type:"error",success:!1,error:f?.message||String(f)}),process.exit(1)}if(t.startsWith("/")){let{loadAllSkills:f,handleSkillCommand:p}=is();f();let m=p(t);if(m&&m.agentPrompt){let{processInput:g,getConversationMessages:y}=Ee();g(m.agentPrompt,i,{autoOrchestrate:n,orchestratorModel:s}).then(()=>a(y)).catch(w=>c(w));return}let{handleSlashCommand:h}=op();h(t,null).then(()=>{r&&(r.restore(),To({type:"done",success:!0,response:""})),process.exit(0)}).catch(g=>c(g));return}let{processInput:u,getConversationMessages:d}=Ee();u(t,i,{autoOrchestrate:n,orchestratorModel:s}).then(()=>{try{let{writeDreamLog:f}=Qc();f(d())}catch{}a(d)}).catch(f=>c(f))}if(_e.includes("--server")){let{setAutoConfirm:t}=It();t(!0),M_().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:o}=j_();o(n).catch(s=>{console.error("Daemon error:",s.message),process.exit(1)});return}var B_=_e.indexOf("--prompt-file");if(B_!==-1){let t=_e[B_+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(o){console.error(`--prompt-file: cannot read file: ${o.message}`),process.exit(1)}if(n||(console.error("--prompt-file: file is empty"),process.exit(1)),_e.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}dp(),F_(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)),dp(),_e.includes("--orchestrate")){let n=_e.indexOf("--orchestrator-model"),o=n!==-1?_e[n+1]:void 0,{runOrchestrated:s}=yi();s(e,{orchestratorModel:o}).then(()=>{process.exit(0)}).catch(r=>{console.error(`Orchestrator error: ${r.message}`),process.exit(1)})}else F_(e)}else oI().then(async()=>{if(dp(),pp){let{setMaxIterations:n}=Ee();n(100)}if(_e.includes("--resume")){let{loadSession:n}=Mn(),{setConversationMessages:o}=Ee(),s=n("_autosave");if(s&&s.messages&&s.messages.length>0){let i=s.messages,a=i.length>20?i.slice(-20):i;o(a);let{getUsage:c,forceCompress:u}=en();if(c(a,[]).percentage>=30){let{messages:p}=u(a,[]);o(p)}let{C:f}=He();process.stdout.write(`${f.dim}Session restored (${a.length} messages)${f.reset}
|
|
2027
2030
|
`)}else{let{C:r}=He();process.stdout.write(`${r.yellow}No previous session found.${r.reset}
|
|
2028
2031
|
`)}}let{startREPL:e}=q_();e(),setTimeout(async()=>{try{let{loadKnownModels:n,findNewModels:o}=kr(),s=n(),r=s.lastChecked?new Date(s.lastChecked):null;if((r?(Date.now()-r.getTime())/864e5:999)<7||!process.env.OLLAMA_API_KEY)return;let{newModels:a}=await o();if(a.length>0){let{C:c}=He();process.stdout.write(`
|
|
2029
2032
|
${c.dim}\u{1F4A1} ${a.length} new Ollama Cloud model(s) available \u2014 /benchmark --discover to test them${c.reset}
|