nex-code 0.4.37 → 0.4.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -41
- package/dist/benchmark.js +397 -360
- package/dist/nex-code.js +664 -621
- package/dist/skills/autoresearch.js +252 -18
- package/package.json +3 -6
package/dist/benchmark.js
CHANGED
|
@@ -1,132 +1,132 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`),o=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(o){let r=parseInt(o[1].slice(0,2),16),i=parseInt(o[2].slice(0,2),16),a=parseInt(o[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function
|
|
1
|
+
"use strict";var re=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Es=re((Ek,ul)=>{"use strict";var ol="\x1B[0m",rl="\x1B[1m",Gn="\x1B[2m";function z(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function cm(){if(!process.stdout.isTTY)return null;try{let{execFileSync:t}=require("child_process"),e=["import sys,os,tty,termios,select","f=open('/dev/tty','r+b',buffering=0)","fd=f.fileno()","s=termios.tcgetattr(fd)","try:"," tty.setraw(fd)"," f.write(bytes([0x1b,0x5d,0x31,0x31,0x3b,0x3f,0x1b,0x5c]))"," r=select.select([fd],[],[],0.1)[0]"," d=b''"," if r:"," while True:"," r2=select.select([fd],[],[],0.05)[0]"," if not r2:break"," c=os.read(fd,1)"," d+=c"," if d[-1:]==bytes([0x07]) or d[-2:]==bytes([0x1b,0x5c]):break"," sys.stdout.buffer.write(d)","finally:"," termios.tcsetattr(fd,termios.TCSADRAIN,s)"," f.close()"].join(`
|
|
2
|
+
`),o=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(o){let r=parseInt(o[1].slice(0,2),16),i=parseInt(o[2].slice(0,2),16),a=parseInt(o[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function il(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function lm(t){try{let s=require("fs").readFileSync(il(),"utf8"),n=JSON.parse(s);if(n&&typeof n[t]=="boolean")return n[t]}catch{}return null}function um(t,e){try{let s=require("fs"),n=require("path"),o=il(),r=n.dirname(o),i={};try{i=JSON.parse(s.readFileSync(o,"utf8"))}catch{}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(c=>delete i[c]),s.existsSync(r)||s.mkdirSync(r,{recursive:!0}),s.writeFileSync(o,JSON.stringify(i),"utf8")}catch{}}function dm(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let i=e.split(";"),a=parseInt(i[i.length-1],10);if(!isNaN(a))return a<8}let s=process.env.TERM_SESSION_ID||"default",n=lm(s);if(n!==null)return n;let o=cm(),r=o!==null?o:!0;return um(s,r),r}var al=dm(),cl={reset:ol,bold:rl,dim:Gn,primary:z(80,190,255),secondary:z(60,170,190),success:z(80,210,120),warning:z(245,175,50),error:z(230,80,80),muted:Gn,subtle:z(130,130,145),tool_read:z(80,190,255),tool_write:z(245,165,55),tool_exec:z(185,100,235),tool_search:z(70,185,190),tool_git:z(90,210,100),tool_web:z(100,215,250),tool_sysadmin:z(225,150,75),tool_default:z(100,205,115),syn_keyword:z(185,100,235),syn_string:z(90,210,120),syn_number:z(245,175,50),syn_comment:Gn,syn_key:z(80,190,255),diff_add:z(80,210,120),diff_rem:z(230,80,80),banner_logo:z(80,200,255),banner_name:z(80,200,255),banner_version:Gn,banner_model:Gn,banner_yolo:z(245,175,50),footer_sep:Gn,footer_model:z(80,175,235),footer_branch:z(80,210,100),footer_project:z(130,130,145),footer_divider:z(80,80,95),footer_mode:z(210,150,50),white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",diff_add_bg:"\x1B[48;2;10;46;20m",diff_rem_bg:"\x1B[48;2;58;16;16m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},ll={reset:ol,bold:rl,dim:z(110,110,120),primary:z(0,110,190),secondary:z(0,125,148),success:z(0,148,62),warning:z(168,92,0),error:z(188,32,32),muted:z(110,110,120),subtle:z(155,155,165),tool_read:z(0,110,190),tool_write:z(168,92,0),tool_exec:z(128,42,188),tool_search:z(0,122,148),tool_git:z(0,138,62),tool_web:z(0,112,178),tool_sysadmin:z(168,82,0),tool_default:z(0,138,62),syn_keyword:z(128,42,188),syn_string:z(0,138,62),syn_number:z(168,92,0),syn_comment:z(135,135,148),syn_key:z(0,110,190),diff_add:z(0,148,62),diff_rem:z(188,32,32),banner_logo:z(0,122,205),banner_name:z(0,122,205),banner_version:z(100,100,118),banner_model:z(100,100,118),banner_yolo:z(168,62,0),footer_sep:z(168,168,178),footer_model:z(0,102,175),footer_branch:z(0,138,62),footer_project:z(135,135,148),footer_divider:z(168,168,178),footer_mode:z(148,88,0),white:z(40,40,52),red:z(188,32,32),green:z(0,148,62),yellow:z(168,92,0),blue:z(0,110,190),magenta:z(128,42,188),cyan:z(0,125,148),gray:z(132,132,142),bgRed:"\x1B[41m",bgGreen:"\x1B[42m",diff_add_bg:"\x1B[48;2;215;245;220m",diff_rem_bg:"\x1B[48;2;255;215;215m",brightCyan:z(0,158,182),brightMagenta:z(158,52,208),brightBlue:z(0,112,208)},fm=al?cl:ll;ul.exports={T:fm,isDark:al,DARK:cl,LIGHT:ll}});var Lo=re((Tk,pm)=>{pm.exports={name:"nex-code",version:"0.4.39",description:"Run 400B+ open coding models on your codebase without the hardware bill. Ollama Cloud first \u2014 OpenAI, Anthropic, and Gemini when you need them.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","examples/","README.md","LICENSE"],engines:{node:">=18.0.0"},scripts:{start:"node dist/nex-code.js",build:"node scripts/build.js",dev:"node scripts/build.js --dev",test:"jest --forceExit","test:orchestrator":"jest tests/orchestrator.test.js --forceExit",coverage:"jest --coverage --forceExit","test:watch":"jest --watch",typecheck:"tsc --noEmit",format:"prettier --write .","install-hooks":"ln -sf ../../hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push && ln -sf ../../hooks/post-merge .git/hooks/post-merge && chmod +x .git/hooks/post-merge && echo 'Hooks installed (pre-push, post-merge).'",prepublishOnly:"npm run build && npm test","merge-to-main":"bash scripts/merge-to-main.sh",improve:"node scripts/improve.js","extract-examples":"node scripts/extract-examples.js","benchmark:realworld":"node scripts/benchmark-realworld.js",release:"npm version patch && git push --follow-tags && npm publish"},keywords:["ai","cli","coding","agent","ollama","ollama-cloud","openai","anthropic","gemini","llm","gpt","agentic","terminal","coding-assistant","open-source","free","qwen3","devstral","kimi-k2","deepseek","local-llm","mcp","model-context-protocol","multi-provider"],repository:{type:"git",url:"https://github.com/hybridpicker/nex-code.git"},bugs:{url:"https://github.com/hybridpicker/nex-code/issues"},homepage:"https://github.com/hybridpicker/nex-code#readme",license:"MIT",dependencies:{axios:"^1.7.0",dotenv:"^16.4.0"},devDependencies:{esbuild:"^0.27.3",jest:"^29.7.0",prettier:"^3.8.1",typescript:"^5.9.3"},overrides:{"brace-expansion":">=5.0.5",picomatch:">=4.0.4"},jest:{coverageThreshold:{global:{lines:45,functions:30,branches:35},"./cli/sub-agent.js":{lines:70,functions:60,branches:55}}}}});var zn=re((Rk,fl)=>{var{T:te}=Es(),jo=5,Kn=(()=>{let t=[];for(let e=0;e<jo;e++)t.push(e);for(let e=jo-2;e>=1;e--)t.push(e);return t})(),dl=["\u273D","\u2726","\u2727","\u2726"],ki=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Kn[this.frame%Kn.length],s="";for(let o=0;o<jo;o++)s+=o===e?`${te.cyan}\u25CF${te.reset}`:" ";let n="";if(this.startTime){let o=Math.floor((Date.now()-this.startTime)/1e3);if(o>=60){let r=Math.floor(o/60),i=o%60;n=` ${te.dim}${r}m ${String(i).padStart(2,"0")}s${te.reset}`}else o>=1&&(n=` ${te.dim}${o}s${te.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${te.dim}${this.text}${te.reset}${n}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},vi=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_render(){if(this._stopped)return;let e=Kn[this.frame%Kn.length],s=`${te.cyan}\u25CF${te.reset}`,n=this._formatElapsed(),o=n?` ${te.dim}${n}${te.reset}`:"",r=process.stderr.columns||80,i="";for(let a=0;a<this.labels.length;a++){let c,l;switch(this.statuses[a]){case"done":c=`${te.green}\u2713${te.reset}`,l=te.dim;break;case"error":c=`${te.red}\u2717${te.reset}`,l=te.dim;break;case"retry":c=`${te.yellow}\u21BB${te.reset}`,l=te.yellow;break;default:c=a===e?s:" ",l=""}let u=a===this.labels.length-1?o:"",d=r-4-(u?n.length+1:0),f=this.labels[a].length>d?this.labels[a].substring(0,Math.max(10,d-3))+"...":this.labels[a];i+=`\x1B[2K ${c} ${l}${f}${te.reset}${u}
|
|
3
3
|
`}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
4
4
|
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(e={}){if(this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),!e.silent)this._renderFinal();else{let s="";for(let n=0;n<this.lineCount;n++)s+=`\x1B[2K
|
|
5
|
-
`;this.lineCount>0&&(s+=`\x1B[${this.lineCount}A`),process.stderr.write(s)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${
|
|
6
|
-
`}process.stderr.write(o)}},
|
|
7
|
-
`;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],l=a===0?"\u23BF":" ",u=
|
|
5
|
+
`;this.lineCount>0&&(s+=`\x1B[${this.lineCount}A`),process.stderr.write(s)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${te.dim}${e}${te.reset}`:"",n=process.stderr.columns||80,o="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${te.green}\u2713${te.reset}`;break;case"error":i=`${te.red}\u2717${te.reset}`;break;case"retry":i=`${te.yellow}\u21BB${te.reset}`;break;default:i=`${te.yellow}\u25CB${te.reset}`}let a=r===this.labels.length-1?s:"",c=n-4-(a?e.length+1:0),l=this.labels[r].length>c?this.labels[r].substring(0,Math.max(10,c-3))+"...":this.labels[r];o+=`\x1B[2K ${i} ${te.dim}${l}${te.reset}${a}
|
|
6
|
+
`}process.stderr.write(o)}},Po={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Io={done:te.green,in_progress:te.cyan,pending:te.dim,failed:te.red},Jt=null,Si=class{constructor(e,s){this.name=e,this.tasks=s.map(n=>({id:n.id,description:n.description,status:n.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=dl[this.frame%dl.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${te.dim}(${o})${te.reset}`:"",i=`\x1B[2K${te.cyan}${e}${te.reset} ${this.name}\u2026${r}
|
|
7
|
+
`;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],l=a===0?"\u23BF":" ",u=Po[c.status]||Po.pending,d=Io[c.status]||Io.pending,f=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${te.dim}${l}${te.reset} ${d}${u}${te.reset} ${f}
|
|
8
8
|
`}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
9
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),
|
|
9
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Jt=this}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._paused||this._renderFinal(),process.stderr.write("\x1B[?25h"),this._paused=!1,Jt===this&&(Jt=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
|
|
10
10
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
11
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(a=>a.status==="done").length,n=this.tasks.filter(a=>a.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,i=`\x1B[2K${
|
|
12
|
-
`;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],l=a===0?"\u23BF":" ",u=
|
|
13
|
-
`}process.stderr.write(i)}},
|
|
11
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(a=>a.status==="done").length,n=this.tasks.filter(a=>a.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,i=`\x1B[2K${te.green}\u2714${te.reset} ${this.name} ${te.dim}(${e} \xB7 ${r})${te.reset}
|
|
12
|
+
`;for(let a=0;a<this.tasks.length;a++){let c=this.tasks[a],l=a===0?"\u23BF":" ",u=Po[c.status]||Po.pending,d=Io[c.status]||Io.pending,f=c.description.length>55?c.description.substring(0,52)+"...":c.description;i+=`\x1B[2K ${te.dim}${l}${te.reset} ${d}${u}${te.reset} ${te.dim}${f}${te.reset}
|
|
13
|
+
`}process.stderr.write(i)}},Ei=class{constructor(e,s){this.toolName=e,this.message=s||`Running ${e}...`,this.count=0,this.total=null,this.detail="",this.frame=0,this.interval=null,this.startTime=null,this._stopped=!1}_render(){if(this._stopped||!process.stderr.isTTY)return;let e=Kn[this.frame%Kn.length],s="";for(let r=0;r<jo;r++)s+=r===e?`${te.cyan}\u25CF${te.reset}`:" ";let n=this.message;this.count>0&&(n+=` ${te.cyan}${this.count}${te.reset}`,this.total&&(n+=`/${this.total}`),this.detail&&(n+=` ${te.dim}${this.detail}${te.reset}`));let o="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(o=` ${te.dim}${r}s${te.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${te.dim}${n}${te.reset}${o}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){e.count!==void 0&&(this.count=e.count),e.total!==void 0&&(this.total=e.total),e.detail!==void 0&&(this.detail=e.detail),e.message!==void 0&&(this.message=e.message)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h")}};function hm(t){Jt=t}function mm(){return Jt}function gm(){Jt&&(Jt.stop(),Jt=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}fl.exports={C:te,Spinner:ki,MultiProgress:vi,TaskProgress:Si,ToolProgress:Ei,setActiveTaskProgress:hm,getActiveTaskProgress:mm,cleanupTerminal:gm}});var Ti=re((Ck,gl)=>{"use strict";var ae={kw:"\x1B[34m",str:"\x1B[32m",cmt:"\x1B[90m",num:"\x1B[33m",type:"\x1B[36m",punct:"\x1B[35m",reset:"\x1B[0m"},pl={js:new Set(["const","let","var","function","return","if","else","for","while","do","class","new","this","import","export","from","default","async","await","try","catch","finally","throw","typeof","instanceof","in","of","switch","case","break","continue","null","undefined","true","false","extends","super","static","get","set","delete","void","yield","interface","type","enum","namespace","abstract","implements","declare","module","require","readonly","keyof","infer","never","unknown","any","as","satisfies"]),py:new Set(["def","class","return","if","elif","else","for","while","with","as","import","from","pass","break","continue","try","except","finally","raise","in","not","and","or","is","lambda","yield","global","nonlocal","del","assert","True","False","None","async","await","self","cls","print","range","len","type","list","dict","set","tuple","str","int","float","bool","open","super","property","staticmethod","classmethod"]),sh:new Set(["if","then","else","elif","fi","for","while","do","done","case","esac","in","function","return","local","export","source","echo","exit","break","continue","readonly","unset","shift","trap","read"]),go:new Set(["func","return","if","else","for","range","type","struct","interface","import","package","var","const","defer","go","chan","select","case","default","break","continue","fallthrough","nil","true","false","make","new","len","cap","append","copy","delete","panic","recover","map","error","string","int","int64","int32","uint","bool","byte","rune"]),rs:new Set(["fn","let","mut","return","if","else","for","while","loop","match","use","mod","pub","struct","enum","impl","trait","where","const","static","type","move","ref","in","as","unsafe","extern","crate","self","Self","super","true","false","None","Some","Ok","Err","i32","i64","u32","u64","usize","f32","f64","bool","str","String","Vec"]),java:new Set(["class","interface","extends","implements","import","package","return","if","else","for","while","do","switch","case","break","continue","new","this","super","null","true","false","public","private","protected","static","final","abstract","void","int","long","double","float","boolean","char","byte","short","try","catch","finally","throw","throws","synchronized","volatile","transient","instanceof","enum","record"])},ym={js:"js",jsx:"js",ts:"js",tsx:"js",mjs:"js",cjs:"js",py:"py",css:"css",scss:"css",less:"css",sh:"sh",bash:"sh",zsh:"sh",go:"go",rs:"rs",java:"java",json:"json",html:"html",htm:"html",xml:"xml",md:"md"};function hl(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return ym[e]||null}function $m(t){return t.replace(/"([^"\\]|\\.)*"\s*:/g,e=>ae.type+e+ae.reset).replace(/"([^"\\]|\\.)*"/g,e=>ae.str+e+ae.reset).replace(/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,e=>ae.num+e+ae.reset).replace(/\b(true|false|null)\b/g,e=>ae.kw+e+ae.reset)}function wm(t){return/<!--/.test(t)?t.replace(/<!--[\s\S]*?(?:-->|$)/g,e=>ae.cmt+e+ae.reset):t.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(e,s,n)=>s+ae.type+n+ae.reset).replace(/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(e,s)=>" "+ae.kw+s+ae.reset+"=").replace(/"([^"]*)"/g,e=>ae.str+e+ae.reset)}function bm(t){return t.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,e=>ae.cmt+e+ae.reset).replace(/#[0-9a-fA-F]{3,8}\b/g,e=>ae.num+e+ae.reset).replace(/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(e,s,n)=>ae.num+s+ae.reset+n).replace(/([a-z][a-z-]*)(\s*:)/g,(e,s,n)=>ae.type+s+ae.reset+n).replace(/"[^"]*"|'[^']*'/g,e=>ae.str+e+ae.reset)}function ml(t,e,s){if(e==="json")return $m(t);if(e==="html"||e==="xml")return wm(t);if(e==="css")return bm(t);if(e==="md")return t;let n=pl[e]||pl.js,o="",r=0;if(s.inBlockComment){let i=t.indexOf("*/");if(i===-1)return ae.cmt+t+ae.reset;if(o+=ae.cmt+t.slice(0,i+2)+ae.reset,s.inBlockComment=!1,r=i+2,r>=t.length)return o}if(s.inString==="`"){let i=t.indexOf("`");if(i===-1)return ae.str+t+ae.reset;if(o+=ae.str+t.slice(0,i+1)+ae.reset,s.inString=null,r=i+1,r>=t.length)return o}for(;r<t.length;){let i=t[r];if(!s.inString&&i==="/"&&t[r+1]==="*"){let a=t.indexOf("*/",r+2);if(a===-1)return o+=ae.cmt+t.slice(r)+ae.reset,s.inBlockComment=!0,o;o+=ae.cmt+t.slice(r,a+2)+ae.reset,r=a+2;continue}if(!s.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return o+=ae.cmt+t.slice(r)+ae.reset,o;if(!s.inString&&(i==='"'||i==="'"||i==="`")){s.inString=i,o+=ae.str+i,r++;continue}if(s.inString){if(i==="\\"&&r+1<t.length){o+=i+t[r+1],r+=2;continue}if(i===s.inString){o+=i+ae.reset,s.inString=null,r++;continue}o+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let a="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(a.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)a+=t[r++];o+=ae.num+a+ae.reset;continue}if(i==="@"&&(e==="js"||e==="java"||e==="py")){let a="@";for(r++;r<t.length&&/[a-zA-Z0-9_$.]/.test(t[r]);)a+=t[r++];o+=ae.punct+a+ae.reset;continue}if(/[a-zA-Z_$]/.test(i)){let a="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)a+=t[r++];n.has(a)?o+=ae.kw+a+ae.reset:/^[A-Z][A-Za-z0-9]*$/.test(a)&&e!=="sh"?o+=ae.type+a+ae.reset:o+=a;continue}o+=i,r++}return s.inString&&s.inString!=="`"&&(o+=ae.reset,s.inString=null),o}function _m(t,e){let s=hl(e);if(!s)return t.split(`
|
|
14
14
|
`);let n=t.split(`
|
|
15
|
-
`),o={inString:null,inBlockComment:!1};return n.map(r=>
|
|
15
|
+
`),o={inString:null,inBlockComment:!1};return n.map(r=>ml(r,s,o))}function xm(t,e){return e?ml(t,e,{inString:null,inBlockComment:!1}):t}gl.exports={detectLang:hl,highlightLine:xm,highlightLines:_m}});var wl=re((Ak,$l)=>{var{T:E}=Es(),Ze=E,km={read_file:E.tool_read,list_directory:E.tool_read,write_file:E.tool_write,edit_file:E.tool_write,patch_file:E.tool_write,bash:E.tool_exec,grep:E.tool_search,search_files:E.tool_search,glob:E.tool_search,git_commit:E.tool_git,git_push:E.tool_git,git_pull:E.tool_git,git_status:E.tool_git,git_diff:E.tool_git,git_log:E.tool_git,git_branch:E.tool_git,git_stash:E.tool_git,web_fetch:E.tool_web,web_search:E.tool_web,sysadmin:E.tool_sysadmin,ssh_exec:E.tool_sysadmin,ssh_upload:E.tool_sysadmin,ssh_download:E.tool_sysadmin,deploy:E.tool_sysadmin},Ri={read_file:"Read",write_file:"Write",edit_file:"Edit",patch_file:"Edit",list_directory:"List",bash:"Bash",grep:"Grep",search_files:"Search",glob:"Glob",web_fetch:"WebFetch",web_search:"WebSearch",git_status:"Bash",git_diff:"Bash",git_log:"Bash",git_commit:"Bash",git_push:"Bash",git_pull:"Bash",git_branch:"Bash",git_stash:"Bash",task_list:"TaskList",spawn_agents:"Agent",ask_user:"AskUser",switch_model:"SwitchModel",gh_run_list:"Bash",gh_run_view:"Bash",gh_workflow_trigger:"Bash",browser_open:"Browser",browser_screenshot:"Browser",browser_click:"Browser",browser_fill:"Browser",ssh_exec:"Bash",ssh_upload:"Upload",ssh_download:"Download",service_manage:"Bash",service_logs:"Bash",container_list:"Bash",container_logs:"Bash",container_exec:"Bash",brain_write:"Write",deploy:"Bash",frontend_recon:"Search"};function Do(t,e=!1,s=null){if(e)return`${E.error}\u23FA${E.reset}`;let n=km[t]||E.tool_default;return s==="blink"?`${n}\x1B[5m\u23FA\x1B[25m${E.reset}`:`${n}${s!==null?s:"\u23FA"}${E.reset}`}function vm(t,e,s=!1,n=null){let o=(t||[]).filter(c=>c&&c.canExecute!==!1);if(o.length===0)return`${Do("",s,n)} Step ${e}`;if(o.length===1){let c=o[0],l=c.args||{},u=Ri[c.fnName]||c.fnName.replace(/_/g," "),d="";l.path?d=l.path:l.command?d=String(l.command).substring(0,80):l.query?d=String(l.query).substring(0,60):l.pattern?d=String(l.pattern).substring(0,60):l.url&&(d=String(l.url).substring(0,60));let f=d?`(${Ze.dim}${d}${Ze.reset})`:"";return`${Do(c.fnName,s,n)} ${Ze.bold}${u}${Ze.reset}${f}`}let r=o[0].fnName,i=[...new Set(o.map(c=>Ri[c.fnName]||c.fnName.replace(/_/g," ")))],a=i.length<=3?i.join(", "):`${o.length} tools`;return`${Do(r,s,n)} ${Ze.bold}${a}${Ze.reset}`}function Sm(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=e.path||"";break;case"bash":case"ssh_exec":s=(e.command||"").substring(0,80);break;case"grep":case"search_files":s=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":s=e.pattern||"";break;case"web_fetch":s=(e.url||"").substring(0,60);break;case"web_search":s=(e.query||"").substring(0,50);break;default:s=JSON.stringify(e).substring(0,80)}let n=Ri[t]||t.replace(/_/g," "),o=s?`(${Ze.dim}${s}${Ze.reset})`:"";return`${Do(t)} ${Ze.bold}${n}${Ze.reset}${o}`}function Em(t,e=8){let s=t.split(`
|
|
16
16
|
`),n=s.slice(0,e),o=s.length-e,r=`${E.muted} \u23BF ${E.reset}`,i=" ",a=n.map((c,l)=>`${l===0?r:i}${E.success}${c}${E.reset}`).join(`
|
|
17
17
|
`);return o>0&&(a+=`
|
|
18
|
-
${E.subtle} \u2026 +${o} lines${E.reset}`),a}function
|
|
18
|
+
${E.subtle} \u2026 +${o} lines${E.reset}`),a}var qo=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],yl=Math.floor(Math.random()*qo.length),Ci=null;function Tm(t){Ci=t}function Rm(){let t=qo[yl%qo.length];yl++;let e=Ci?` \xB7 ${Ci}`:"";return`${t}${e}`}function Cm(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading ${e.path||"file"}`;case"list_directory":return`Listing ${e.path||"."}`;case"search_files":return`Searching ${e.pattern||"..."}`;case"glob":return`Searching ${e.pattern||"..."}`;case"grep":return`Searching ${e.pattern||"..."}`;case"web_fetch":return`Fetching ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Checking git status";case"git_diff":return`Diffing${e.file?` ${e.file}`:""}`;case"git_log":return`Reading git log${e.file?` (${e.file})`:""}`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;case"sysadmin":{let s=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${s}: full audit...`;case"disk_usage":return`Sysadmin${s}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${s}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${s}: network status...`;case"ssl_check":return`Sysadmin${s}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${s}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${s}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${s}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${s}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${s}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${s}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${s}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${s}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${s}: cron ${e.cron_action||""}...`;default:return`Sysadmin${s}: ${e.action}...`}}default:return`Running: ${t}`}}function Am(t,e,s,n){let o=String(s||"");if(n){let a=o.split(`
|
|
19
19
|
`)[0];if(a.startsWith("BLOCKED:")){let d=a.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return` ${E.muted}\u23BF blocked: ${d}${E.reset}`}let c=a.replace(/^ERROR:\s*/i,"").substring(0,80),l=o.match(/\nHINT: (.+)/),u=l?`
|
|
20
20
|
${E.muted}${l[1].substring(0,100)}${E.reset}`:"";return` ${E.error}\u23BF ${c}${E.reset}${u}`}let r;switch(t){case"read_file":{let c=o.split(`
|
|
21
|
-
`).filter(Boolean).filter(
|
|
22
|
-
`).length,l=e.path?require("path").basename(e.path):null,u=l?`Wrote ${l} \xB7 ${c} line${c!==1?"s":""}`:`Wrote ${c} line${c!==1?"s":""}`,{highlightLines:d}=
|
|
21
|
+
`).filter(Boolean).filter(m=>!/^File:\s/.test(m)&&!/^\[LARGE FILE:/.test(m)),l=c.length,u=c[c.length-1],d=u?parseInt(u.match(/^(\d+):/)?.[1]||"0"):0,f=e.line_start||e.line_end,h=e.path?require("path").basename(e.path):null,g=h?` ${E.muted}from ${h}${E.reset}`:"";f&&d>l?r=`Read lines ${e.line_start||1}\u2013${d}${g}`:r=`Read ${l} line${l!==1?"s":""}${g}`;break}case"write_file":{let c=(e.content||"").split(`
|
|
22
|
+
`).length,l=e.path?require("path").basename(e.path):null,u=l?`Wrote ${l} \xB7 ${c} line${c!==1?"s":""}`:`Wrote ${c} line${c!==1?"s":""}`,{highlightLines:d}=Ti(),f=d(e.content||"",e.path||null),h=40,g=8;if(c<=h){let m=f.map(b=>` ${b}`).join(`
|
|
23
23
|
`);r=`${u}
|
|
24
|
-
${
|
|
24
|
+
${m}`}else{let m=f.slice(0,g).map(b=>` ${b}`).join(`
|
|
25
25
|
`);r=`${u}
|
|
26
|
-
${
|
|
27
|
-
${E.subtle}\u2026 +${c-
|
|
26
|
+
${m}
|
|
27
|
+
${E.subtle}\u2026 +${c-g} lines${E.reset}`}break}case"edit_file":{let a=(e.old_text||"").split(`
|
|
28
28
|
`),c=(e.new_text||"").split(`
|
|
29
|
-
`),l=a.length,u=c.length,d=e.path?require("path").basename(e.path):null,f=d?` ${E.muted}${d}${E.reset}`:"",h=a.find(
|
|
30
|
-
`+
|
|
29
|
+
`),l=a.length,u=c.length,d=e.path?require("path").basename(e.path):null,f=d?` ${E.muted}${d}${E.reset}`:"",h=a.find(G=>G.trim()),g=c.find(G=>G.trim()),{highlightLine:m,detectLang:b}=Ti(),x=b(e.path||null),j=[];h&&j.push(` ${E.diff_rem}- ${E.reset}${m(h.trimEnd().substring(0,72),x)}${E.reset}`),g&&j.push(` ${E.diff_add}+ ${E.reset}${m(g.trimEnd().substring(0,72),x)}${E.reset}`),r=`${E.diff_rem}\u2212${l}${E.reset} ${E.diff_add}+${u}${E.reset}${f}`+(j.length>0?`
|
|
30
|
+
`+j.join(`
|
|
31
31
|
`):"");break}case"patch_file":{let a=e.patches||[],c=a.reduce((u,d)=>u+(d.old_text||"").split(`
|
|
32
32
|
`).length,0),l=a.reduce((u,d)=>u+(d.new_text||"").split(`
|
|
33
33
|
`).length,0);r=`${E.reset}${a.length} patch${a.length!==1?"es":""} ${E.diff_rem}\u2212${c}${E.reset} ${E.diff_add}+${l}${E.reset}`;break}case"bash":{let c=o.match(/^EXIT (\d+)/),l=o.split(`
|
|
34
|
-
`).filter(f=>f&&!f.startsWith("EXIT ")&&!f.startsWith("HINT:")&&f.trim()),u=c?c[1]==="0"?`${E.success}\u2713${E.reset}`:`${E.error}\u2717 Exit ${c[1]}${E.reset}`:`${E.success}\u2713${E.reset}`,d=o.match(/\nHINT: (.+)/);if(d)r=`${u} ${E.muted}\u2014 ${d[1].substring(0,100)}${E.reset}`;else if(l.length===0)r=u;else{let f=c&&c[1]!=="0",h=f?l.slice(-3):l.slice(0,3),
|
|
35
|
-
`)}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r=`No matches${e.pattern?` ${E.muted}"${String(e.pattern).substring(0,40)}"${E.reset}`:""}`;else{let
|
|
36
|
-
`).filter(Boolean),l=c.length,d=new Set(c.map(
|
|
37
|
-
${
|
|
34
|
+
`).filter(f=>f&&!f.startsWith("EXIT ")&&!f.startsWith("HINT:")&&f.trim()),u=c?c[1]==="0"?`${E.success}\u2713${E.reset}`:`${E.error}\u2717 Exit ${c[1]}${E.reset}`:`${E.success}\u2713${E.reset}`,d=o.match(/\nHINT: (.+)/);if(d)r=`${u} ${E.muted}\u2014 ${d[1].substring(0,100)}${E.reset}`;else if(l.length===0)r=u;else{let f=c&&c[1]!=="0",h=f?l.slice(-3):l.slice(0,3),g=l.length-3,m=h.map((b,x)=>x===0?`${u} ${E.muted}${b.substring(0,120)}${E.reset}`:` ${E.muted}${b.substring(0,120)}${E.reset}`);if(g>0){let b=f?` ${E.subtle}${g} lines above\u2026${E.reset}`:` ${E.subtle}\u2026 +${g} lines${E.reset}`;f?m.unshift(b):m.push(b)}r=m.join(`
|
|
35
|
+
`)}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r=`No matches${e.pattern?` ${E.muted}"${String(e.pattern).substring(0,40)}"${E.reset}`:""}`;else{let g=function(x){let j=x.indexOf(":");if(j===-1)return`${E.muted}${x.substring(0,90)}${E.reset}`;let G=x.substring(0,j),L=x.substring(j+1),P=L.match(/^(\d+)[:-](.*)/s),C=P?`:${P[1]}`:"",Z=(P?P[2]:L).trim(),Y=`${E.subtle}${a.basename(G)}${C}${E.reset}`,ue=`${E.muted}${Z.substring(0,80)}${Z.length>80?"\u2026":""}${E.reset}`;return`${Y} ${ue}`};var i=g;let a=require("path"),c=o.split(`
|
|
36
|
+
`).filter(Boolean),l=c.length,d=new Set(c.map(x=>x.split(":")[0]).filter(Boolean)).size,f=e.pattern?` ${E.muted}"${String(e.pattern).substring(0,40)}"${E.reset}`:"",h=d>1?`${l} match${l!==1?"es":""} in ${d} files${f}`:`${l} match${l!==1?"es":""}${f}`,m=c.slice(0,3).map((x,j)=>j===0?`${h}
|
|
37
|
+
${g(x)}`:` ${g(x)}`),b=c.length-3;b>0&&m.push(` ${E.subtle}\u2026 +${b} lines${E.reset}`),r=m.join(`
|
|
38
38
|
`)}break}case"glob":{let a=e.pattern?` ${E.muted}${String(e.pattern).substring(0,50)}${E.reset}`:"";if(o==="(no matches)")r=`No files found${a}`;else{let c=require("path"),l=o.split(`
|
|
39
|
-
`).filter(Boolean),u=l.length,d=l.slice(0,5).map(
|
|
39
|
+
`).filter(Boolean),u=l.length,d=l.slice(0,5).map(g=>c.basename(g)),f=u-d.length,h=d.join(", ")+(f>0?`, +${f} more`:"");r=`${u} file${u!==1?"s":""}${a} \u2014 ${E.muted}${h}${E.reset}`}break}case"list_directory":{if(o==="(empty)")r="0 entries";else{let a=o.split(`
|
|
40
40
|
`).filter(Boolean),c=a.length,l=a.slice(0,6).join(", "),u=c-6;r=u>0?`${c} entries \u2014 ${E.muted}${l}, +${u} more${E.reset}`:`${c} entr${c!==1?"ies":"y"} \u2014 ${E.muted}${l}${E.reset}`}break}case"git_status":{let a=o.match(/Branch:\s*(\S+)/),c=o.split(`
|
|
41
41
|
`).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;r=a?`${a[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let a=(o.match(/^\+[^+]/gm)||[]).length,c=(o.match(/^-[^-]/gm)||[]).length;r=a||c?`+${a} \u2212${c} lines`:"No diff";break}case"git_log":{let a=o.split(`
|
|
42
42
|
`).filter(d=>/^commit\s+[0-9a-f]{7}/.test(d)),c=a.length,l=a[0]?a[0].replace(/^commit\s+/,"").substring(0,7):null,u=(()=>{let d=o.indexOf(a[0]||"\0");return d===-1?null:o.substring(d).split(`
|
|
43
|
-
`).find((h,
|
|
43
|
+
`).find((h,g)=>g>0&&h.trim()&&!h.startsWith("Author:")&&!h.startsWith("Date:")&&!h.startsWith("Merge:"))})();if(c===0)r="Log retrieved";else if(l&&u){let d=c>1?` ${E.muted}+${c-1} more${E.reset}`:"";r=`${l} ${E.muted}${u.trim().substring(0,60)}${E.reset}${d}`}else r=`${c} commit${c!==1?"s":""}`;break}case"git_commit":{let a=o.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),c=o.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);r=a?`${a[1]}${c?` \u2014 ${c[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let a=o.match(/(?:->|→)\s*(\S+)/);r=a?`\u2192 ${a[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(o))r="Already up to date";else{let a=(o.match(/^\+/gm)||[]).length;r=a>0?`Pulled \xB7 +${a} lines`:"Pulled"}break}case"web_fetch":{let a=o.match(/<title[^>]*>([^<]{1,80})<\/title>/i),c=o.match(/^#\s+(.{1,80})/m),l=e.url||"",u="";try{u=new URL(l).hostname}catch{u=l.substring(0,60)}let d=a?a[1].trim():c?c[1].trim():null;r=d?`${u} \u2014 ${E.muted}${d.substring(0,70)}${E.reset}`:`Fetched ${u}`;break}case"web_search":{let a=o.split(`
|
|
44
44
|
|
|
45
45
|
`).filter(Boolean),c=a.length,l=a[0]?a[0].split(`
|
|
46
46
|
`)[0].replace(/^\d+\.\s*/,"").trim():null,u=l?` ${E.muted}\u2014 ${l.substring(0,70)}${E.reset}`:"";r=`${c} result${c!==1?"s":""}${u}`;break}case"task_list":r="Done";break;case"spawn_agents":{let a=(o.match(/✓ Agent/g)||[]).length,c=(o.match(/✗ Agent/g)||[]).length;r=c>0?`${a} done, ${c} failed`:`${a} agent${a!==1?"s":""} done`;break}case"switch_model":{let a=o.match(/Switched to (.+)/);r=a?`\u2192 ${a[1]}`:"Done";break}case"ssh_exec":{let c=o.startsWith("EXIT ")||o.startsWith("Command failed"),l=o.split(`
|
|
47
|
-
`).filter(d=>d.trim()&&!d.startsWith("EXIT ")),u=c?`${E.error}\u2717${E.reset}`:`${E.success}\u2713${E.reset}`;if(l.length===0)r=u;else{if(l.length>2&&l.every(
|
|
47
|
+
`).filter(d=>d.trim()&&!d.startsWith("EXIT ")),u=c?`${E.error}\u2717${E.reset}`:`${E.success}\u2713${E.reset}`;if(l.length===0)r=u;else{if(l.length>2&&l.every(m=>/^\[/.test(m.trim()))){r=`${u} ${l.length} log lines`;break}let f=c?l.slice(-3):l.slice(0,3),h=l.length-3,g=f.map((m,b)=>b===0?`${u} ${E.muted}${m.substring(0,120)}${E.reset}`:` ${E.muted}${m.substring(0,120)}${E.reset}`);if(h>0){let m=c?` ${E.subtle}${h} lines above\u2026${E.reset}`:` ${E.subtle}\u2026 +${h} lines${E.reset}`;c?g.unshift(m):g.push(m)}r=g.join(`
|
|
48
48
|
`)}break}default:{let a=o.split(`
|
|
49
|
-
`).filter(c=>c.trim()&&!c.startsWith("EXIT ")&&!c.startsWith("HINT:"));if(a.length>0){let c=a[0].trim().substring(0,90),l=a.length>1?` ${E.subtle}\u2026 +${a.length-1} lines${E.reset}`:"";r=`${E.muted}${c}${E.reset}${l}`}else r="Done"}}return` ${E.muted}\u23BF ${r}${E.reset}`}function
|
|
50
|
-
${E.success}\u25C6${
|
|
49
|
+
`).filter(c=>c.trim()&&!c.startsWith("EXIT ")&&!c.startsWith("HINT:"));if(a.length>0){let c=a[0].trim().substring(0,90),l=a.length>1?` ${E.subtle}\u2026 +${a.length-1} lines${E.reset}`:"";r=`${E.muted}${c}${E.reset}${l}`}else r="Done"}}return` ${E.muted}\u23BF ${r}${E.reset}`}function Om(t,e,s,n,o,r){let i=Math.round(n/1e3),a=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,c=`
|
|
50
|
+
${E.success}\u25C6${Ze.reset} ${Ze.bold}${t}${Ze.reset}`;return c+=`${Ze.dim} \xB7 ${a}`,r.size>0&&(c+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),c+=Ze.reset,c}$l.exports={C:Ze,formatToolCall:Sm,formatResult:Em,getToolSpinnerText:Cm,formatToolSummary:Am,formatSectionHeader:vm,formatMilestone:Om,getThinkingVerb:Rm,setActiveModelForSpinner:Tm,THINKING_VERBS:qo}});var He=re((Ok,_l)=>{var{T:un}=Es(),Ai=un,bl=["01100110","01111110","01111110","01011010","01111110","00111100"];function Nm(t,e){let s=[];for(let n=0;n<t.length;n+=2){let o="";for(let r=0;r<t[0].length;r++){let i=t[n][r]==="1",a=n+1<t.length&&t[n+1][r]==="1";i&&a?o+=`${e}\u2588\x1B[0m`:i&&!a?o+=`${e}\u2580\x1B[0m`:!i&&a?o+=`${e}\u2584\x1B[0m`:o+=" "}s.push(o)}return s}function Mm(t,e,s={}){let n=Ai.bold,o=Ai.reset,r=Nm(bl,un.banner_logo),i=s.yolo?` ${n}${un.banner_yolo}\u26A1 YOLO${o}`:"",a=Lo().version,c=[` ${un.banner_name}${n}nex-code${o} ${un.banner_version}v${a}${o}`,` ${un.banner_model}${t}${o} ${un.muted}\xB7 /help${o}${i}`,""],l=Math.max(r.length,c.length),u=Math.floor((l-r.length)/2),d=Math.floor((l-c.length)/2),f=bl[0].length,h=[];for(let g=0;g<l;g++){let m=r[g-u]??" ".repeat(f),b=c[g-d]??"";h.push(m+b)}console.log(`
|
|
51
51
|
`+h.join(`
|
|
52
52
|
`)+`
|
|
53
|
-
`)}var{Spinner:
|
|
54
|
-
`);this.buffer=s.pop()||"";for(let n of s){let o=this.parseLine(n);if(o?.done)return o}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},jo=class extends Kn{constructor(e,s={}){super(e,s),this.toolCallsMap={}}parseLine(e){let s=e.trim();if(!s||!s.startsWith("data: "))return{done:!1};let n=s.slice(6);if(n==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(n)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a=i.index??0;this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},Do=class extends Yn{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i}){let a={model:e,messages:s,max_tokens:o,temperature:r};return i&&(a.stream=!0),n&&n.length>0&&(a.tools=n),a}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}createStreamParser(e,s={}){return new jo(e,s)}},qo=class extends Kn{constructor(e,s={}){super(e,s),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let s=e.trim();if(!s.startsWith("data: "))return{done:!1};let n=s.slice(6),o;try{o=JSON.parse(n)}catch{return{done:!1}}switch(o.type){case"content_block_start":{let r=o.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=o.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let s={};if(e.inputJson)try{s=JSON.parse(e.inputJson)}catch{s=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:s}}})}}},Fo=class extends Yn{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:s,max_tokens:o,temperature:r};return i&&(c.stream=!0),a?.system&&(c.system=a.system),n&&n.length>0&&(c.tools=n),c}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}createStreamParser(e,s={}){return new qo(e,s)}},Bo=class extends Kn{constructor(e,s={}){super(e,s),this.toolCalls=[],this.onThinkingToken=s.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let s;try{s=JSON.parse(e)}catch{return{done:!1}}return s.message?.thinking&&this.onThinkingToken(s.message.thinking),s.message?.content&&(this.onToken(s.message.content),this.content+=s.message.content),s.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(s.message.tool_calls)),s.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,s)=>({id:e.id||`ollama-${Date.now()}-${s}`,function:{name:e.function?.name||e.name||"unknown",arguments:e.function?.arguments||e.arguments||{}}}))}}},Wo=class extends Yn{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:s,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:a?.repeat_penalty??1.05}};return n&&n.length>0&&(c.tools=n),c}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:(s.tool_calls||[]).map((n,o)=>({id:n.id||`ollama-${Date.now()}-${o}`,function:{name:n.function?.name||n.name||"unknown",arguments:n.function?.arguments||n.arguments||{}}}))}}createStreamParser(e,s={}){return new Bo(e,s)}},Im=new Do,jm=new Fo,Dm=new Wo;ll.exports={WireProtocol:Yn,StreamParser:Kn,OpenAICompatibleProtocol:Do,AnthropicProtocol:Fo,OllamaChatProtocol:Wo,OpenAIStreamParser:jo,AnthropicStreamParser:qo,OllamaStreamParser:Bo,openaiProtocol:Im,anthropicProtocol:jm,ollamaProtocol:Dm}});var fl=se((pk,dl)=>{var Uo=require("axios"),qm=require("http"),Fm=require("https"),{BaseProvider:Bm,readStreamErrorBody:Wm}=Gn(),{ollamaProtocol:cn}=zn(),Ho=new qm.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Go=new Fm.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),ul={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5:cloud":{id:"glm-5:cloud",name:"GLM 5 Cloud",maxTokens:16384,contextWindow:2e5},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:2e5},"glm-4.6":{id:"glm-4.6",name:"GLM 4.6",maxTokens:16384,contextWindow:2e5},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"nemotron-3-super:cloud":{id:"nemotron-3-super:cloud",name:"Nemotron 3 Super Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},vi=class extends Bm{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||ul,defaultModel:e.defaultModel||"qwen3-coder:480b",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this._discovered=!1}async discoverModels(){if(!this._discovered){if(this._discovered=!0,!process.stdout.isTTY){Uo.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ho,httpsAgent:Go}).then(e=>{let s=e.data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await Uo.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ho,httpsAgent:Go})).data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
|
|
55
|
-
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=
|
|
56
|
-
|
|
57
|
-
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}n.push(r)}}for(let o=n.length-1;o>0;o--)n[o].role==="user"&&n[o-1].role==="user"&&n.splice(o,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(o),null):{role:"user",content:[o]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return Vt.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,{messages:c,system:l}=this.formatMessages(e),u=this.formatTools(s),d=Vt.buildRequestBody({model:r,messages:c,tools:u,maxTokens:a,temperature:n.temperature??this.temperature,stream:!1,extra:{system:l}}),f;try{f=await yl.post(`${this.baseUrl}${Vt.getEndpoint()}`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let m=h.response?.status?` [HTTP ${h.response.status}]`:"",g=h.response?.data?.error?.message||h.response?.data?.error||h.message;throw new Error(`API Error${m}: ${g}`)}return Vt.normalizeResponse(f.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l,system:u}=this.formatMessages(e),d=this.formatTools(s),f=Vt.buildRequestBody({model:r,messages:l,tools:d,maxTokens:a,temperature:n.temperature??this.temperature,stream:!0,extra:{system:u}}),h;try{h=await yl.post(`${this.baseUrl}${Vt.getEndpoint()}`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let b=g.response?.status?` [HTTP ${g.response.status}]`:"",v=await Ym(g,O=>O?.error?.message||O?.error);throw new Error(`API Error${b}: ${v}`)}let m=Vt.createStreamParser(c);return new Promise((g,b)=>{n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),b(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",v=>{let{done:O,result:U}=m.feed(v.toString());O&&g(U)}),h.data.on("error",v=>{n.signal?.aborted||b(new Error(`Stream error: ${v.message}`))}),h.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return Vt.normalizeResponse(e)}};wl.exports={AnthropicProvider:Ei,ANTHROPIC_MODELS:$l}});var vl=se((gk,kl)=>{var _l=require("axios"),{BaseProvider:zm,readStreamErrorBody:Xm}=Gn(),{openaiProtocol:un}=zn(),xl={"gemini-3.1-pro-preview":{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",maxTokens:65536,contextWindow:1048576},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:65536,contextWindow:1048576},"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash":{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash-lite":{id:"gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",maxTokens:65536,contextWindow:1048576},"gemini-2.0-flash":{id:"gemini-2.0-flash",name:"Gemini 2.0 Flash",maxTokens:8192,contextWindow:1048576},"gemini-2.0-flash-lite":{id:"gemini-2.0-flash-lite",name:"Gemini 2.0 Flash Lite",maxTokens:8192,contextWindow:1048576},"gemini-1.5-pro":{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro",maxTokens:8192,contextWindow:1048576},"gemini-1.5-flash":{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash",maxTokens:8192,contextWindow:1048576}},Ti=class extends zm{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||xl,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),c=un.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),l;try{l=await _l.post(`${this.baseUrl}${un.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return un.normalizeResponse(l.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,a=n.onToken||(()=>{}),{messages:c}=this.formatMessages(e),l=un.buildRequestBody({model:o,messages:c,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await _l.post(`${this.baseUrl}${un.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",m=await Xm(f,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let d=un.createStreamParser(a);return new Promise((f,h)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",m=>{let{done:g,result:b}=d.feed(m.toString());g&&f(b)}),u.data.on("error",m=>{n.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return un.normalizeResponse(e)}};kl.exports={GeminiProvider:Ti,GEMINI_MODELS:xl}});var Tl=se((yk,El)=>{var Yo=require("axios"),{BaseProvider:Vm,readStreamErrorBody:Jm}=Gn(),{ollamaProtocol:dn}=zn(),Sl="http://localhost:11434",Ri=class extends Vm{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Sl,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let s=(await Yo.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of s){let o=n.name||n.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let a=await Yo.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),c=a.data?.model_info||a.data?.details||{};i=c["general.context_length"]||c["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
|
|
58
|
-
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=
|
|
59
|
-
`)}}function
|
|
60
|
-
`)}function
|
|
61
|
-
`),a}catch(a){throw o.stop(),a}}async function
|
|
62
|
-
`){l(o);return}if(f==="\x1B[A"){o=(o-1+s.length)%s.length,a();return}if(f==="\x1B[B"){o=(o+1)%s.length,a();return}let h=f.toLowerCase().trim();if(h==="y"){c(!0);return}if(h==="n"){c(!1);return}if(h==="a"&&e.toolName){
|
|
53
|
+
`)}var{Spinner:Lm,MultiProgress:Pm,TaskProgress:Im,ToolProgress:jm,setActiveTaskProgress:Dm,getActiveTaskProgress:qm,cleanupTerminal:Fm}=zn(),{formatToolCall:Bm,formatResult:Wm,getToolSpinnerText:Um,formatToolSummary:Hm,formatSectionHeader:Ym,formatMilestone:Gm,getThinkingVerb:Km,setActiveModelForSpinner:zm}=wl();_l.exports={C:Ai,banner:Mm,Spinner:Lm,MultiProgress:Pm,TaskProgress:Im,ToolProgress:jm,setActiveTaskProgress:Dm,getActiveTaskProgress:qm,cleanupTerminal:Fm,formatToolCall:Bm,formatResult:Wm,getToolSpinnerText:Um,formatToolSummary:Hm,formatSectionHeader:Ym,formatMilestone:Gm,getThinkingVerb:Km,setActiveModelForSpinner:zm}});var Xn=re((Nk,xl)=>{async function Xm(t,e){if(!t.response?.data)return t.message;let s=t.response.data;if(typeof s=="object"&&s!==null&&typeof s.pipe!="function")return e(s)||t.message;try{let n=await new Promise((r,i)=>{let a=[];s.on("data",c=>a.push(c)),s.on("end",()=>r(Buffer.concat(a).toString("utf8"))),s.on("error",i)}),o=JSON.parse(n);return e(o)||n||t.message}catch{return t.message}}var Oi=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,s,n={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,s,n={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};xl.exports={BaseProvider:Oi,readStreamErrorBody:Xm}});var Zn=re((Mk,kl)=>{var Vn=class{buildRequestBody(e){throw new Error("buildRequestBody() not implemented")}getEndpoint(){throw new Error("getEndpoint() not implemented")}formatTools(e){return e}normalizeResponse(e){throw new Error("normalizeResponse() not implemented")}createStreamParser(e,s={}){throw new Error("createStreamParser() not implemented")}},Jn=class{constructor(e,s={}){this.onToken=e,this.callbacks=s,this.content="",this.buffer=""}feed(e){this.buffer+=e;let s=this.buffer.split(`
|
|
54
|
+
`);this.buffer=s.pop()||"";for(let n of s){let o=this.parseLine(n);if(o?.done)return o}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},Fo=class extends Jn{constructor(e,s={}){super(e,s),this.toolCallsMap={}}parseLine(e){let s=e.trim();if(!s||!s.startsWith("data: "))return{done:!1};let n=s.slice(6);if(n==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(n)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let a=i.index??0;this.toolCallsMap[a]||(this.toolCallsMap[a]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[a].id=i.id),i.function?.name&&(this.toolCallsMap[a].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[a].arguments+=i.function.arguments)}return{done:!1}}getResult(){return{content:this.content,tool_calls:Object.values(this.toolCallsMap).filter(e=>e.name).map(e=>({id:e.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:e.name,arguments:e.arguments}}))}}},Bo=class extends Vn{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i}){let a={model:e,messages:s,max_tokens:o,temperature:r};return i&&(a.stream=!0),n&&n.length>0&&(a.tools=n),a}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}createStreamParser(e,s={}){return new Fo(e,s)}},Wo=class extends Jn{constructor(e,s={}){super(e,s),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let s=e.trim();if(!s.startsWith("data: "))return{done:!1};let n=s.slice(6),o;try{o=JSON.parse(n)}catch{return{done:!1}}switch(o.type){case"content_block_start":{let r=o.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=o.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let s={};if(e.inputJson)try{s=JSON.parse(e.inputJson)}catch{s=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:s}}})}}},Uo=class extends Vn{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:s,max_tokens:o,temperature:r};return i&&(c.stream=!0),a?.system&&(c.system=a.system),n&&n.length>0&&(c.tools=n),c}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}createStreamParser(e,s={}){return new Wo(e,s)}},Ho=class extends Jn{constructor(e,s={}){super(e,s),this.toolCalls=[],this.onThinkingToken=s.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let s;try{s=JSON.parse(e)}catch{return{done:!1}}return s.message?.thinking&&this.onThinkingToken(s.message.thinking),s.message?.content&&(this.onToken(s.message.content),this.content+=s.message.content),s.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(s.message.tool_calls)),s.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,s)=>({id:e.id||`ollama-${Date.now()}-${s}`,function:{name:e.function?.name||e.name||"unknown",arguments:e.function?.arguments||e.arguments||{}}}))}}},Yo=class extends Vn{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:s,tools:n,maxTokens:o,temperature:r,stream:i,extra:a}){let c={model:e,messages:s,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:a?.repeat_penalty??1.05}};return n&&n.length>0&&(c.tools=n),c}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:(s.tool_calls||[]).map((n,o)=>({id:n.id||`ollama-${Date.now()}-${o}`,function:{name:n.function?.name||n.name||"unknown",arguments:n.function?.arguments||n.arguments||{}}}))}}createStreamParser(e,s={}){return new Ho(e,s)}},Vm=new Bo,Jm=new Uo,Zm=new Yo;kl.exports={WireProtocol:Vn,StreamParser:Jn,OpenAICompatibleProtocol:Bo,AnthropicProtocol:Uo,OllamaChatProtocol:Yo,OpenAIStreamParser:Fo,AnthropicStreamParser:Wo,OllamaStreamParser:Ho,openaiProtocol:Vm,anthropicProtocol:Jm,ollamaProtocol:Zm}});var El=re((Lk,Sl)=>{var Go=require("axios"),Qm=require("http"),eg=require("https"),{BaseProvider:tg,readStreamErrorBody:ng}=Xn(),{ollamaProtocol:dn}=Zn(),Ko=new Qm.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),zo=new eg.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),vl={"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",maxTokens:16384,contextWindow:131072},"qwen3-coder-next":{id:"qwen3-coder-next",name:"Qwen3 Coder Next",maxTokens:16384,contextWindow:262144},"devstral-2:123b":{id:"devstral-2:123b",name:"Devstral 2 123B",maxTokens:16384,contextWindow:131072},"devstral-small-2:24b":{id:"devstral-small-2:24b",name:"Devstral Small 2 24B",maxTokens:16384,contextWindow:131072},"minimax-m2.7:cloud":{id:"minimax-m2.7:cloud",name:"MiniMax M2.7 Cloud",maxTokens:16384,contextWindow:131072},"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",maxTokens:16384,contextWindow:256e3},"kimi-k2:1t":{id:"kimi-k2:1t",name:"Kimi K2 1T",maxTokens:16384,contextWindow:256e3},"kimi-k2-thinking":{id:"kimi-k2-thinking",name:"Kimi K2 Thinking",maxTokens:16384,contextWindow:256e3},"deepseek-v3.2":{id:"deepseek-v3.2",name:"DeepSeek V3.2",maxTokens:16384,contextWindow:131072},"deepseek-v3.1:671b":{id:"deepseek-v3.1:671b",name:"DeepSeek V3.1 671B",maxTokens:16384,contextWindow:131072},"cogito-2.1:671b":{id:"cogito-2.1:671b",name:"Cogito 2.1 671B",maxTokens:16384,contextWindow:131072},"qwen3.5:397b-cloud":{id:"qwen3.5:397b-cloud",name:"Qwen3.5 397B Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:397b":{id:"qwen3.5:397b",name:"Qwen3.5 397B",maxTokens:16384,contextWindow:262144},"qwen3.5:122b-a10b":{id:"qwen3.5:122b-a10b",name:"Qwen3.5 122B-A10B",maxTokens:16384,contextWindow:262144},"qwen3.5:35b-a3b":{id:"qwen3.5:35b-a3b",name:"Qwen3.5 35B-A3B",maxTokens:16384,contextWindow:262144},"qwen3.5:27b":{id:"qwen3.5:27b",name:"Qwen3.5 27B",maxTokens:16384,contextWindow:262144},"qwen3-next:80b":{id:"qwen3-next:80b",name:"Qwen3 Next 80B",maxTokens:16384,contextWindow:131072},"mistral-large-3:675b":{id:"mistral-large-3:675b",name:"Mistral Large 3 675B",maxTokens:16384,contextWindow:131072},"gpt-oss:120b":{id:"gpt-oss:120b",name:"GPT-OSS 120B",maxTokens:16384,contextWindow:131072},"minimax-m2.5":{id:"minimax-m2.5",name:"MiniMax M2.5",maxTokens:16384,contextWindow:131072},"glm-5:cloud":{id:"glm-5:cloud",name:"GLM 5 Cloud",maxTokens:16384,contextWindow:2e5},"glm-5":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:2e5},"glm-4.6":{id:"glm-4.6",name:"GLM 4.6",maxTokens:16384,contextWindow:2e5},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"nemotron-3-super:cloud":{id:"nemotron-3-super:cloud",name:"Nemotron 3 Super Cloud",maxTokens:16384,contextWindow:262144},"qwen3.5:9b":{id:"qwen3.5:9b",name:"Qwen3.5 9B",maxTokens:8192,contextWindow:262144},"qwen3.5:4b":{id:"qwen3.5:4b",name:"Qwen3.5 4B",maxTokens:8192,contextWindow:262144},"qwen3.5:2b":{id:"qwen3.5:2b",name:"Qwen3.5 2B",maxTokens:8192,contextWindow:262144},"qwen3.5:0.8b":{id:"qwen3.5:0.8b",name:"Qwen3.5 0.8B",maxTokens:8192,contextWindow:262144},"gemma3:27b":{id:"gemma3:27b",name:"Gemma 3 27B",maxTokens:8192,contextWindow:131072},"gemma3:12b":{id:"gemma3:12b",name:"Gemma 3 12B",maxTokens:8192,contextWindow:131072},"gemma3:4b":{id:"gemma3:4b",name:"Gemma 3 4B",maxTokens:8192,contextWindow:131072},"ministral-3:14b":{id:"ministral-3:14b",name:"Ministral 3 14B",maxTokens:8192,contextWindow:131072},"ministral-3:8b":{id:"ministral-3:8b",name:"Ministral 3 8B",maxTokens:8192,contextWindow:131072},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:16384,contextWindow:131072}},Ni=class extends tg{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||vl,defaultModel:e.defaultModel||"qwen3-coder:480b",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this._discovered=!1}async discoverModels(){if(!this._discovered){if(this._discovered=!0,!process.stdout.isTTY){Go.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ko,httpsAgent:zo}).then(e=>{let s=e.data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await Go.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Ko,httpsAgent:zo})).data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
|
|
55
|
+
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=dn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1,extra:{repeat_penalty:n.repeat_penalty}}),c;try{c=await Go.post(`${this.baseUrl}${dn.getEndpoint()}`,a,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Ko,httpsAgent:zo})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let u=l.response?.status?` [HTTP ${l.response.status}]`:"",d=l.response?.data?.error||l.message;throw new Error(`API Error${u}: ${d}`)}return dn.normalizeResponse(c.data)}async stream(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=n.onToken||(()=>{}),c=n.onThinkingToken||(()=>{}),l=dn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0,extra:{repeat_penalty:n.repeat_penalty}}),u;try{u=await Go.post(`${this.baseUrl}${dn.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:Ko,httpsAgent:zo})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",g=await ng(f,m=>m?.error);throw new Error(`API Error${h}: ${g}`)}let d=dn.createStreamParser(a,{onThinkingToken:c});return new Promise((f,h)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{let{done:m,result:b}=d.feed(g.toString());m&&f(b)}),u.data.on("error",g=>{n.signal?.aborted||h(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return dn.normalizeResponse(e)}};Sl.exports={OllamaProvider:Ni,OLLAMA_MODELS:vl}});var Al=re((Pk,Cl)=>{var Tl=require("axios"),{BaseProvider:sg,readStreamErrorBody:og}=Xn(),{openaiProtocol:fn}=Zn(),Rl={"gpt-4o":{id:"gpt-4o",name:"GPT-4o",maxTokens:16384,contextWindow:128e3},"gpt-4o-mini":{id:"gpt-4o-mini",name:"GPT-4o Mini",maxTokens:16384,contextWindow:128e3},"gpt-4.1":{id:"gpt-4.1",name:"GPT-4.1",maxTokens:32768,contextWindow:128e3},"gpt-4.1-mini":{id:"gpt-4.1-mini",name:"GPT-4.1 Mini",maxTokens:32768,contextWindow:128e3},"gpt-4.1-nano":{id:"gpt-4.1-nano",name:"GPT-4.1 Nano",maxTokens:16384,contextWindow:128e3},o1:{id:"o1",name:"o1",maxTokens:1e5,contextWindow:2e5},o3:{id:"o3",name:"o3",maxTokens:1e5,contextWindow:2e5},"o3-mini":{id:"o3-mini",name:"o3 Mini",maxTokens:65536,contextWindow:2e5},"o4-mini":{id:"o4-mini",name:"o4 Mini",maxTokens:1e5,contextWindow:2e5}},Mi=class extends sg{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Rl,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,{messages:a}=this.formatMessages(e),c=fn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),l;try{l=await Tl.post(`${this.baseUrl}${fn.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return fn.normalizeResponse(l.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,a=n.onToken||(()=>{}),{messages:c}=this.formatMessages(e),l=fn.buildRequestBody({model:o,messages:c,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await Tl.post(`${this.baseUrl}${fn.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",g=await og(f,m=>m?.error?.message||m?.error);throw new Error(`API Error${h}: ${g}`)}let d=fn.createStreamParser(a);return new Promise((f,h)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{let{done:m,result:b}=d.feed(g.toString());m&&f(b)}),u.data.on("error",g=>{n.signal?.aborted||h(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return fn.normalizeResponse(e)}};Cl.exports={OpenAIProvider:Mi,OPENAI_MODELS:Rl}});var Ll=re((Ik,Ml)=>{var Ol=require("axios"),{BaseProvider:rg,readStreamErrorBody:ig}=Xn(),{anthropicProtocol:Zt}=Zn(),Nl={"claude-sonnet":{id:"claude-sonnet-4-6",name:"Claude Sonnet 4.6",maxTokens:64e3,contextWindow:2e5},"claude-opus":{id:"claude-opus-4-6",name:"Claude Opus 4.6",maxTokens:128e3,contextWindow:2e5},"claude-haiku":{id:"claude-haiku-4-5-20251001",name:"Claude Haiku 4.5",maxTokens:64e3,contextWindow:2e5},"claude-sonnet-4-5":{id:"claude-sonnet-4-5-20250929",name:"Claude Sonnet 4.5",maxTokens:64e3,contextWindow:2e5},"claude-sonnet-4":{id:"claude-sonnet-4-20250514",name:"Claude Sonnet 4",maxTokens:64e3,contextWindow:2e5}},ag="2023-06-01",Li=class extends rg{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Nl,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||ag}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s="",n=[];for(let o of e){if(o.role==="system"){s+=(s?`
|
|
56
|
+
|
|
57
|
+
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}n.push(r)}}for(let o=n.length-1;o>0;o--)n[o].role==="user"&&n[o-1].role==="user"&&n.splice(o,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(o),null):{role:"user",content:[o]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return Zt.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,{messages:c,system:l}=this.formatMessages(e),u=this.formatTools(s),d=Zt.buildRequestBody({model:r,messages:c,tools:u,maxTokens:a,temperature:n.temperature??this.temperature,stream:!1,extra:{system:l}}),f;try{f=await Ol.post(`${this.baseUrl}${Zt.getEndpoint()}`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let g=h.response?.status?` [HTTP ${h.response.status}]`:"",m=h.response?.data?.error?.message||h.response?.data?.error||h.message;throw new Error(`API Error${g}: ${m}`)}return Zt.normalizeResponse(f.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),a=n.maxTokens||i?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l,system:u}=this.formatMessages(e),d=this.formatTools(s),f=Zt.buildRequestBody({model:r,messages:l,tools:d,maxTokens:a,temperature:n.temperature??this.temperature,stream:!0,extra:{system:u}}),h;try{h=await Ol.post(`${this.baseUrl}${Zt.getEndpoint()}`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(m){if(m.name==="CanceledError"||m.name==="AbortError"||m.code==="ERR_CANCELED")throw m;let b=m.response?.status?` [HTTP ${m.response.status}]`:"",x=await ig(m,j=>j?.error?.message||j?.error);throw new Error(`API Error${b}: ${x}`)}let g=Zt.createStreamParser(c);return new Promise((m,b)=>{n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),b(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",x=>{let{done:j,result:G}=g.feed(x.toString());j&&m(G)}),h.data.on("error",x=>{n.signal?.aborted||b(new Error(`Stream error: ${x.message}`))}),h.data.on("end",()=>{m(g.flush())})})}normalizeResponse(e){return Zt.normalizeResponse(e)}};Ml.exports={AnthropicProvider:Li,ANTHROPIC_MODELS:Nl}});var Dl=re((jk,jl)=>{var Pl=require("axios"),{BaseProvider:cg,readStreamErrorBody:lg}=Xn(),{openaiProtocol:pn}=Zn(),Il={"gemini-3.1-pro-preview":{id:"gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",maxTokens:65536,contextWindow:1048576},"gemini-3-flash-preview":{id:"gemini-3-flash-preview",name:"Gemini 3 Flash Preview",maxTokens:65536,contextWindow:1048576},"gemini-2.5-pro":{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash":{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",maxTokens:65536,contextWindow:1048576},"gemini-2.5-flash-lite":{id:"gemini-2.5-flash-lite",name:"Gemini 2.5 Flash Lite",maxTokens:65536,contextWindow:1048576},"gemini-2.0-flash":{id:"gemini-2.0-flash",name:"Gemini 2.0 Flash",maxTokens:8192,contextWindow:1048576},"gemini-2.0-flash-lite":{id:"gemini-2.0-flash-lite",name:"Gemini 2.0 Flash Lite",maxTokens:8192,contextWindow:1048576},"gemini-1.5-pro":{id:"gemini-1.5-pro",name:"Gemini 1.5 Pro",maxTokens:8192,contextWindow:1048576},"gemini-1.5-flash":{id:"gemini-1.5-flash",name:"Gemini 1.5 Flash",maxTokens:8192,contextWindow:1048576}},Pi=class extends cg{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Il,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),c=pn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),l;try{l=await Pl.post(`${this.baseUrl}${pn.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return pn.normalizeResponse(l.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,a=n.onToken||(()=>{}),{messages:c}=this.formatMessages(e),l=pn.buildRequestBody({model:o,messages:c,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await Pl.post(`${this.baseUrl}${pn.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let h=f.response?.status?` [HTTP ${f.response.status}]`:"",g=await lg(f,m=>m?.error?.message||m?.error);throw new Error(`API Error${h}: ${g}`)}let d=pn.createStreamParser(a);return new Promise((f,h)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{let{done:m,result:b}=d.feed(g.toString());m&&f(b)}),u.data.on("error",g=>{n.signal?.aborted||h(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return pn.normalizeResponse(e)}};jl.exports={GeminiProvider:Pi,GEMINI_MODELS:Il}});var Bl=re((Dk,Fl)=>{var Xo=require("axios"),{BaseProvider:ug,readStreamErrorBody:dg}=Xn(),{ollamaProtocol:hn}=Zn(),ql="http://localhost:11434",Ii=class extends ug{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||ql,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let s=(await Xo.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of s){let o=n.name||n.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let a=await Xo.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),c=a.data?.model_info||a.data?.details||{};i=c["general.context_length"]||c["llama.context_length"]||this._parseContextFromModelfile(a.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
|
|
58
|
+
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=hn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!1}),i;try{i=await Xo.post(`${this.baseUrl}${hn.getEndpoint()}`,r,{timeout:n.timeout||this.timeout})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let c=a.response?.status?` [HTTP ${a.response.status}]`:"",l=a.response?.data?.error||a.message;throw new Error(`API Error${c}: ${l}`)}return hn.normalizeResponse(i.data)}async stream(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=n.onToken||(()=>{}),i=hn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!0}),a;try{a=await Xo.post(`${this.baseUrl}${hn.getEndpoint()}`,i,{timeout:n.timeout||this.timeout,responseType:"stream",signal:n.signal})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let u=l.response?.status?` [HTTP ${l.response.status}]`:"",d=await dg(l,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let c=hn.createStreamParser(r);return new Promise((l,u)=>{n.signal&&n.signal.addEventListener("abort",()=>{a.data.destroy(),u(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",d=>{let{done:f,result:h}=c.feed(d.toString());f&&l(h)}),a.data.on("error",d=>{n.signal?.aborted||u(new Error(`Stream error: ${d.message}`))}),a.data.on("end",()=>{l(c.flush())})})}normalizeResponse(e){return hn.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}};Fl.exports={LocalProvider:Ii,DEFAULT_LOCAL_URL:ql}});var mn=re((qk,Ul)=>{"use strict";var dt=require("fs"),Wl=require("path");function fg(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function pg(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function hg(t,e){let s=Wl.dirname(t),n=Wl.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{dt.existsSync(s)||dt.mkdirSync(s,{recursive:!0}),dt.writeFileSync(n,e,"utf-8"),dt.renameSync(n,t)}catch(o){try{dt.unlinkSync(n)}catch{}throw o}}function mg(t,e,{timeout:s=5e3,retryMs:n=50}={}){let o=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=dt.openSync(o,"wx"),dt.writeSync(i,Buffer.from(String(process.pid))),dt.closeSync(i),i=-1;try{return e()}finally{try{dt.unlinkSync(o)}catch{}}}catch(a){if(i!==-1)try{dt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let c=dt.readFileSync(o,"utf-8").trim(),l=parseInt(c,10);if(!fg(l)){try{dt.unlinkSync(o)}catch{}continue}}catch(c){if(c.code&&c.code!=="ENOENT")throw c;continue}if(Date.now()>=r){try{dt.unlinkSync(o)}catch{}return e()}pg(n)}}}Ul.exports={atomicWrite:hg,withFileLockSync:mg}});var Jo=re((Fk,Vl)=>{var Qn=require("fs"),ji=require("path"),{atomicWrite:gg,withFileLockSync:yg}=mn(),Hl={openai:{"gpt-4o":{input:2.5,output:10},"gpt-4o-mini":{input:.15,output:.6},"gpt-4.1":{input:2,output:8},"gpt-4.1-mini":{input:.4,output:1.6},"gpt-4.1-nano":{input:.1,output:.4},o1:{input:15,output:60},o3:{input:10,output:40},"o3-mini":{input:1.1,output:4.4},"o4-mini":{input:1.1,output:4.4}},anthropic:{"claude-sonnet":{input:3,output:15},"claude-opus":{input:5,output:25},"claude-haiku":{input:.8,output:4},"claude-sonnet-4-5":{input:3,output:15},"claude-sonnet-4":{input:3,output:15}},gemini:{"gemini-2.5-pro":{input:1.25,output:10},"gemini-2.5-flash":{input:.15,output:.6},"gemini-2.0-flash":{input:.1,output:.4},"gemini-2.0-flash-lite":{input:.075,output:.3}},ollama:{"qwen3-coder:480b":{input:0,output:0},"qwen3-coder-next":{input:0,output:0},"devstral-2:123b":{input:0,output:0},"devstral-small-2:24b":{input:0,output:0},"kimi-k2.5":{input:0,output:0},"kimi-k2:1t":{input:0,output:0},"deepseek-v3.2":{input:0,output:0},"minimax-m2.5":{input:0,output:0},"glm-5":{input:0,output:0},"glm-4.7":{input:0,output:0},"gpt-oss:120b":{input:0,output:0}},local:{}},Vo=[],Qt={};function $g(t,e,s,n){if(Vo.push({provider:t,model:e,input:s,output:n}),Qt[t]!==void 0){let o=zl(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
|
|
59
|
+
`)}}function Di(t,e){let s=Hl[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function Yl(t){let e=Di(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Gl(){let t={};for(let r of Vo){let i=`${r.provider}:${r.model}`;t[i]||(t[i]={provider:r.provider,model:r.model,input:0,output:0}),t[i].input+=r.input,t[i].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:Yl(r)})),s=e.reduce((r,i)=>r+i.cost,0),n=e.reduce((r,i)=>r+i.input,0),o=e.reduce((r,i)=>r+i.output,0);return{totalCost:s,totalInput:n,totalOutput:o,breakdown:e}}function wg(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=Gl();if(n.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of n){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";o.push(` ${r.provider}:${r.model}`),o.push(` Input: ${r.input.toLocaleString()} tokens`),o.push(` Output: ${r.output.toLocaleString()} tokens`),o.push(` Cost: ${i}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
|
|
60
|
+
`)}function bg(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function _g(t,e,s,n){let o=Di(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function xg(){Vo=[]}function kg(t,e){Qt[t]=e}function vg(t){delete Qt[t]}function Sg(){return{...Qt}}function Kl(t){let e=0;for(let s of Vo)s.provider===t&&(e+=Yl(s));return e}function zl(t){let e=Kl(t),s=Qt[t];if(s===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let n=Math.max(0,s-e);return{allowed:e<s,spent:e,limit:s,remaining:n}}function Xl(){let t=ji.join(process.cwd(),".nex","config.json");if(Qn.existsSync(t))try{let e=JSON.parse(Qn.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Qt={...e.costLimits})}catch{}}function Eg(){let t=ji.join(process.cwd(),".nex"),e=ji.join(t,"config.json");Qn.existsSync(t)||Qn.mkdirSync(t,{recursive:!0}),yg(e,()=>{let s={};if(Qn.existsSync(e))try{s=JSON.parse(Qn.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Qt,gg(e,JSON.stringify(s,null,2))})}function Tg(){Qt={}}Xl();Vl.exports={PRICING:Hl,trackUsage:$g,getSessionCosts:Gl,formatCosts:wg,formatCostHint:_g,resetCosts:xg,getPricing:Di,setCostLimit:kg,removeCostLimit:vg,getCostLimits:Sg,getProviderSpend:Kl,checkBudget:zl,loadCostLimits:Xl,saveCostLimits:Eg,resetCostLimits:Tg,estimateTokens:bg}});var Zo=re((Bk,Jl)=>{function qi(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var Rg=qi();function Cg(...t){qi()&&console.log(...t)}function Ag(...t){qi()&&console.warn(...t)}Jl.exports={DEBUG:Rg,debugLog:Cg,warnLog:Ag}});var eu=re((Wk,Ql)=>{"use strict";var Og=new Set(["read_file","grep","glob","search_files","list_directory"]),Ng=new Set(["write_file","edit_file","patch_file"]),Mg=new Set(["bash"]),Lg=new Set(["web_search","web_fetch","perplexity_search"]);function Zl(t,e){let s=0,n=0,o=0,r=0,i=0;for(let[a,c]of t)i+=c,Og.has(a)&&(s+=c),Ng.has(a)&&(n+=c),Mg.has(a)&&(o+=c),Lg.has(a)&&(r+=c);return i===0?`Phase ${e}`:r/i>.5?"Research":s/i>.5?"Exploration":n/i>.3?"Implementation":o/i>.3&&n/i<.15?"Verification":`Phase ${e}`}var Fi=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,s,n,o){if(this._disabled)return null;this._stepsThisPhase++;for(let i of s)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:Zl(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(n),filesModified:new Set(o)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};Ql.exports={MilestoneTracker:Fi,_phaseName:Zl}});var Rs=re((Uk,tu)=>{var Ts=Ge(),Pg={"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",max_tokens:16384},"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",max_tokens:16384}};function Ig(){return Ts.getActiveModel()}function jg(t){return Ts.setActiveModel(t)}function Dg(){return Ts.getModelNames()}function qg(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let n=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(n)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let n=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(n)}catch{}let s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}return null}async function Fg(t,e){let{C:s}=He(),{Spinner:n}=He(),o=new n("Thinking...");o.start();let r=!0,i="";try{let a=await Ts.callStream(t,e,{onToken:c=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(c),i+=c}});return r?o.stop():process.stdout.write(`${s.reset}
|
|
61
|
+
`),a}catch(a){throw o.stop(),a}}async function Bg(t,e){return Ts.callChat(t,e)}tu.exports={MODELS:Pg,getActiveModel:Ig,setActiveModel:jg,getModelNames:Dg,callOllamaStream:Fg,callOllama:Bg,parseToolArgs:qg}});var Cs=re((Hk,au)=>{var Wg=require("readline"),{C:Lt}=He(),Ui=[/rm\s+-rf\s+\/(?:\s|$)/,/rm\s+-rf\s+~(?:\/|\s|$)/,/rm\s+-rf\s+\.(?:\/|\s|$)/,/rm\s+-rf\s+\*(?:\s|$)/,/mkfs/,/dd\s+if=/,/:\(\)\s*\{/,/>\/dev\/sd/,/curl.*\|\s*(?:ba)?sh/,/wget.*\|\s*(?:ba)?sh/,/cat\s+.*\.env\b/,/cat\s+.*credentials/i,/chmod\s+777/,/chown\s+root/,/passwd/,/userdel/,/useradd/,/\beval\s*\(/,/base64.*\|.*bash/,/\bprintenv\b/,/cat\s+.*\.ssh\/id_/,/cat\s+.*\.ssh\/config/,/\bnc\s+-[el]/,/\bncat\b/,/\bsocat\b/,/python3?\s+-c\s/,/node\s+-e\s/,/perl\s+-e\s/,/ruby\s+-e\s/,/(?:^|[;&|]\s*)history(?:\s|$)/,/curl.*-X\s*POST/,/curl.*--data/,/\bsed\s+-n\s+['"]?\d+,\d+p/],nu=[...Ui,/\bgrep\b.*\.env\b/,/\bawk\b.*\.env\b/,/\bsed\b.*\.env\b/,/\bhead\b.*\.env\b/,/\btail\b.*\.env\b/,/\bless\b.*\.env\b/,/\bmore\b.*\.env\b/,/\bstrings\b.*\.env\b/,/\bgrep\b.*credentials/i,/\bawk\b.*credentials/i,/\bsed\b.*credentials/i,/\bhead\b.*credentials/i,/\btail\b.*credentials/i,/\bcat\b.*private.*key/i,/\bgrep\b.*private_key/i,/\bcat\b.*google.*\.json/i,/\bcat\b.*service.?account/i];function Ug(t){for(let e of nu)if(e.test(t))return e;return null}var su=[/\.env\b/,/credentials\b/i,/\.ssh\b/,/\.gnupg\b/,/\.aws\b/,/\.npmrc\b/,/\.docker\/config/,/\.kube\/config/,/venv\b/,/\.venv\b/,/\.sqlite3\b/,/\.git\/(?!hooks)/],Hg=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,Bi=[/systemctl\s+(status|is-active|is-enabled|list-units|show)/,/journalctl\b/,/\btail\s/,/\bcat\s/,/\bhead\s/,/\bls\b/,/\bfind\s/,/\bgrep\s/,/\bwc\s/,/\bdf\b/,/\bfree\b/,/\buptime\b/,/\bwho\b/,/\bps\s/,/\bgit\s+(status|log|diff|branch|fetch)\b/,/\bgit\s+pull\b/,/\bss\s+-[tlnp]/,/\bnetstat\s/,/\bdu\s/,/\blscpu\b/,/\bnproc\b/,/\buname\b/,/\bhostname\b/,/\bgetent\b/,/\bid\b/,/psql\s.*-c\s/,/\bmysql\s.*-e\s/,/\bdnf\s+(check-update|list|info|history|repolist|updateinfo)\b/,/\brpm\s+-q/,/\bapt\s+list\b/,/\bopenssl\s+s_client\b/,/\bopenssl\s+x509\b/,/\bcertbot\s+certificates\b/,/\bcurl\s+-[sIkv]|curl\s+--head/,/\bdig\s/,/\bnslookup\s/,/\bping\s/,/\bgetenforce\b/,/\bsesearch\b/,/\bausearch\b/,/\bsealert\b/,/\bcrontab\s+-l\b/,/\btimedatectl\b/,/\bfirewall-cmd\s+--list/,/\bfirewall-cmd\s+--state/];function ou(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let n=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(n.length===0)return!1;let o=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(l=>l.trim()).filter(Boolean).every(l=>o(l)):Bi.some(c=>c.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Bi.some(a=>a.test(i))};return n.every(o)}var Hi=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/,/--no-verify\b/,/git\s+reset\s+--hard\b/,/git\s+clean\s+-[a-z]*f/,/git\s+checkout\s+--\s/,/git\s+push\s+(?:--force\b|-f\b)/],ru=[/git\s+push/,/npm\s+publish/,/\bHUSKY=0\b/,/\bSKIP_HUSKY=1\b/,/\bSKIP_PREFLIGHT_CHECK=true\b/,/npx\s+.*publish/,/docker\s+rm/,/ssh\s/,/wget\s/,/curl\s.*-o\s/,/pip\s+install/,/npm\s+install\s+-g/],iu=[...Hi,...ru],Yi=!1,gn=null,Wi=null;function Yg(t){Yi=t}function Gg(t){Wi=t}function Kg(){return Yi}function zg(t){gn=t}function Xg(t){for(let e of Ui)if(e.test(t))return e;return null}function Vg(t){if(/ssh\s/.test(t)&&ou(t))return!1;for(let e of iu)if(e.test(t))return!0;return!1}function Jg(t){for(let e of Hi)if(e.test(t))return!0;return!1}function Zg(t){if(process.env.NEX_UNPROTECT==="1"||!Hg.test(t))return null;for(let e of su)if(e.test(t))return e;return null}function Qg(t,e={}){if(Yi)return Promise.resolve(!0);if(Wi)return Wi(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return ey(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0;gn&&gn.pause();let r=global._nexRawWrite||(d=>process.stdout.write(d)),i=()=>{let d=process.stdout.rows||24;return Math.max(1,d-s.length-2)},a=()=>{let d=i();global._nexRawWrite&&d>1&&global._nexRawWrite(`\x1B[1;${d-1}r`);let f=`\x1B[${d};1H\x1B[2K${Lt.yellow}${t}${Lt.reset}`;for(let h=0;h<s.length;h++){let g=h===o,m=g?`${Lt.yellow}\u276F${Lt.reset}`:" ",b=g?`${Lt.yellow}${s[h]}${Lt.reset}`:s[h];f+=`\x1B[${d+1+h};1H\x1B[2K ${m} ${b}`}r(f)},c=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(m=>process.stdout.write(m)),h=i(),g="";for(let m=0;m<s.length+1;m++)g+=`\x1B[${h+m};1H\x1B[2K`;f(g),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),gn&&gn.resume(),n(d)},l=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&Qo(e.toolName),c(!0)},u=d=>{if(d[0]===3){c(!1);return}let f=d.toString();if(f==="\r"||f===`
|
|
62
|
+
`){l(o);return}if(f==="\x1B[A"){o=(o-1+s.length)%s.length,a();return}if(f==="\x1B[B"){o=(o+1)%s.length,a();return}let h=f.toLowerCase().trim();if(h==="y"){c(!0);return}if(h==="n"){c(!1);return}if(h==="a"&&e.toolName){Qo(e.toolName),c(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function ey(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(Qo(e.toolName),n(!0)):n(i!=="n")};if(gn)gn.question(`${Lt.yellow}${t} ${s}${Lt.reset}`,o);else{let r=Wg.createInterface({input:process.stdin,output:process.stdout});r.question(`${Lt.yellow}${t} ${s}${Lt.reset}`,i=>{r.close(),o(i)})}})}var Qo=()=>{};function ty(t){Qo=t}au.exports={FORBIDDEN_PATTERNS:Ui,SSH_FORBIDDEN_PATTERNS:nu,BASH_PROTECTED_PATHS:su,SSH_SAFE_PATTERNS:Bi,isSSHReadOnly:ou,DANGEROUS_BASH:iu,CRITICAL_BASH:Hi,NOTABLE_BASH:ru,isForbidden:Xg,isSSHForbidden:Ug,isDangerous:Vg,isCritical:Jg,isBashPathForbidden:Zg,confirm:Qg,setAutoConfirm:Yg,getAutoConfirm:Kg,setConfirmHook:Gg,setReadlineInterface:zg,setAllowAlwaysHandler:ty}});var uu=re((Gk,lu)=>{var er=require("path"),{C:M}=He(),{T:Gi,isDark:Yk}=Es(),{confirm:ny,getAutoConfirm:sy}=Cs(),cu=2e3;function As(t,e){let s=t.split(`
|
|
63
63
|
`),n=e.split(`
|
|
64
|
-
`),o=[],r=s.length,i=n.length;if(r>
|
|
65
|
-
${M.bold}${M.cyan} Diff: ${t}${M.reset}`);let o=
|
|
66
|
-
${M.bold}${M.cyan} File exists \u2014 showing changes: ${t}${M.reset}`);let n=
|
|
64
|
+
`),o=[],r=s.length,i=n.length;if(r>cu||i>cu){for(let d of s)o.push({type:"remove",line:d});for(let d of n)o.push({type:"add",line:d});return o}let a=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let d=1;d<=r;d++)for(let f=1;f<=i;f++)s[d-1]===n[f-1]?a[d][f]=a[d-1][f-1]+1:a[d][f]=Math.max(a[d-1][f],a[d][f-1]);let c=r,l=i,u=[];for(;c>0||l>0;)c>0&&l>0&&s[c-1]===n[l-1]?(u.unshift({type:"same",line:s[c-1]}),c--,l--):l>0&&(c===0||a[c][l-1]>=a[c-1][l])?(u.unshift({type:"add",line:n[l-1]}),l--):(u.unshift({type:"remove",line:s[c-1]}),c--);return u}function oy(t,e,s,n=3){console.log(`
|
|
65
|
+
${M.bold}${M.cyan} Diff: ${t}${M.reset}`);let o=As(e,s),r=[];if(o.forEach((c,l)=>{c.type!=="same"&&r.push(l)}),r.length===0){console.log(`${M.gray} (no changes)${M.reset}`);return}let i=Math.max(0,r[0]-n),a=Math.min(o.length,r[r.length-1]+n+1);i>0&&console.log(`${M.gray} ...${M.reset}`);for(let c=i;c<a;c++){let l=o[c];switch(l.type){case"remove":console.log(`${M.red} - ${l.line}${M.reset}`);break;case"add":console.log(`${M.green} + ${l.line}${M.reset}`);break;default:console.log(`${M.gray} ${l.line}${M.reset}`)}}a<o.length&&console.log(`${M.gray} ...${M.reset}`),console.log()}function ry(t,e,s){console.log(`
|
|
66
|
+
${M.bold}${M.cyan} File exists \u2014 showing changes: ${t}${M.reset}`);let n=As(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${M.gray} (identical content)${M.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${M.gray} ...(${o-r} more changes)${M.reset}`);break}switch(i.type){case"remove":console.log(`${M.red} - ${i.line}${M.reset}`),r++;break;case"add":console.log(`${M.green} + ${i.line}${M.reset}`),r++;break;default:r>0&&console.log(`${M.gray} ${i.line}${M.reset}`)}}console.log()}function iy(t,e){console.log(`
|
|
67
67
|
${M.bold}${M.cyan} New file: ${t}${M.reset}`);let s=e.split(`
|
|
68
|
-
`),n=s.slice(0,20);for(let o of n)console.log(`${M.green} + ${o}${M.reset}`);s.length>20&&console.log(`${M.gray} ...+${s.length-20} more lines${M.reset}`),console.log()}async function
|
|
69
|
-
${M.bold}${M.cyan} Side-by-side: ${t}${M.reset}`),console.log(` ${M.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${M.reset}`);let i=
|
|
70
|
-
`)}function
|
|
68
|
+
`),n=s.slice(0,20);for(let o of n)console.log(`${M.green} + ${o}${M.reset}`);s.length>20&&console.log(`${M.gray} ...+${s.length-20} more lines${M.reset}`),console.log()}async function ay(t){return sy()?!0:ny(` ${t}?`)}function cy(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
|
|
69
|
+
${M.bold}${M.cyan} Side-by-side: ${t}${M.reset}`),console.log(` ${M.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${M.reset}`);let i=As(e,s),a=[],c=0;for(;c<i.length;)if(i[c].type==="same")a.push({left:i[c].line,right:i[c].line,type:"same"}),c++;else if(i[c].type==="remove"){let h=[];for(;c<i.length&&i[c].type==="remove";)h.push(i[c].line),c++;let g=[];for(;c<i.length&&i[c].type==="add";)g.push(i[c].line),c++;let m=Math.max(h.length,g.length);for(let b=0;b<m;b++)a.push({left:b<h.length?h[b]:"",right:b<g.length?g[b]:"",type:"changed"})}else i[c].type==="add"&&(a.push({left:"",right:i[c].line,type:"changed"}),c++);let l=a.map((h,g)=>h.type!=="same"?g:-1).filter(h=>h>=0);if(l.length===0){console.log(` ${M.gray}(no changes)${M.reset}`);return}let u=Math.max(0,l[0]-2),d=Math.min(a.length,l[l.length-1]+3),f=(h,g)=>{let m=h.replace(/\x1b\[[0-9;]*m/g,"");return m.length>=g?h.substring(0,g):h+" ".repeat(g-m.length)};u>0&&console.log(` ${M.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${M.reset}`);for(let h=u;h<d;h++){let g=a[h];if(g.type==="same")console.log(` ${M.gray}${f(g.left,r)}${M.reset}\u2502${M.gray}${f(g.right,r)}${M.reset}`);else{let m=g.left?`${M.red}${f(g.left,r)}${M.reset}`:`${f("",r)}`,b=g.right?`${M.green}${f(g.right,r)}${M.reset}`:`${f("",r)}`;console.log(` ${m}\u2502${b}`)}}d<a.length&&console.log(` ${M.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${M.reset}`),console.log(` ${M.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${M.reset}
|
|
70
|
+
`)}function ly(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],a=er.isAbsolute(t)?er.relative(process.cwd(),t):t,c=As(e,s),l=1,u=1;for(let C of c)C.type==="same"?(C.oldLine=l++,C.newLine=u++):C.type==="remove"?(C.oldLine=l++,C.newLine=null):(C.oldLine=null,C.newLine=u++);let d=0,f=0;for(let C of c)C.type==="add"?d++:C.type==="remove"&&f++;if(console.log(`
|
|
71
71
|
${M.green}\u23FA${M.reset} ${M.bold}${o}(${a})${M.reset}`),d===0&&f===0){console.log(` ${M.dim}\u23BF (no changes)${M.reset}
|
|
72
|
-
`);return}let h=[];if(d>0&&h.push(`Added ${d} line${d!==1?"s":""}`),f>0&&h.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let C=i.filter(
|
|
72
|
+
`);return}let h=[];if(d>0&&h.push(`Added ${d} line${d!==1?"s":""}`),f>0&&h.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let C=i.filter(ie=>ie.severity==="error").length,Z=i.filter(ie=>ie.severity==="warn").length,Y=i.filter(ie=>ie.severity==="info").length,ue=[];C>0&&ue.push(`${M.red}${C} error${C!==1?"s":""}${M.dim}`),Z>0&&ue.push(`${M.yellow}${Z} warning${Z!==1?"s":""}${M.dim}`),Y>0&&ue.push(`${M.cyan}${Y} info${Y!==1?"s":""}${M.dim}`),h.push(`found ${ue.join(", ")}`)}console.log(` ${M.dim}\u23BF ${h.join(", ")}${M.reset}`);let m=[];c.forEach((C,Z)=>{C.type!=="same"&&m.push(Z)});let b=[],x=null,j=null;for(let C of m){let Z=Math.max(0,C-r),Y=Math.min(c.length-1,C+r);x===null?(x=Z,j=Y):(Z<=j+1||(b.push([x,j]),x=Z),j=Y)}x!==null&&b.push([x,j]);let G=" ",L=process.stdout.columns||120;function P(C,Z,Y){let ue=Y.replace(/\x1b\[[0-9;]*m/g,""),ie=Y+" ".repeat(Math.max(0,L-ue.length));return`${C}${Z}${ie}${M.reset}`}for(let C=0;C<b.length;C++){C>0&&console.log(`${G}${M.dim}\xB7\xB7\xB7${M.reset}`);let[Z,Y]=b[C];for(let ue=Z;ue<=Y;ue++){let ie=c[ue],se=ie.newLine!=null?ie.newLine:ie.oldLine,T=String(se).padStart(4),Te=ie.type!=="remove"?i.filter(K=>K.line===ie.newLine):[];ie.type==="remove"?console.log(P(Gi.diff_rem_bg,M.red,`${G}${T} - ${ie.line}`)):ie.type==="add"?console.log(P(Gi.diff_add_bg,M.green,`${G}${T} + ${ie.line}`)):console.log(`${G}${M.dim}${T} ${M.reset}${ie.line}`);for(let K of Te){let X=M.cyan,me="\u2139";K.severity==="error"?(X=M.red,me="\u2716"):K.severity==="warn"&&(X=M.yellow,me="\u26A0"),console.log(`${G} ${X}${me} ${K.message}${M.reset}`)}}}console.log()}function uy(t,e,s={}){let n=er.isAbsolute(t)?er.relative(process.cwd(),t):t,o=e.split(`
|
|
73
73
|
`),r=s.annotations||[];console.log(`
|
|
74
|
-
${M.green}\u23FA${M.reset} ${M.bold}Create(${n})${M.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(
|
|
75
|
-
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function
|
|
76
|
-
`);for(let d of u)d.startsWith("+")&&!d.startsWith("+++")&&o++,d.startsWith("-")&&!d.startsWith("---")&&r++}else o=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":o>r*2?i="feat":r>o?i="refactor":i="fix";let c=t.slice(0,3).map(u=>u.split("/").pop());return{summary:`${i}: update ${c.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function
|
|
77
|
-
${
|
|
78
|
-
${
|
|
79
|
-
${
|
|
74
|
+
${M.green}\u23FA${M.reset} ${M.bold}Create(${n})${M.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(m=>m.severity==="error").length,f=r.filter(m=>m.severity==="warn").length,h=r.filter(m=>m.severity==="info").length,g=[];d>0&&g.push(`${M.red}${d} error${d!==1?"s":""}${M.dim}`),f>0&&g.push(`${M.yellow}${f} warning${f!==1?"s":""}${M.dim}`),h>0&&g.push(`${M.cyan}${h} info${h!==1?"s":""}${M.dim}`),i.push(`found ${g.join(", ")}`)}console.log(` ${M.dim}\u23BF ${i.join(", ")}${M.reset}`);let c=" ",l=process.stdout.columns||120,u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),h=d+1,g=r.filter(j=>j.line===h),m=`${c}${f} + ${o[d]}`,b=m.replace(/\x1b\[[0-9;]*m/g,""),x=m+" ".repeat(Math.max(0,l-b.length));console.log(`${Gi.diff_add_bg}${M.green}${x}${M.reset}`);for(let j of g){let G=M.cyan,L="\u2139";j.severity==="error"?(G=M.red,L="\u2716"):j.severity==="warn"&&(G=M.yellow,L="\u26A0"),console.log(`${c} ${G}${L} ${j.message}${M.reset}`)}}o.length>20&&console.log(`${c}${M.dim} ...+${o.length-20} more lines${M.reset}`),console.log()}lu.exports={diffLines:As,showEditDiff:oy,showWriteDiff:ry,showNewFilePreview:iy,confirmFileChange:ay,showSideBySideDiff:cy,showDiff:ly,showNewFile:uy}});var sr=re((Kk,pu)=>{var du=require("util").promisify(require("child_process").exec),dy=require("util").promisify(require("child_process").execFile),{C:Ie}=He();async function Ki(t){try{let{stdout:e}=await du(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function tr(...t){try{let{stdout:e}=await dy("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function fy(){return await Ki("git rev-parse --is-inside-work-tree")==="true"}async function py(){return await Ki("git branch --show-current")}async function zi(){try{let{stdout:t}=await du("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
75
|
+
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function nr(t=!1){return await Ki(`git diff ${t?"--cached":""}`)||""}async function Xi(){return(await zi()).map(e=>e.file)}async function fu(){let t=await Xi();if(t.length===0)return null;let e=await nr(),n=await nr(!0)||e,o=0,r=0;if(n){let u=n.split(`
|
|
76
|
+
`);for(let d of u)d.startsWith("+")&&!d.startsWith("+++")&&o++,d.startsWith("-")&&!d.startsWith("---")&&r++}else o=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.includes("doc")?i="docs":o>r*2?i="feat":r>o?i="refactor":i="fix";let c=t.slice(0,3).map(u=>u.split("/").pop());return{summary:`${i}: update ${c.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function hy(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await tr("checkout","-b",s)!==null?s:null}async function my(t){return await tr("add","-A"),await tr("commit","-m",t)?await tr("rev-parse","--short","HEAD"):null}async function gy(){let t=await fu();if(!t)return`${Ie.dim}No changes${Ie.reset}`;let e=[];e.push(`
|
|
77
|
+
${Ie.bold}${Ie.cyan}Git Diff Summary:${Ie.reset}`),e.push(` ${Ie.green}+${t.stats.additions}${Ie.reset} ${Ie.red}-${t.stats.deletions}${Ie.reset} in ${t.files.length} file(s)`),e.push(`
|
|
78
|
+
${Ie.bold}${Ie.cyan}Files:${Ie.reset}`);for(let s of t.files.slice(0,20))e.push(` ${Ie.dim}${s}${Ie.reset}`);return t.files.length>20&&e.push(` ${Ie.dim}...+${t.files.length-20} more${Ie.reset}`),e.push(`
|
|
79
|
+
${Ie.bold}${Ie.cyan}Suggested message:${Ie.reset}`),e.push(` ${Ie.cyan}${t.summary}${Ie.reset}
|
|
80
80
|
`),e.join(`
|
|
81
|
-
`)}async function
|
|
81
|
+
`)}async function yy(){return(await zi()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function $y(){let t=await Xi();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let n of t.slice(0,10))e.push(` ${n}`);let s=await nr();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
|
|
82
82
|
...(truncated)`:s;e.push(`
|
|
83
83
|
DIFF:
|
|
84
84
|
${n}`)}return e.join(`
|
|
85
|
-
`)}
|
|
86
|
-
`).map(s=>{let n=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!n)return null;let o=n[2].trim();return o.startsWith(
|
|
87
|
-
`)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?o.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:o,body:n}}function
|
|
85
|
+
`)}pu.exports={isGitRepo:fy,getCurrentBranch:py,getStatus:zi,getDiff:nr,getChangedFiles:Xi,analyzeDiff:fu,createBranch:hy,commit:my,formatDiffSummary:gy,getDiffContext:$y,getMergeConflicts:yy}});var bu=re((Xk,wu)=>{var Ke=require("fs").promises,zk=require("fs"),$t=require("path"),wy=require("crypto"),{execSync:Os}=require("child_process"),by=100*1024,gu=50,st=[],es=[];function _y(t,e,s,n){for(st.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});st.length>gu;)st.shift();es.length=0,yu(st[st.length-1]).catch(()=>{})}async function xy(){if(st.length===0)return null;let t=st.pop();if(t.oldContent===null)try{await Ke.unlink(t.filePath)}catch{}else await Ke.writeFile(t.filePath,t.oldContent,"utf-8");return es.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function ky(){if(es.length===0)return null;let t=es.pop();return await Ke.writeFile(t.filePath,t.newContent,"utf-8"),st.push(t),{tool:t.tool,filePath:t.filePath}}function vy(t=10){return st.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Sy(){return st.length}function Ey(){return es.length}function Ty({diskToo:t=!0}={}){if(st.length=0,es.length=0,t){let e=rr();Ke.readdir(e).then(s=>{for(let n of s)n.endsWith(".json")&&Ke.unlink($t.join(e,n)).catch(()=>{})}).catch(()=>{})}}function rr(){return $t.join(process.cwd(),".nex","history")}async function hu(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=by)return{inline:!0,content:t};let s=wy.createHash("sha256").update(t,"utf-8").digest("hex"),n=$t.join(e,"blobs");return await Ke.mkdir(n,{recursive:!0}),await Ke.writeFile($t.join(n,s),t,"utf-8"),{inline:!1,hash:s}}async function yu(t){let e=rr();await Ke.mkdir(e,{recursive:!0});let s=$t.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),n=`${t.timestamp}-${s}.json`,o=await hu(t.oldContent,e),r=await hu(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:o.inline?{inline:!0,content:o.content}:{inline:!1,hash:o.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await Ke.writeFile($t.join(e,n),JSON.stringify(i),"utf-8")}async function mu(t,e){if(!t)return null;if(t.inline)return t.content;let s=$t.join(e,"blobs",t.hash);return Ke.readFile(s,"utf-8")}async function Ry(){let t=rr(),e;try{e=await Ke.readdir(t)}catch{return 0}let s=e.filter(o=>o.endsWith(".json")).sort(),n=0;for(let o of s)try{let r=await Ke.readFile($t.join(t,o),"utf-8"),i=JSON.parse(r),a=await mu(i.oldContent,t),c=await mu(i.newContent,t);st.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:c}),n++}catch{}for(;st.length>gu;)st.shift();return n}async function Cy(t=7){let e=rr(),s;try{s=await Ke.readdir(e)}catch{return 0}let n=Date.now()-t*24*60*60*1e3,o=s.filter(l=>l.endsWith(".json")),r=0,i=new Set,a=[];for(let l of o)try{let u=await Ke.readFile($t.join(e,l),"utf-8"),d=JSON.parse(u);d.timestamp<n?(a.push(l),r++):(d.oldContent&&!d.oldContent.inline&&d.oldContent.hash&&i.add(d.oldContent.hash),d.newContent&&!d.newContent.inline&&d.newContent.hash&&i.add(d.newContent.hash))}catch{}for(let l of a)try{await Ke.unlink($t.join(e,l))}catch{}let c=$t.join(e,"blobs");try{let l=await Ke.readdir(c);for(let u of l)if(!i.has(u))try{await Ke.unlink($t.join(c,u))}catch{}}catch{}return r}var or="nex-snapshot";function Ay(t,e=process.cwd()){let s=t?`${or}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${or}-${Date.now()}`;try{return Os("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Os(`git stash push -u -m "${s}"`,{cwd:e,timeout:15e3}),Os("git stash pop",{cwd:e,timeout:1e4}),{name:s,label:s,ok:!0}):{name:s,label:s,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(n){return{name:s,label:s,ok:!1,error:n.message}}}function $u(t=process.cwd()){try{let e=Os("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
|
|
86
|
+
`).map(s=>{let n=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!n)return null;let o=n[2].trim();return o.startsWith(or)?{index:parseInt(n[1],10),label:o,shortName:o.replace(`${or}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function Oy(t,e=process.cwd()){try{let s=$u(e);if(s.length===0)return{ok:!1,error:"No snapshots found"};let n;return t===void 0||t==="last"?n=s[0]:typeof t=="number"?n=s.find(o=>o.index===t):n=s.find(o=>o.label===t||o.shortName===t||o.shortName.includes(String(t))),n?(Os(`git stash apply stash@{${n.index}}`,{cwd:e,timeout:15e3}),{ok:!0,label:n.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(s){return{ok:!1,error:s.message}}}wu.exports={recordChange:_y,undo:xy,redo:ky,getHistory:vy,getUndoCount:Sy,getRedoCount:Ey,clearHistory:Ty,persistEntry:yu,loadPersistedHistory:Ry,pruneHistory:Cy,createSnapshot:Ay,listSnapshots:$u,restoreSnapshot:Oy}});var ea=re((Vk,Eu)=>{var Oe=require("fs"),ot=require("path"),{atomicWrite:Ny,withFileLockSync:My}=mn(),et=[];function Ns(){return ot.join(process.cwd(),".nex","skills")}function _u(){return ot.join(process.cwd(),".nex","config.json")}function xu(){let t=Ns();return Oe.existsSync(t)||Oe.mkdirSync(t,{recursive:!0}),t}function Zi(){let t=_u();if(!Oe.existsSync(t))return[];try{let e=JSON.parse(Oe.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function ku(t){let e=_u(),s=ot.dirname(e);Oe.existsSync(s)||Oe.mkdirSync(s,{recursive:!0}),My(e,()=>{let n={};if(Oe.existsSync(e))try{n=JSON.parse(Oe.readFileSync(e,"utf-8"))}catch{n={}}n.skills||(n.skills={}),n.skills.disabled=t,Ny(e,JSON.stringify(n,null,2))})}function vu(t,e){let s=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&s.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&s.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&s.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))s.push("commands must be an array");else for(let n=0;n<t.commands.length;n++){let o=t.commands[n];(!o.cmd||typeof o.cmd!="string")&&s.push(`commands[${n}].cmd must be a non-empty string`),o.handler!==void 0&&typeof o.handler!="function"&&s.push(`commands[${n}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))s.push("tools must be an array");else for(let n=0;n<t.tools.length;n++){let o=t.tools[n];(!o.function||!o.function.name||typeof o.function.name!="string")&&s.push(`tools[${n}].function.name must be a non-empty string`),o.execute!==void 0&&typeof o.execute!="function"&&s.push(`tools[${n}].execute must be a function`)}return{valid:s.length===0,errors:s}}function Su(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let s=e[1],n=e[2].trim(),o=[],r=!1;for(let i of s.split(`
|
|
87
|
+
`)){let a=i.trim();if(/^trigger:\s*$/i.test(a)){r=!0;continue}r&&a.startsWith("- ")?o.push(a.slice(2).trim().replace(/^["']|["']$/g,"")):r&&a&&!a.startsWith("#")&&(r=!1)}return{triggers:o,body:n}}function Vi(t){try{let e=Oe.readFileSync(t,"utf-8").trim();if(!e)return null;let s=ot.basename(t,".md"),{triggers:n,body:o}=Su(e);return{name:s,type:"prompt",filePath:t,instructions:o||e,triggers:n,commands:[],tools:[]}}catch{return null}}function Ji(t){try{let e=require(t),{valid:s,errors:n}=vu(e,t);return s?{name:e.name||ot.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(r=>({cmd:r.cmd.startsWith("/")?r.cmd:`/${r.cmd}`,desc:r.desc||r.description||"",handler:r.handler||null})),tools:(e.tools||[]).map(r=>({type:r.type||"function",function:{name:r.function.name,description:r.function.description||"",parameters:r.function.parameters||{type:"object",properties:{}}},execute:r.execute||null}))}:(console.error(`Skill validation failed: ${t}
|
|
88
88
|
${n.join(`
|
|
89
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
89
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Qi(){et=[];let t=Zi(),e=Ns(),s=[];if(Oe.existsSync(e))try{s=Oe.readdirSync(e)}catch{s=[]}for(let o of s){let r=ot.join(e,o),i;try{i=Oe.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;o.endsWith(".md")?a=Vi(r):o.endsWith(".js")&&(a=Ji(r)),a&&(a.enabled=!t.includes(a.name),et.push(a))}let n=ot.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Oe.existsSync(n)){let o;try{o=Oe.readdirSync(n).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{o=[]}for(let r of o){let i=ot.join(n,r),a=ot.basename(r,ot.extname(r));if(et.some(u=>u.name===a))continue;let c;try{c=Oe.statSync(i)}catch{continue}if(!c.isFile())continue;let l=r.endsWith(".md")?Vi(i):Ji(i);l&&(l._builtin=!0,l.enabled=!t.includes(l.name),et.push(l))}}return et}function Ly(){let t=[];for(let e of et)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
90
90
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
91
91
|
${t.join(`
|
|
92
92
|
|
|
93
|
-
`)}`}function
|
|
93
|
+
`)}`}function Py(){let t=[];for(let e of et)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function Iy(){let t=[];for(let e of et)if(e.enabled)for(let s of e.tools)t.push({type:"function",function:{name:`skill_${s.function.name}`,description:`[Skill:${e.name}] ${s.function.description}`,parameters:s.function.parameters}});return t}async function jy(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of et)if(n.enabled){for(let o of n.tools)if(o.function.name===s&&o.execute)try{let r=await o.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${s}' failed: ${r.message}`}}return`ERROR: Skill tool '${s}' not found`}function Dy(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of et)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(n);if(typeof i=="string"&&i.length>0)return{handled:!0,agentPrompt:i}}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return{handled:!0}}}return!1}function qy(){return et.map(t=>({name:t.name,type:t.type,enabled:t.enabled,description:t.description||"",commands:t.commands.length,tools:t.tools.length,filePath:t.filePath}))}function Fy(t){let e=et.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Zi().filter(n=>n!==t);return ku(s),!0}function By(t){let e=et.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Zi();return s.includes(t)||(s.push(t),ku(s)),!0}function Wy(){return et}async function Uy(t,e={}){let{execSync:s}=require("child_process"),n=xu(),o=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(o=`https://github.com/${t}.git`);let r=e.name||ot.basename(o,".git").replace(/^nex-skill-/,""),i=ot.join(n,r);if(Oe.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:@#?=&%+~]+$/.test(o))throw new Error(`Invalid git URL: ${o}`);let u=i.replace(/'/g,"'\\''");s(`git clone --depth 1 '${o}' '${u}'`,{timeout:3e4,stdio:"pipe"})}catch(u){return{ok:!1,name:r,error:`Git clone failed: ${u.stderr?.toString().trim()||u.message}`}}let a=ot.join(i,"skill.json"),c=Oe.existsSync(a),l=Oe.readdirSync(i).some(u=>(u.endsWith(".md")||u.endsWith(".js"))&&!u.startsWith("."));if(!c&&!l){try{Oe.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"No skill.json manifest or .md/.js skill file found in repository"}}if(c)try{let u=JSON.parse(Oe.readFileSync(a,"utf-8"));u.name||(u.name=r)}catch{try{Oe.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Qi(),{ok:!0,name:r}}async function Hy(t){let e=require("axios");try{let s=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${s}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(o=>({name:o.name.replace(/^nex-skill-/,""),description:o.description||"(no description)",url:o.clone_url,stars:o.stargazers_count,owner:o.owner.login}))}catch(s){return[{name:"error",description:`Search failed: ${s.message}`,url:"",stars:0,owner:""}]}}function Yy(t){let e=ot.join(Ns(),t);if(!Oe.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${Ns()}`};try{return Oe.rmSync(e,{recursive:!0,force:!0}),Qi(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}function Gy(t){if(!t)return[];let e=t.toLowerCase(),s=[];for(let n of et){if(!n.enabled||!n.triggers||n.triggers.length===0)continue;if(n.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(n.instructions||"").split(`
|
|
94
94
|
`).slice(0,3).join(`
|
|
95
|
-
`);s.push({name:n.name,instructions:r})}}return s}
|
|
95
|
+
`);s.push({name:n.name,instructions:r})}}return s}Eu.exports={initSkillsDir:xu,loadAllSkills:Qi,getSkillInstructions:Ly,getSkillCommands:Py,getSkillToolDefinitions:Iy,routeSkillCall:jy,handleSkillCommand:Dy,listSkills:qy,enableSkill:Fy,disableSkill:By,getLoadedSkills:Wy,installSkill:Uy,searchSkills:Hy,removeSkill:Yy,matchSkillTriggers:Gy,_getSkillsDir:Ns,_validateScriptSkill:vu,_loadMarkdownSkill:Vi,_loadScriptSkill:Ji,_parseFrontmatter:Su}});var na=re((Jk,Nu)=>{var{spawn:Ky}=require("child_process"),zy=require("path"),Tu=require("fs"),Ht=new Map;function Xy(){return zy.join(process.cwd(),".nex","config.json")}function ta(){let t=Xy();if(!Tu.existsSync(t))return{};try{return JSON.parse(Tu.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function ir(t,e,s={},n=1e4){return new Promise((o,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,a=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:s})+`
|
|
96
96
|
`,c="",l=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},n);function u(f){c+=f.toString();let h=c.split(`
|
|
97
|
-
`);for(let
|
|
98
|
-
`):JSON.stringify(o)}function
|
|
99
|
-
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),i=[],a={...e},c=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=
|
|
97
|
+
`);for(let g of h)if(g.trim())try{let m=JSON.parse(g);if(m.id===i){d(),m.error?r(new Error(`MCP error: ${m.error.message||JSON.stringify(m.error)}`)):o(m.result);return}}catch{}c=h[h.length-1]||""}function d(){clearTimeout(l),t.stdout.removeListener("data",u)}t.stdout.on("data",u);try{t.stdin.write(a)}catch(f){d(),r(new Error(`MCP write failed: ${f.message}`))}})}async function Ru(t,e){if(Ht.has(t))return Ht.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let i of s)process.env[i]&&(n[i]=process.env[i]);let o=Ky(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await ir(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await ir(o,"tools/list",{});return r.tools=i&&i.tools||[],Ht.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Cu(t){let e=Ht.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Ht.delete(t),!0}function Vy(){for(let[t]of Ht)Cu(t)}async function Au(t,e,s={}){let n=Ht.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await ir(n.proc,"tools/call",{name:e,arguments:s});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
98
|
+
`):JSON.stringify(o)}function Ou(){let t=[];for(let[e,s]of Ht)for(let n of s.tools)t.push({server:e,name:n.name,description:n.description||"",inputSchema:n.inputSchema||{type:"object",properties:{}}});return t}function Jy(){return Ou().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Zy(t,e){if(!t.startsWith("mcp_"))return null;let s=t.substring(4).split("_");if(s.length<2)return null;let n=s[0],o=s.slice(1).join("_");return Au(n,o,e)}function Qy(){let t=ta();return Object.entries(t).map(([e,s])=>{let n=Ht.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function e$(){let t=ta(),e=[];for(let[s,n]of Object.entries(t))try{let o=await Ru(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Nu.exports={loadMCPConfig:ta,sendRequest:ir,connectServer:Ru,disconnectServer:Cu,disconnectAll:Vy,callTool:Au,getAllTools:Ou,getMCPToolDefinitions:Jy,routeMCPCall:Zy,listServers:Qy,connectAll:e$}});var cr=re((Zk,Iu)=>{var Mu=require("fs"),sa=require("path"),ar=[],Ms=[],yn={},Ls=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function Lu(t,e){if(!t||!t.function||!t.function.name)return{ok:!1,error:"Tool definition must have function.name"};if(typeof e!="function")return{ok:!1,error:"Handler must be a function"};let s=t.function.name;return Ms.some(n=>n.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(Ms.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function Pu(t,e){return Ls.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(yn[t]||(yn[t]=[]),yn[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Ls.join(", ")}`}}async function oa(t,e){let s=yn[t]||[],n=e;for(let o of s)try{let r=await o(n);r!==void 0&&(n=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return n}function t$(){let t=sa.join(process.cwd(),".nex","plugins"),e=[];if(!Mu.existsSync(t))return{loaded:0,errors:[]};let s=Mu.readdirSync(t).filter(o=>o.endsWith(".js")),n={registerTool:Lu,registerHook:Pu,EVENTS:Ls};for(let o of s){let r=sa.join(t,o);try{let i=require(r);if(typeof i=="function")i(n);else if(typeof i.setup=="function")i.setup(n);else{e.push(`${o}: Plugin must export a function or { setup: function }`);continue}ar.push({name:i.name||sa.basename(o,".js"),filePath:r})}catch(i){e.push(`${o}: ${i.message}`)}}return{loaded:ar.length,errors:e}}function n$(){return Ms.map(t=>t.definition)}async function s$(t,e,s={}){let n=Ms.find(a=>a.definition.function.name===t);if(!n)return null;let o=await oa("beforeToolExec",{name:t,args:e,options:s}),r=await n.handler(o.args||e,s);return(await oa("afterToolExec",{name:t,args:e,result:r})).result||r}function o$(){return[...ar]}function r$(){let t={};for(let e of Ls)t[e]=(yn[e]||[]).length;return t}function i$(){ar.length=0,Ms.length=0;for(let t of Object.keys(yn))delete yn[t]}Iu.exports={registerTool:Lu,registerHook:Pu,emit:oa,loadPlugins:t$,getPluginToolDefinitions:n$,executePluginTool:s$,getLoadedPlugins:o$,getHookCounts:r$,clearPlugins:i$,EVENTS:Ls}});var ra=re((Qk,Fu)=>{var{getSkillToolDefinitions:a$}=ea(),{getMCPToolDefinitions:c$}=na(),{getPluginToolDefinitions:l$}=cr(),lr=new Map;function ju(){let{TOOL_DEFINITIONS:t}=ts();return[...t,...a$(),...c$(),...l$()]}function Du(t){if(lr.has(t))return lr.get(t);let s=ju().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return lr.set(t,n),n}function u$(){lr.clear()}function ur(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=qu(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function qu(t,e){let s=t.length,n=e.length,o=Array.from({length:s+1},()=>Array(n+1).fill(0));for(let r=0;r<=s;r++)o[r][0]=r;for(let r=0;r<=n;r++)o[0][r]=r;for(let r=1;r<=s;r++)for(let i=1;i<=n;i++)o[r][i]=t[r-1]===e[i-1]?o[r-1][i-1]:1+Math.min(o[r-1][i],o[r][i-1],o[r-1][i-1]);return o[s][n]}function d$(t,e){let s=Du(t);if(s===null){let d=ju().map(h=>h.function.name),f=ur(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
99
|
+
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),i=[],a={...e},c=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=ur(u,r);d&&!o.includes(d)?(a[u]=e[d],delete a[d],c=!0):i.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in a||"n"in a)&&!o.includes("-n")&&(delete a["-n"],delete a.n,c=!0),("-i"in a||"--ignore-case"in a)&&"ignore_case"in(s.properties||{})&&(a.ignore_case=!0,delete a["-i"],delete a["--ignore-case"],c=!0),("-r"in a||"--recursive"in a)&&(delete a["-r"],delete a["--recursive"],c=!0)),t==="read_file"&&("offset"in a&&!("line_start"in a)&&(a.line_start=a.offset,delete a.offset,c=!0),"start_line"in a&&!("line_start"in a)&&(a.line_start=a.start_line,delete a.start_line,c=!0),"end_line"in a&&!("line_end"in a)&&(a.line_end=a.end_line,delete a.end_line,c=!0));for(let u of Object.keys(a))if(!o.includes(u)){let d=ur(u,o);if(d&&!(d in a))a[d]=a[u],delete a[u],c=!0;else if(!c){let f=d?` Did you mean "${d}"?`:"";i.push(`Unknown parameter "${u}".${f}`)}}for(let u of Object.keys(a)){if(!s.properties[u])continue;let d=s.properties[u].type,f=typeof a[u];d==="string"&&f==="number"?(a[u]=String(a[u]),c=!0):d==="number"&&f==="string"&&!isNaN(a[u])?(a[u]=Number(a[u]),c=!0):d==="boolean"&&f==="string"&&(a[u]=a[u]==="true",c=!0)}return i.length>0&&!c?{valid:!1,error:`Tool "${t}" argument errors:
|
|
100
100
|
`+i.map(u=>` - ${u}`).join(`
|
|
101
101
|
`)+`
|
|
102
102
|
|
|
103
|
-
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:c?a:null}}function
|
|
103
|
+
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:c?a:null}}function f$(t,e){let s=[],n={...t};if(!n.function&&!n.name)return s.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:n,errors:s};if(!n.function&&n.name&&(n.function={name:n.name,arguments:n.arguments||n.args||{}},delete n.name,delete n.args),n.function&&n.function.args!==void 0&&n.function.arguments===void 0&&(n.function.arguments=n.function.args,delete n.function.args),n.function&&(n.function.arguments===void 0||n.function.arguments===null)&&(n.function.arguments={}),n.function&&typeof n.function.arguments=="string"){let o=n.function.arguments;if(o.trim()==="")n.function.arguments={};else try{n.function.arguments=JSON.parse(o)}catch(r){return s.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:n,errors:s}}}return n.function&&typeof n.function.arguments!="object"?(s.push(`Arguments must be an object, got ${typeof n.function.arguments}`),{valid:!1,normalized:n,errors:s}):!n.function.name||typeof n.function.name!="string"?(s.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:n,errors:s}):{valid:s.length===0,normalized:n,errors:s}}Fu.exports={validateToolArgs:d$,validateToolCallFormat:f$,closestMatch:ur,levenshtein:qu,getCachedSchema:Du,clearSchemaCache:u$}});var Hu=re((ev,Uu)=>{var{levenshtein:dr}=ra(),p$=200,h$=.3,m$=2;function ia(t){return t.replace(/\r\n/g,`
|
|
104
104
|
`).replace(/\r/g,`
|
|
105
|
-
`).replace(/\t/g," ".repeat(
|
|
105
|
+
`).replace(/\t/g," ".repeat(m$)).split(`
|
|
106
106
|
`).map(e=>{let s=e.replace(/\s+$/,""),n=s.match(/^(\s*)(.*)/);if(!n)return s;let[,o,r]=n;return o+r.replace(/ {2,}/g," ")}).join(`
|
|
107
|
-
`)}function
|
|
107
|
+
`)}function g$(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=ia(t),n=ia(e);if(!s.includes(n))return null;let o=t.split(`
|
|
108
108
|
`),r=s.split(`
|
|
109
109
|
`),i=n.split(`
|
|
110
110
|
`),a=i[0],c=i[i.length-1];for(let l=0;l<=r.length-i.length;l++){let u=!0;for(let d=0;d<i.length;d++)if(r[l+d]!==i[d]){u=!1;break}if(u)return o.slice(l,l+i.length).join(`
|
|
111
|
-
`)}if(i.length===1){for(let l=0;l<r.length;l++)if(r[l].indexOf(n)!==-1)return o[l]}return null}function
|
|
111
|
+
`)}if(i.length===1){for(let l=0;l<r.length;l++)if(r[l].indexOf(n)!==-1)return o[l]}return null}function y$(t,e){if(!t||!e)return null;let s=t.split(`
|
|
112
112
|
`),o=e.split(`
|
|
113
|
-
`).length;return s.length===0||o===0?null:o===1
|
|
114
|
-
`),l=
|
|
115
|
-
`),h=
|
|
116
|
-
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],a=r+1;for(let c of
|
|
117
|
-
`).filter(Boolean),
|
|
118
|
-
`);for(let o=0;o<n.length;o++){let r=n[o],i=o+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/(?:export\s+)?class\s+(\w+)/);c&&s.push({type:"class",name:c[1],line:i});let l=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);l&&s.push({type:"function",name:l[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of f)/^\w+$/.test(h)&&s.push({type:"export",name:h,line:i})}let d=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(d){let f=d[1]||d[2];s.push({type:"import",name:f,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/^class\s+(\w+)/);c&&s.push({type:"class",name:c[1],line:i});let l=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);l&&s.push({type:"import",name:l[1]||l[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/^type\s+(\w+)\s+struct/);c&&s.push({type:"class",name:c[1],line:i})}}return s}async function
|
|
113
|
+
`).length;return s.length===0||o===0?null:o===1?$$(s,e):b$(s,e,o)}function Bu(t){return Math.max(1,Math.floor(t/p$))}function Wu(t,e){return t<=Math.ceil(e*h$)}function $$(t,e){let s=e.trim(),n=Bu(t.length),o=null,r=1/0;for(let i=0;i<t.length;i+=n){let a=t[i];if(!a.trim())continue;let c=dr(a.trim(),s);c<r&&(r=c,o={text:a,distance:c,line:i+1})}return o&&n>1&&(o=w$(t,s,o,n)||o,r=o.distance),Wu(r,e.length)?o:null}function w$(t,e,s,n){let o=s.line-1,r=Math.max(0,o-n),i=Math.min(t.length-1,o+n),a=s.distance,c=null;for(let l=r;l<=i;l++){let u=t[l];if(!u.trim())continue;let d=dr(u.trim(),e);d<a&&(a=d,c={text:u,distance:d,line:l+1})}return c}function b$(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Bu(n),r=null,i=1/0;for(let a=0;a<n;a+=o){let c=t.slice(a,a+s).join(`
|
|
114
|
+
`),l=dr(c,e);l<i&&(i=l,r={text:c,distance:l,line:a+1})}return r&&o>1&&(r=_$(t,e,r,o,s,n)||r,i=r.distance),Wu(i,e.length)?r:null}function _$(t,e,s,n,o,r){let i=s.line-1,a=Math.max(0,i-n),c=Math.min(r-1,i+n),l=s.distance,u=null;for(let d=a;d<=c;d++){let f=t.slice(d,d+o).join(`
|
|
115
|
+
`),h=dr(f,e);h<l&&(l=h,u={text:f,distance:h,line:d+1})}return u}Uu.exports={normalizeWhitespace:ia,fuzzyFindText:g$,findMostSimilar:y$}});var Gu=re((nv,Yu)=>{var{C:tv}=He(),x$=[{name:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{name:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{name:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{name:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{name:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{name:"GitHub Token",regex:/ghp_[a-zA-Z0-9]{36}/i},{name:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{name:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{name:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"'][^'"']{8,}/i}],k$=[{name:"TODO",regex:/\bTODO\b/i,severity:"warn"},{name:"FIXME",regex:/\bFIXME\b/i,severity:"warn"},{name:"Debugger",regex:/\bdebugger\b/,severity:"error",ext:[".js",".ts",".jsx",".tsx"]},{name:"eval()",regex:/\beval\s*\(/,severity:"warn",ext:[".js",".ts",".jsx",".tsx"]},{name:"Console Log",regex:/\bconsole\.log\(/,severity:"info",ext:[".js",".ts",".jsx",".tsx"]},{name:"ANSI Code",regex:/\\x1b\[[0-9;]*m/,severity:"warn",message:"Avoid hardcoded ANSI codes; use cli/ui.js instead."}];function v$(t,e){let s=e.split(`
|
|
116
|
+
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],a=r+1;for(let c of x$)c.regex.test(i)&&n.push({line:a,message:`Potential secret detected: ${c.name}`,severity:"error"});for(let c of k$)c.ext&&!c.ext.includes(o)||c.regex.test(i)&&n.push({line:a,message:c.message||`Found ${c.name}`,severity:c.severity||"warn"})}return s.length>500&&n.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),n}function S$(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}Yu.exports={runDiagnostics:v$,getMemoryUsage:S$}});var da=re((sv,Zu)=>{var ns=require("fs").promises,ss=require("path"),{exec:E$}=require("util").promisify(require("child_process").exec),os=[],ua=null,fr=!1,ca=0,T$=6e4;function zu(t){return!(os.length===0||ua!==t||Date.now()-ca>T$)}async function Xu(t){if(!fr&&!zu(t)){fr=!0,ua=t;try{try{let{stdout:n}=await E$("rg --files",{cwd:t,timeout:5e3});os=n.split(`
|
|
117
|
+
`).filter(Boolean),ca=Date.now(),fr=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await ns.readdir(n,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let a=o?`${o}/${i.name}`:i.name;i.isDirectory()?await s(ss.join(n,i.name),a):e.push(a)}};await s(t,""),os=e,ca=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{fr=!1}}}function la(){return os}function R$(){return ua}function C$(t){return os.filter(e=>ss.basename(e)===t)}function A$(t){let e=t.toLowerCase();return os.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}var aa=null,Ku=0,O$=12e4,N$=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Vu(t,e){let s=[],n=t.split(`
|
|
118
|
+
`);for(let o=0;o<n.length;o++){let r=n[o],i=o+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let a=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/(?:export\s+)?class\s+(\w+)/);c&&s.push({type:"class",name:c[1],line:i});let l=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);l&&s.push({type:"function",name:l[1],line:i});let u=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(u){let f=u[1].split(",").map(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of f)/^\w+$/.test(h)&&s.push({type:"export",name:h,line:i})}let d=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(d){let f=d[1]||d[2];s.push({type:"import",name:f,line:i})}}if(e===".py"){let a=r.match(/^(?:async\s+)?def\s+(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/^class\s+(\w+)/);c&&s.push({type:"class",name:c[1],line:i});let l=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);l&&s.push({type:"import",name:l[1]||l[2],line:i})}if(e===".go"){let a=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);a&&s.push({type:"function",name:a[1],line:i});let c=r.match(/^type\s+(\w+)\s+struct/);c&&s.push({type:"class",name:c[1],line:i})}}return s}async function Ju(t){t=t||process.cwd();let e=ss.join(t,".nex","index","content-index.json"),s={};if(aa&&Date.now()-Ku<O$)return aa;try{let i=await ns.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}la().length===0&&await Xu(t);let o={files:{}},r=!1;for(let i of la()){let a=ss.extname(i);if(!N$.has(a))continue;let c=ss.join(t,i);try{let u=(await ns.stat(c)).mtimeMs;if(s.files[i]&&s.files[i].mtime===u){o.files[i]=s.files[i];continue}let d=await ns.readFile(c,"utf-8"),f=Vu(d,a);o.files[i]={defs:f,mtime:u},r=!0}catch{}}if(r){let i=ss.join(t,".nex","index");await ns.mkdir(i,{recursive:!0}),await ns.writeFile(e,JSON.stringify(o),"utf-8")}return aa=o,Ku=Date.now(),o}async function M$(t,e){let s=await Ju(),n=[],o=t.toLowerCase();for(let[r,i]of Object.entries(s.files))for(let a of i.defs)e&&a.type!==e||a.name.toLowerCase().includes(o)&&n.push({file:r,type:a.type,name:a.name,line:a.line});return n.sort((r,i)=>{let a=r.name.toLowerCase()===o?0:1,c=i.name.toLowerCase()===o?0:1;if(a!==c)return a-c;let l=r.name.toLowerCase().startsWith(o)?0:1,u=i.name.toLowerCase().startsWith(o)?0:1;return l-u}),n.slice(0,50)}Zu.exports={refreshIndex:Xu,getFileIndex:la,getIndexedCwd:R$,findFileInIndex:C$,searchIndex:A$,isIndexValid:zu,buildContentIndex:Ju,searchContentIndex:M$,extractDefinitions:Vu}});var pa=re((ov,nd)=>{var pr=require("fs"),mr=require("path"),gr=require("os"),{execFile:L$}=require("child_process"),{promisify:P$}=require("util"),fa=P$(L$),I$=mr.join(gr.homedir(),".nex","servers.json"),hr=mr.join(gr.tmpdir(),"nex-ssh-sockets");function j$(){return mr.join(process.cwd(),".nex","servers.json")}function Qu(){let t=n=>{if(!pr.existsSync(n))return{};try{return JSON.parse(pr.readFileSync(n,"utf-8"))}catch{return{}}},e=t(I$),s=t(j$());return{...e,...s}}function D$(t){let e=Qu();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:o}}let s=Object.keys(e),n=s.length?`Available profiles: ${s.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${n}`)}function q$(){pr.existsSync(hr)||pr.mkdirSync(hr,{recursive:!0})}function ed(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,gr.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),q$();let s=t.user?`${t.user}@${t.host}`:t.host,n=mr.join(hr,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function td(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,gr.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function F$(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=ed(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await fa("ssh",[...o,r],{timeout:s,maxBuffer:4194304});return{stdout:i||"",stderr:a||"",exitCode:0}}catch(i){let a=typeof i.code=="number"?i.code:1,c=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:c,exitCode:a,error:yr(c,t)}}}async function B$(t,e,s,{timeout:n=12e4}={}){let o=td(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await fa("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Uploaded ${e} \u2192 ${r}:${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(yr(a,t)||a)}}async function W$(t,e,s,{timeout:n=12e4}={}){let o=td(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await fa("scp",o,{timeout:n,maxBuffer:1048576});return i||a||`Downloaded ${r}:${e} \u2192 ${s}`}catch(i){let a=(i.stderr||i.message||"").toString();throw new Error(yr(a,t)||a)}}function yr(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
|
|
119
119
|
HINT: Connection refused on ${e.host}:${s}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${s} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let s=e.key?`key: ${e.key}`:"SSH agent";return`${t}
|
|
120
120
|
HINT: Auth failed using ${s} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
|
|
121
121
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
122
122
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
123
123
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
124
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function
|
|
125
|
-
`,"utf-8")}
|
|
124
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function U$(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,n=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${s}${n}${o}${r}${i}`}nd.exports={loadServerProfiles:Qu,resolveProfile:D$,buildSSHArgs:ed,sshExec:F$,scpUpload:B$,scpDownload:W$,enrichSSHError:yr,formatProfile:U$,SSH_SOCKET_DIR:hr}});var rd=re((rv,od)=>{var Ps=require("fs"),ha=require("path"),H$=ha.join(".nex","deploy.json");function ma(){return ha.join(process.cwd(),H$)}function sd(){let t=ma();if(!Ps.existsSync(t))return{};try{return JSON.parse(Ps.readFileSync(t,"utf-8"))}catch{return{}}}function Y$(t){let e=sd();if(e[t])return{...e[t],_name:t};let s=Object.keys(e),n=s.length?`Available: ${s.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${n}`)}function G$(t){let e=ha.join(process.cwd(),".nex");Ps.existsSync(e)||Ps.mkdirSync(e,{recursive:!0}),Ps.writeFileSync(ma(),JSON.stringify(t,null,2)+`
|
|
125
|
+
`,"utf-8")}od.exports={loadDeployConfigs:sd,resolveDeployConfig:Y$,saveDeployConfigs:G$,getDeployConfigPath:ma}});var qs=re((iv,cd)=>{var{getActiveModel:K$,getActiveProviderName:z$}=Ge(),Is={essential:["bash","read_file","write_file","edit_file","list_directory"],standard:["bash","read_file","write_file","edit_file","list_directory","search_files","glob","grep","ask_user","git_status","git_diff","git_log","task_list","ssh_exec","service_manage","service_logs","container_list","container_logs","container_exec","container_manage","deploy"],full:null},js={"qwen3-coder:480b":"full","qwen3-coder-next":"full","kimi-k2.5":"full","kimi-k2:1t":"full","kimi-k2-thinking":"full","deepseek-v3.2":"full","deepseek-v3.1:671b":"full","devstral-2:123b":"full","devstral-small-2:24b":"standard","cogito-2.1:671b":"full","qwen3-next:80b":"full","qwen3.5:397b-cloud":"full","qwen3.5:397b":"full","qwen3.5:122b-a10b":"full","qwen3.5:35b-a3b":"full","qwen3.5:27b":"full","qwen3.5:9b":"standard","qwen3.5:4b":"essential","qwen3.5:2b":"essential","qwen3.5:0.8b":"essential","mistral-large-3:675b":"full","gpt-oss:120b":"full","minimax-m2.5":"full","glm-5":"full","glm-4.7":"standard","gemma3:27b":"standard","gemma3:12b":"essential","gemma3:4b":"essential","ministral-3:14b":"standard","ministral-3:8b":"essential","gpt-4o":"full","gpt-4.1":"full",o1:"full",o3:"full","o4-mini":"full","claude-sonnet":"full","claude-sonnet-4-5":"full","claude-opus":"full","claude-haiku":"standard","claude-sonnet-4":"full","gemini-3.1-pro-preview":"full","gemini-3-flash-preview":"full","gemini-2.5-pro":"full","gemini-2.5-flash":"full","gemini-2.0-flash":"standard","gemini-2.0-flash-lite":"essential"},Ds={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Pt={};function ad(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Pt=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Pt={}}}ad();function ga(){let e=K$()?.id,s=z$();return e&&Pt[e]?Pt[e]:s&&Pt[`${s}:*`]?Pt[`${s}:*`]:e&&js[e]?js[e]:s&&Ds[s]?Ds[s]:"full"}var X$=new Set(["claude-sonnet","claude-sonnet-4-5","claude-sonnet-4","claude-opus","claude-haiku","gpt-4o","gpt-4.1","o1","o3","o4-mini","kimi-k2:1t","kimi-k2.5","kimi-k2-thinking","qwen3-coder:480b","qwen3-coder-next","deepseek-v3.2","deepseek-v3.1:671b"]),id={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function V$(t,e){return t&&(X$.has(t)||t.startsWith("claude-"))?"strict":e&&id[e]?id[e]:"fuzzy"}function J$(t,e){return t&&Pt[t]?Pt[t]:e&&Pt[`${e}:*`]?Pt[`${e}:*`]:t&&js[t]?js[t]:e&&Ds[e]?Ds[e]:"full"}function Z$(t,e){let s=e||ga();if(s==="full"||!Is[s])return t;let n=new Set(Is[s]);return t.filter(o=>n.has(o.function.name))}function Q$(){let t=ga(),e=Is[t]?Is[t].length:"all";return{tier:t,toolCount:e}}cd.exports={filterToolsForModel:Z$,getActiveTier:ga,getModelTier:J$,getEditMode:V$,getTierInfo:Q$,TIERS:Is,MODEL_TIERS:js,PROVIDER_DEFAULT_TIER:Ds,loadConfigOverrides:ad}});var Bs=re((av,dd)=>{var ya=null,Yt=null,Fs=null,ld=`Playwright is not installed. Install with:
|
|
126
126
|
npm install playwright && npx playwright install chromium
|
|
127
|
-
Then restart nex-code.`;function
|
|
128
|
-
...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function
|
|
129
|
-
`)}function
|
|
127
|
+
Then restart nex-code.`;function ud(){if(Fs!==null)return Fs;try{require("playwright"),Fs=!0}catch{Fs=!1}return Fs}async function $r(){if(!ud())throw new Error(ld);return ya||(ya=require("playwright")),(!Yt||!Yt.isConnected())&&(Yt=await ya.chromium.launch({headless:!0})),Yt}async function ew(){if(Yt){try{await Yt.close()}catch{}Yt=null}}process.on("exit",()=>{if(Yt)try{Yt.close()}catch{}});async function tw(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await $r()).newPage();try{await o.goto(t,{waitUntil:s,timeout:e});let r=await o.title(),i=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(l=>l.remove()),document.body?.innerText||"")),a=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(c=>({text:(c.innerText||c.textContent||"").trim().substring(0,80),href:c.href})).filter(c=>c.text&&c.href&&!c.href.startsWith("javascript:")));return{title:r,url:o.url(),text:i.substring(0,8e3)+(i.length>8e3?`
|
|
128
|
+
...(truncated)`:""),links:a.slice(0,20)}}finally{await o.close()}}async function nw(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await $r()).newPage();try{await i.setViewportSize({width:e,height:s}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let a=await i.screenshot({type:"png",fullPage:n}),c=require("os"),l=require("path"),u=require("fs"),d=l.join(c.tmpdir(),`nex-screenshot-${Date.now()}.png`);return u.writeFileSync(d,a),{path:d,base64:a.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function sw(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await $r()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function ow(t,{selector:e,value:s,submit:n=!1,timeout:o=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let i=await(await $r()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(s)),n&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}dd.exports={isPlaywrightAvailable:ud,browserNavigate:tw,browserScreenshot:nw,browserClick:sw,browserFill:ow,closeBrowser:ew,INSTALL_MSG:ld}});var $a=re((cv,fd)=>{var{C:Ne}=He(),Us="",tt=[],Ws=0,$n=null;function rw(t){$n=t}function iw(t,e){Us=t,tt=[],Ws=0;for(let n of e){Ws++;let o=`t${Ws}`;tt.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${Ws}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=tt.map(n=>({...n}));return $n&&$n("create",{name:t,tasks:s}),s}function aw(t,e,s){let n=tt.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),$n&&$n("update",{id:t,status:e,result:s}),{...n}):null}function cw(){return{name:Us,tasks:tt.map(t=>({...t}))}}function lw(){Us="",tt=[],Ws=0,$n&&$n("clear",{})}function uw(){return tt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=tt.find(n=>n.id===e);return s&&s.status==="done"}))}function dw(){if(tt.length===0)return`${Ne.dim}No active tasks${Ne.reset}`;let t=[];Us&&(t.push(` ${Ne.bold}${Ne.cyan}Tasks: ${Us}${Ne.reset}`),t.push(` ${Ne.dim}${"\u2500".repeat(40)}${Ne.reset}`));for(let o of tt){let r,i;switch(o.status){case"done":r="\u2713",i=Ne.green;break;case"in_progress":r="\u2192",i=Ne.cyan;break;case"failed":r="\u2717",i=Ne.red;break;default:r="\xB7",i=Ne.dim}let a=o.dependsOn.length>0?` ${Ne.dim}(after: ${o.dependsOn.join(", ")})${Ne.reset}`:"",c=`[${o.status}]`,l=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Ne.reset} ${Ne.bold}${o.id}${Ne.reset} ${l.padEnd(40)} ${i}${c}${Ne.reset}${a}`),o.result&&o.status==="done"){let u=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Ne.dim}\u2192 ${u}${Ne.reset}`)}}let e=tt.filter(o=>o.status==="done").length,s=tt.filter(o=>o.status==="failed").length,n=tt.length;return t.push(` ${Ne.dim}${"\u2500".repeat(40)}${Ne.reset}`),t.push(` ${Ne.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${Ne.reset}`),t.join(`
|
|
129
|
+
`)}function fw(){return tt.length>0&&tt.some(t=>t.status==="pending"||t.status==="in_progress")}fd.exports={createTasks:iw,updateTask:aw,getTaskList:cw,clearTasks:lw,getReadyTasks:uw,renderTaskList:dw,setOnChange:rw,hasActiveTasks:fw}});var wr=re((lv,hd)=>{var Hs={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:12,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
|
|
130
130
|
Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
|
|
131
131
|
You excel at sysadmin, frontend, and multi-step coding tasks.
|
|
132
132
|
Prefer action over narration \u2014 read, fix, verify, done.`},"devstral-small":{staleWarn:2e4,staleAbort:6e4,investigationCap:10,postEditCap:8,briefing:`You are devstral-small, a fast and lightweight coding model.
|
|
@@ -139,31 +139,62 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:2e4,staleAbort:6e4,i
|
|
|
139
139
|
Prioritize decisive, targeted edits. Read only what you need, then fix.
|
|
140
140
|
Stay on-scope \u2014 your strength is focused, efficient coding tasks.`},"qwen3-vl":{staleWarn:6e4,staleAbort:18e4,investigationCap:15,postEditCap:12,briefing:`You are qwen3-vl, the highest-ranked model for data, frontend, and agentic tasks.
|
|
141
141
|
Trust your reasoning. Use tools thoroughly when the task demands it.
|
|
142
|
-
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
142
|
+
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},pd={staleWarn:6e4,staleAbort:12e4,investigationCap:12,postEditCap:10};function pw(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let r of Object.keys(Hs))e.startsWith(r)&&r.length>n&&(s=r,n=r.length);let o=s?{...Hs[s]}:{...pd};for(let[r,i]of[["NEX_STALE_WARN_MS","staleWarn"],["NEX_STALE_ABORT_MS","staleAbort"]])if(process.env[r]){let a=parseInt(process.env[r],10);Number.isInteger(a)&&a>=1e3&&a<=3e5&&(o[i]=a)}return o}function hw(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let o of Object.keys(Hs))e.startsWith(o)&&o.length>n&&(s=o,n=o.length);return s&&Hs[s].briefing||""}hd.exports={getModelProfile:pw,getModelBriefing:hw,PROFILES:Hs,DEFAULTS:pd}});var ba=re((uv,bd)=>{var{callChat:mw}=Ge(),{estimateTokens:wa}=It(),md=process.env.NEX_COMPACTION!=="false",gd=6,yd=2e3,$d=3,gw=`Your task is to create a detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions.
|
|
143
|
+
This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context.
|
|
144
|
+
|
|
145
|
+
Before providing your final summary, wrap your analysis in <analysis> tags to organize your thoughts and ensure you've covered all necessary points. In your analysis process:
|
|
146
|
+
1. Chronologically analyze each message. For each section thoroughly identify:
|
|
147
|
+
- The user's explicit requests and intents
|
|
148
|
+
- Your approach to addressing the user's requests
|
|
149
|
+
- Key decisions, technical concepts and code patterns
|
|
150
|
+
- Specific details like file names, code snippets, function signatures, file edits
|
|
151
|
+
- Errors that you ran into and how you fixed them
|
|
152
|
+
- Specific user feedback and direction changes
|
|
153
|
+
2. Double-check for technical accuracy and completeness.
|
|
154
|
+
|
|
155
|
+
Your summary MUST include these sections:
|
|
156
|
+
|
|
157
|
+
1. Primary Request and Intent: Capture all of the user's explicit requests and intents in detail
|
|
158
|
+
2. Key Technical Concepts: List all important technical concepts, technologies, and frameworks discussed
|
|
159
|
+
3. Files and Code Sections: Enumerate specific files examined, modified, or created \u2014 include full code snippets where applicable and why each is important
|
|
160
|
+
4. Errors and Fixes: List all errors encountered and how they were resolved; note any user feedback that changed your approach
|
|
161
|
+
5. Problem Solving: Document problems solved and any ongoing troubleshooting
|
|
162
|
+
6. All User Messages: List ALL user messages that are not tool results \u2014 critical for understanding feedback and changing intent
|
|
163
|
+
7. Pending Tasks: Outline any pending tasks explicitly requested
|
|
164
|
+
8. Current Work: Describe precisely what was being worked on immediately before this summary, including file names and code snippets
|
|
165
|
+
9. Optional Next Step: The next step directly in line with the user's most recent explicit request. Include direct quotes from the conversation showing exactly what task you were working on.
|
|
166
|
+
|
|
167
|
+
Format your output as:
|
|
168
|
+
<analysis>
|
|
169
|
+
[Your thought process]
|
|
170
|
+
</analysis>
|
|
171
|
+
|
|
172
|
+
<summary>
|
|
173
|
+
[Sections 1-9 above]
|
|
174
|
+
</summary>`,wn=0;async function yw(t){if(!md||t.length<gd||wn>=$d)return null;let e=[{role:"system",content:gw},{role:"user",content:wd(t)}];try{let n=((await mw(e,[],{temperature:0,maxTokens:yd})).content||"").trim();if(!n)return wn++,null;let o=n.match(/<summary>([\s\S]*?)<\/summary>/);if(o?n=o[1].trim():n=n.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!n)return wn++,null;let r=t.reduce((a,c)=>a+wa(c.content||"")+(c.tool_calls?wa(JSON.stringify(c.tool_calls)):0),0),i=wa(n);return i>=r*.8?(wn++,null):(wn=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
175
|
+
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return wn++,null}}function $w(){wn=0}function wd(t){return t.map(e=>{let s=e.role==="tool"?"tool_result":e.role,n=(e.content||"").substring(0,500);if(e.tool_calls){let o=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${s}] ${n}
|
|
149
176
|
tools: ${o}`}return`[${s}] ${n}`}).join(`
|
|
150
177
|
|
|
151
|
-
`)}
|
|
152
|
-
`);if(o.length<=10){let
|
|
178
|
+
`)}bd.exports={compactMessages:yw,formatMessagesForSummary:wd,resetCompactionFailures:$w,COMPACTION_ENABLED:md,COMPACTION_MIN_MESSAGES:gd,COMPACTION_SUMMARY_BUDGET:yd,MAX_CONSECUTIVE_FAILURES:$d}});var It=re((dv,Ad)=>{var ww=require("path");function xd(){return Ge().getActiveModel()}var bw={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},_w={devstral:3.8,mistral:3.8,ministral:3.8,codestral:3.8,qwen:3.5,deepseek:3.6,kimi:3.7,gemma:4,llama:3.8,cogito:3.6,phi:4},bn=new Map,_d=1e3,_a=new WeakMap,_n=null;function xw(){if(_n!==null)return _n;try{let t=xd(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[n,o]of Object.entries(_w))if(s.startsWith(n))return _n=o,_n;return _n=bw[e]||4,_n}catch{return 4}}function kw(){_n=null}function xn(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=120?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length>>1,(t.length>>1)+30)}:${t.substring(t.length-30)}`,s=bn.get(e);if(s!==void 0)return bn.delete(e),bn.set(e,s),s;let n=Math.ceil(t.length/xw());if(bn.size>=_d){let o=_d>>1,r=bn.keys();for(let i=0;i<o;i++)bn.delete(r.next().value)}return bn.set(e,n),n}function vw(t){if(_a.has(t))return _a.get(t);let e=JSON.stringify(t);return _a.set(t,e),e}function as(t){let s=4;if(t.content&&(s+=xn(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=xn(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=xn(o):o&&(s+=xn(JSON.stringify(o)))}return s}function wt(t){let e=0;for(let s of t)e+=as(s);return e}function Sw(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let s=t?t.length:0,n=e.length,o=0;for(let r=s;r<n;r++)o+=as(e[r]);return o}function br(t){return!t||t.length===0?0:xn(JSON.stringify(t))}function _r(){return xd()?.contextWindow||32768}function Ew(t,e){let s=wt(t),n=br(e),o=s+n,r=_r(),i=r>0?o/r*100:0,a=0,c=0,l=0;for(let u of t){let d=as(u);u.role==="system"?a+=d:u.role==="tool"?l+=d:c+=d}return{used:o,limit:r,percentage:Math.round(i*10)/10,breakdown:{system:a,conversation:c,toolResults:l,toolDefinitions:n},messageCount:t.length}}var Ys=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,kd=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,vd=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Sd={essential:.6,standard:.65,full:Math.min(Ys,.68)};function Ed(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Ys;try{let{getActiveTier:t}=qs(),e=t();return Sd[e]??Ys}catch{return Ys}}var Tw=200,Rw=1e3;function Td(t,e){if(!t||t.length<=e)return t;let n=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=n)return t;let o=t.split(`
|
|
179
|
+
`);if(o.length<=10){let g=Math.floor(n*.6),m=Math.floor(n*.4),b=t.substring(0,g),x=t.substring(t.length-m);return b+`
|
|
153
180
|
...(${t.length} chars total)...
|
|
154
|
-
`+
|
|
181
|
+
`+x}let r=Math.floor(o.length*.4),i=Math.floor(o.length*.4),a=[],c=0,l=Math.floor(n*.4);for(let g=0;g<r&&c<l;g++)if(c+o[g].length+1>l&&o[g].trim().startsWith("```")){a.push(o[g]),c+=o[g].length+1;let m=g+1;for(;m<o.length&&c<l*1.5&&!o[m].trim().startsWith("```");)a.push(o[m]),c+=o[m].length+1,m++;m<o.length&&o[m].trim().startsWith("```")&&(a.push(o[m]),c+=o[m].length+1),g=m}else a.push(o[g]),c+=o[g].length+1;let u=[],d=0,f=Math.floor(n*.4);for(let g=o.length-1;g>=o.length-i&&d<f;g--)if(d+o[g].length+1>f&&o[g].trim().startsWith("```")){u.push(o[g]),d+=o[g].length+1;let m=g-1;for(;m>=0&&d<f*1.5&&!o[m].trim().startsWith("```");)u.push(o[m]),d+=o[m].length+1,m--;m>=0&&o[m].trim().startsWith("```")&&(u.push(o[m]),d+=o[m].length+1),g=m}else u.push(o[g]),d+=o[g].length+1;u.reverse();let h=o.length-a.length-u.length;return a.join(`
|
|
155
182
|
`)+`
|
|
156
183
|
...(${h} lines omitted, ${o.length} total)...
|
|
157
184
|
`+u.join(`
|
|
158
|
-
`)}function
|
|
159
|
-
...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),o}return t}function
|
|
185
|
+
`)}function is(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:Rw,n=e==="aggressive"?50:e==="medium"?100:Tw;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:Td(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
|
|
186
|
+
...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),o}return t}function Rd(t,e,s,n){let o=0;if(t.role==="system")return 100;if(t.role==="user")o+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?o+=30:o+=15}else t.role==="assistant"&&(o+=t.tool_calls?20:10);let r=s>1?e/(s-1):1;if(o+=Math.round(r*30),n&&n.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),a=0;for(let c of n)(i.includes(c)||i.includes(ww.basename(c)))&&a++;o+=Math.min(30,a*10)}return Math.min(100,o)}function Cd(t,e=10){let s=new Set,n=t.slice(-e),o=/(?:\/[\w.-]+)+\.\w+/g;for(let r of n){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(o);a&&a.forEach(c=>s.add(c))}return s}function Cw(t,{filesModified:e=new Set,currentPhase:s=null}={}){let n=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");n.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}s&&n.push(`Current phase: ${s}`);let o=t.filter(r=>r.role==="assistant"&&typeof r.content=="string"&&r.content.trim().length>30).slice(-3).map(r=>r.content.trim().slice(0,200).replace(/\n+/g," "));return o.length>0&&n.push(`Recent progress:
|
|
187
|
+
`+o.map(r=>`- ${r}`).join(`
|
|
188
|
+
`)),n.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
|
|
189
|
+
${n.join(`
|
|
190
|
+
`)}`,_pinned:!0,_progressSnapshot:!0}}var rs={msgCount:-1,lastMsgRef:null,result:null};function Aw(){rs={msgCount:-1,lastMsgRef:null,result:null}}async function Ow(t,e,s={}){let n=t.length>0?t[t.length-1]:null;if(!s.force&&rs.result&&t.length===rs.msgCount&&n===rs.lastMsgRef)return rs.result;let o=s.threshold??Ed(),r=s.safetyMargin??kd,i=s.keepRecent??vd,a=_r(),c=br(e),l=Math.floor(a*(o-r)),u=l-c,d=wt(t),f=d+c;if(f<=l){let se={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return rs={msgCount:t.length,lastMsgRef:n,result:se},se}let h=d,g=null,m=0;t.length>0&&t[0].role==="system"&&(g=t[0],m=1);let b=Math.max(m,t.length-i),x=t.slice(m,b),j=t.slice(b),G=x.filter(se=>se._pinned),L=x.filter(se=>!se._compacted&&!se._pinned);if(L.length>=6)try{let{compactMessages:se}=ba(),T=await se(L);if(T){let Te=x.filter(fe=>fe._compacted&&!fe._pinned),K=[...G,...Te,T.message],X=en(g,K,j),me=wt(X);if(me+c<=l)return{messages:X,compressed:!0,compacted:!0,tokensRemoved:h-me};x=K}}catch(se){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",se.message)}let P=(f-l)/l,C=x.map(se=>is(se,"light")),Z=en(g,C,j),Y=wt(Z);if(Y+c<=l)return{messages:Z,compressed:!0,compacted:!1,tokensRemoved:h-Y};if(C=x.map(se=>is(se,"medium")),Z=en(g,C,j),Y=wt(Z),Y+c<=l)return{messages:Z,compressed:!0,compacted:!1,tokensRemoved:h-Y};if(C=x.map(se=>is(se,"aggressive")),Z=en(g,C,j),Y=wt(Z),Y+c<=l)return{messages:Z,compressed:!0,compacted:!1,tokensRemoved:h-Y};let ue=Cd([...C,...j]),ie=C.map((se,T)=>({msg:se,score:se._pinned?1/0:Rd(se,T,C.length,ue),tokens:as(se)}));for(;ie.length>0&&Y>u;){let se=-1;for(let T=0;T<ie.length;T++)ie[T].score!==1/0&&(se===-1||ie[T].score<ie[se].score)&&(se=T);if(se===-1)break;Y-=ie[se].tokens,ie.splice(se,1)}return C=ie.map(se=>se.msg),Z=en(g,C,j),Y=wt(Z),{messages:Z,compressed:!0,compacted:!1,tokensRemoved:h-Y}}function en(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function Nw(t,e){if(!t)return"";if(xn(t)<=e)return t;let n=e*4,o=t.split(`
|
|
160
191
|
`),r=Math.floor(n*.6),i=Math.floor(n*.4),a="",c=0;for(let h of o){if(a.length+h.length+1>r)break;a+=(a?`
|
|
161
|
-
`:"")+h,c++}let l="",u=0;for(let h=o.length-1;h>=c;h--){let
|
|
162
|
-
`:"")+l;if(
|
|
192
|
+
`:"")+h,c++}let l="",u=0;for(let h=o.length-1;h>=c;h--){let g=o[h]+(l?`
|
|
193
|
+
`:"")+l;if(g.length>i)break;l=g,u++}let f=`
|
|
163
194
|
|
|
164
195
|
... (${o.length-c-u} lines omitted, ${o.length} total) ...
|
|
165
196
|
|
|
166
|
-
`;return a+f+l}var
|
|
197
|
+
`;return a+f+l}var Mw=6;function Lw(t,e,s=!1){let n=_r(),o=br(e),r=Math.floor(n*(s?.35:.5))-o,i=wt(t),a=Math.floor(i*(s?.5:.8));r>a&&(r=a);let c=null,l=0;t.length>0&&t[0].role==="system"&&(c=t[0],l=1);let u=s?2:Mw,d=Math.max(l,t.length-u),f=t.slice(l,d),h=t.slice(d),g=f.map(P=>is(P,"aggressive"));s&&(h=h.map(P=>is(P,"aggressive")));let m=en(c,g,h),b=wt(m);for(;g.length>0&&b>r;){let P=g.shift();b-=as(P)}s&&b>r&&(h=h.filter(C=>C.role==="user").slice(-1),m=en(c,[],h),b=wt(m)),m=en(c,g,h);let x=t.filter(P=>P.role==="user"),j=P=>{let C=typeof P.content=="string"?P.content:"";return C.startsWith("[SYSTEM WARNING]")||C.startsWith("[SYSTEM:")||C.startsWith("BLOCKED:")},G=x.find(P=>!j(P)),L=[...x].reverse().find(P=>!j(P));if(G&&!m.find(P=>P===G)){let P=m.findIndex(Z=>Z.role==="system"),C=P>=0?P+1:0;m.splice(C,0,G)}return L&&L!==G&&!m.find(P=>P===L)&&m.push(L),{messages:m,tokensRemoved:i-wt(m)}}Ad.exports={estimateTokens:xn,estimateMessageTokens:as,estimateMessagesTokens:wt,estimateDeltaTokens:Sw,estimateToolsTokens:br,serializeMessage:vw,getContextWindow:_r,getUsage:Ew,compressMessage:is,compressToolResult:Td,scoreMessageRelevance:Rd,extractActiveFiles:Cd,buildProgressSnapshot:Cw,fitToContext:Ow,forceCompress:Lw,truncateFileContent:Nw,invalidateTokenRatioCache:kw,invalidateFitToContextCache:Aw,getEffectiveCompressionThreshold:Ed,COMPRESSION_THRESHOLD:Ys,TIER_COMPRESSION_THRESHOLDS:Sd,SAFETY_MARGIN:kd,KEEP_RECENT:vd}});var Sa=re((pv,Zd)=>{var{callStream:Pw,getActiveProviderName:kr,getActiveModelId:Od,getConfiguredProviders:Iw,getProvider:Nd,getActiveProvider:Md,parseModelSpec:Ld}=Ge(),{parseToolArgs:Pd}=Rs(),{filterToolsForModel:jw,getModelTier:xr}=qs(),{getModelBriefing:Dw}=wr(),{trackUsage:Id,estimateTokens:jd}=Jo(),{MultiProgress:qw,C:fv}=He();function Dd(t){return!t||typeof t!="string"?0:typeof jd=="function"?jd(t):Math.ceil(t.length/4)}var Bd=15,Fw=5,qd=3,Wd=8,Bw=2,vr=new Map,Ud=600*1e3;function Ww(t,e){let s=vr.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<Ud?!1:(vr.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Gs(t){vr.delete(t)}function xa(){vr.clear()}function ka(t){let e=(t.message||"").toLowerCase(),s=t.code||"";return e.includes("429")||e.includes("rate limit")?"rate_limit":e.includes("401")||e.includes("403")||e.includes("unauthorized")||e.includes("forbidden")?"auth":e.includes("context")&&(e.includes("too long")||e.includes("overflow")||e.includes("maximum"))||e.includes("400")&&(e.includes("content")||e.includes("length"))?"context_overflow":e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")?"server":e.includes("timed out")||e.includes("timeout")?"timeout":s==="ECONNRESET"||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ENOTFOUND"||e.includes("socket disconnected")||e.includes("tls")||e.includes("econnreset")||e.includes("fetch failed")||e.includes("etimedout")||e.includes("enotfound")?"network":"unknown"}function Hd(t){let e=ka(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Yd(t,e,s){let n;for(let o=0;o<=qd;o++)try{return await Pw(t,e,s)}catch(r){n=r;let i=ka(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(o<qd&&Hd(r)){let c=i==="rate_limit"?Math.min(2e3*Math.pow(2,o),15e3):Math.min(500*Math.pow(2,o),4e3);await new Promise(l=>setTimeout(l,c).unref());continue}throw r}throw n}var Fd=new Set(["ask_user","task_list"]);function Gd(t){return t>=2?new Set([...Fd,"spawn_agents"]):Fd}var Uw=new Set(["write_file","edit_file","patch_file"]),Kd={explore:{allowedTools:new Set(["bash","read_file","list_directory","glob","grep","search_files","web_fetch","web_search"]),systemSuffix:"You are an exploration agent. Read and search code only. Do NOT modify any files."},review:{allowedTools:new Set(["read_file","list_directory","glob","grep","search_files"]),systemSuffix:"You are a code review agent. Read code and report findings. Do NOT make changes."},implement:{allowedTools:null,systemSuffix:""}},Hw=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Yw=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function zd(t){return Yw.test(t)?"full":Hw.test(t)?"essential":t.length>300?"full":"standard"}function Xd(t){let e=Iw(),s=kr(),n=[...e].sort((o,r)=>(o.name===s?-1:1)-(r.name===s?-1:1));for(let o of n)for(let r of o.models)if(xr(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Gw={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function va(t){if(t.model){let{provider:o,model:r}=Ld(t.model),i=o?Nd(o):Md(),a=o||kr();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=xr(r,a);return{provider:a,model:r,tier:c}}}let e=zd(t.task),s=Gw[e];if(s){let{provider:o,model:r}=Ld(s),i=o?Nd(o):Md(),a=o||kr();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=xr(r,a);return{provider:a,model:r,tier:c}}}let n=Xd(e);if(n){let o=xr(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function Vd(t,e={},s=0){let n=s===0?Bd:Wd,o=Math.min(t.max_iterations||10,n),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],a={input:0,output:0},c=new Set,l=new Map,u=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
|
|
167
198
|
|
|
168
199
|
TASK: ${t.task}
|
|
169
200
|
${t.context?`
|
|
@@ -185,25 +216,25 @@ TOOL STRATEGY:
|
|
|
185
216
|
ERROR RECOVERY:
|
|
186
217
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
187
218
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
188
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&
|
|
219
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`,d=t.type&&Kd[t.type],f=d&&d.systemSuffix?`
|
|
189
220
|
|
|
190
|
-
${d.systemSuffix}`:"",h=
|
|
191
|
-
${
|
|
221
|
+
${d.systemSuffix}`:"",h=va(t),g=h.provider,m=h.model,b=h.tier,x=Dw(m||Od()),G=[{role:"system",content:(x?`## Model Briefing
|
|
222
|
+
${x}
|
|
192
223
|
|
|
193
224
|
---
|
|
194
225
|
|
|
195
|
-
`:"")+u+f}];
|
|
196
|
-
`)}let
|
|
197
|
-
...(truncated)`:
|
|
198
|
-
`)}catch(u){return l.stop(),
|
|
199
|
-
`);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),c=i[2].trim();c.startsWith("[")&&c.endsWith("]")?e[a]=c.slice(1,-1).split(",").map(l=>l.trim()).filter(Boolean):e[a]=c}s=n[2]}return{frontmatter:e,body:s}}function
|
|
200
|
-
`);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let c of
|
|
226
|
+
`:"")+u+f}];G.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:L,executeTool:P}=ts(),C=Gd(s),Z=jw(L.filter(ue=>!C.has(ue.function.name)),b);if(d&&d.allowedTools&&(Z=Z.filter(ue=>d.allowedTools.has(ue.function.name))),m&&!t._skipLog){let ue=b?` (${b})`:"";process.stderr.write(` [sub-agent: ${g}:${m}${ue}]
|
|
227
|
+
`)}let Y={};g&&(Y.provider=g),m&&(Y.model=m);try{for(let ie=0;ie<o;ie++){let se=await Yd(G,Z,Y);if(!se||typeof se!="object")throw new Error("Empty or invalid response from provider");{let fe=g||kr(),$e=m||Od();if(se.usage){let pe=se.usage.prompt_tokens||0,Re=se.usage.completion_tokens||0;a.input+=pe,a.output+=Re,Id(fe,$e,pe,Re)}else{let pe=se.content||"",Re=G.map(v=>typeof v.content=="string"?v.content:Array.isArray(v.content)?v.content.map(O=>typeof O=="string"?O:O.text||"").join(""):"").join(" "),w=Dd(Re),I=Dd(pe);a.input+=w,a.output+=I,a._estimated=!0,Id(fe,$e,w,I)}}let T=se.content||"",Te=se.tool_calls,K={role:"assistant",content:T||""};if(Te&&Te.length>0&&(K.tool_calls=Te),G.push(K),!Te||Te.length===0){for(let fe of c)Gs(fe);return{task:t.task,status:"done",result:T||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:g&&m?`${g}:${m}`:null}}let X=Te.map(fe=>{let $e=fe.function.name,pe=Pd(fe.function.arguments),Re=fe.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!pe)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${$e}`,tool_call_id:Re});let w=null;if(Uw.has($e)&&pe.path){let v=require("path"),O=v.isAbsolute(pe.path)?pe.path:v.resolve(process.cwd(),pe.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let R=v.relative(process.cwd(),O);if(t._readOnlyFiles.some(H=>R===H||R.startsWith(H+"/")||O===H||O.startsWith(H+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${pe.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:Re})}if(c.has(O)||!Ww(O,r))return Promise.resolve({role:"tool",content:`ERROR: File '${pe.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:Re});c.add(O),w=O}return i.push($e),e.onUpdate&&e.onUpdate({type:"tool_call",tool:$e,agentId:r}),($e==="spawn_agents"?Jd(pe,s+1):P($e,pe,{autoConfirm:!0,silent:!0})).then(v=>{w&&(Gs(w),c.delete(w));let O=String(v??"");return{role:"tool",content:O.length>2e4?O.substring(0,2e4)+`
|
|
228
|
+
...(truncated)`:O,tool_call_id:Re}}).catch(v=>(w&&(Gs(w),c.delete(w)),{role:"tool",content:`ERROR: ${v.message}`,tool_call_id:Re}))}),me=await Promise.all(X);if(G.push(...me),ie>=7&&G.length>12)try{let{compressMessage:fe}=It(),$e=G.length-6;for(let pe=1;pe<$e;pe++)G[pe]._subAgentCompressed||(G[pe]={...fe(G[pe],"light"),_subAgentCompressed:!0})}catch{}for(let fe=0;fe<Te.length;fe++){let $e=Te[fe];if($e.function.name==="bash_exec"){let pe=Pd($e.function.arguments);if((me[fe]?.content||"").startsWith("ERROR")&&pe&&pe.command){let w=pe.command.replace(/\s+/g," ").trim().slice(0,100);l.set(w,(l.get(w)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${ie+1}/${o}`)}for(let ie of c)Gs(ie);let ue=[...l.entries()].filter(([,ie])=>ie>=3).sort((ie,se)=>se[1]-ie[1]).slice(0,3).map(([ie,se])=>`"${ie}" (failed ${se}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:ue,result:G[G.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:g&&m?`${g}:${m}`:null}}catch(ue){for(let ie of c)Gs(ie);return{task:t.task,status:"failed",result:`Error: ${ue.message}`,toolsUsed:i,tokensUsed:a,modelSpec:g&&m?`${g}:${m}`:null}}}async function Jd(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let s=e===0?Fw:Bw,n=e===0?Bd:Wd,o=(t.agents||[]).slice(0,s);if(o.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,a=o.map(u=>va(u)),c=o.map((u,d)=>{let f=a[d],h=f.model?` [${f.model}]`:"",g=u.task.substring(0,i-h.length);return`${r}Agent ${d+1}${h}: ${g}${u.task.length>g.length?"...":""}`}),l=new qw(c);l.start();try{let u=o.map((m,b)=>{let x=a[b],j=Math.min(m.max_iterations||n,n),G=x.model?{...m,model:`${x.provider}:${x.model}`,_skipLog:!0,max_iterations:j}:{...m,_skipLog:!0,max_iterations:j};return Vd(G,{onUpdate:()=>{}},e).then(L=>(l.update(b,L.status==="failed"?"error":"done"),L)).catch(L=>(l.update(b,"error"),{task:m.task,status:"failed",result:`Error: ${L.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);l.stop(),xa();let f=["Sub-agent results:",""],h=0,g=0;for(let m=0;m<d.length;m++){let b=d[m],x=b.status==="done"?"\u2713":b.status==="truncated"?"\u26A0":"\u2717",j=b.modelSpec?` [${b.modelSpec}]`:"";f.push(`${x} Agent ${m+1}${j}: ${b.task}`),f.push(` Status: ${b.status}`),f.push(` Tools used: ${b.toolsUsed.length>0?b.toolsUsed.join(", "):"none"}`),f.push(` Result: ${b.result}`),b.repeatedFailures&&b.repeatedFailures.length>0&&f.push(` Repeated failures: ${b.repeatedFailures.join("; ")}`),f.push(""),h+=b.tokensUsed.input,g+=b.tokensUsed.output}return f.push(`Total sub-agent tokens: ${h} input + ${g} output`),f.join(`
|
|
229
|
+
`)}catch(u){return l.stop(),xa(),`ERROR: Sub-agent execution failed: ${u.message}`}}Zd.exports={runSubAgent:Vd,executeSpawnAgents:Jd,clearAllLocks:xa,classifyTask:zd,pickModelForTier:Xd,resolveSubAgentModel:va,classifyError:ka,isRetryableError:Hd,callWithRetry:Yd,getExcludedTools:Gd,LOCK_TIMEOUT_MS:Ud,SUB_AGENT_TYPES:Kd}});var Ma=re((hv,pf)=>{var je=require("fs"),Gt=require("path"),{atomicWrite:Qd,withFileLockSync:ef}=mn(),Kw=new Set(["the","a","an","is","are","and","or","but","in","on","at","to","for","of","with","this","that","it","as","be","by","from","was","were","has","have","had","not","do","does","did","so","if","its","my","me","we","you","he","she","they","our","your","their","can","will","would","could","should","may","might","then","than","also","which","when","where","how","what","who","all","any","each","more","most","use","used","using","get","set","new","add","make","der","die","das","den","dem","des","ein","eine","einen","einem","eines","und","oder","aber","von","zu","mit","auf","bei","nach","aus","vor","ist","sind","war","hat","haben","wird","kann","soll","muss","nicht","auch","als","durch"]);function ls(){let t=Gt.join(process.cwd(),".nex","brain");return je.existsSync(t)||je.mkdirSync(t,{recursive:!0}),t}function Er(){return Gt.join(ls(),".brain-index.json")}function Ra(){return Gt.join(ls(),".embeddings.json")}function Ks(){let t=Gt.join(process.cwd(),".nex","brain");if(!je.existsSync(t))return[];try{return je.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=Gt.join(t,e),n=je.statSync(s);return{name:e.replace(/\.md$/,""),path:s,size:n.size,modified:new Date(n.mtimeMs)}}).sort((e,s)=>s.modified-e.modified)}catch{return[]}}function zs(t){let e={},s=t,n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(n){let o=n[1].split(`
|
|
230
|
+
`);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),c=i[2].trim();c.startsWith("[")&&c.endsWith("]")?e[a]=c.slice(1,-1).split(",").map(l=>l.trim()).filter(Boolean):e[a]=c}s=n[2]}return{frontmatter:e,body:s}}function tf(t){let e=Gt.join(ls(),`${t}.md`);if(!je.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=je.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=zs(s);return{name:t,content:s,body:o,frontmatter:n}}function zw(t,e){let s=Gt.join(ls(),`${t}.md`);Qd(s,e),Jw(t,e),Xw()}function Xw(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Ra();je.existsSync(t)&&setImmediate(async()=>{try{await lf()}catch{}})}function Vw(t){let e=Gt.join(ls(),`${t}.md`);return je.existsSync(e)?(je.unlinkSync(e),Zw(t),!0):!1}function Sr(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Kw.has(e))}function Ca(t){let e={},{frontmatter:s,body:n}=zs(t),o=Array.isArray(s.tags)?s.tags:[];for(let i of o){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(n||t).split(`
|
|
231
|
+
`);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let c of Sr(a))e[c]=(e[c]||0)+3}for(let i of Sr(n||t))e[i]=(e[i]||0)+1;return e}function Aa(){let t=Er();if(!je.existsSync(t))return{documents:{}};try{return JSON.parse(je.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Oa(t){Qd(Er(),JSON.stringify(t,null,2))}function Jw(t,e){ef(Er(),()=>{let s=Aa(),{frontmatter:n}=zs(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:Ca(e),tags:o,modified:new Date().toISOString()},Oa(s)})}function Zw(t){ef(Er(),()=>{let e=Aa();delete e.documents[t],Oa(e)})}function Ta(){let t=Ks(),e={documents:{}};for(let s of t){let n=je.readFileSync(s.path,"utf-8"),{frontmatter:o}=zs(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:Ca(n),tags:r,modified:s.modified.toISOString()}}return Oa(e),e}function nf(){let t=Aa(),e=Ks();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return Ta()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return Ta();return t}function sf(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=Sr(t);if(o.length===0)return[];let r=nf(),i=[];for(let[a,c]of Object.entries(r.documents)){let l=0;for(let u of o){c.keywords[u]&&(l+=c.keywords[u]);for(let[d,f]of Object.entries(c.keywords))d!==u&&d.length>3&&u.length>3&&(d.includes(u)||u.includes(d))&&(l+=f*.3)}l>=n&&i.push({name:a,score:l})}return i.sort((a,c)=>c.score-a.score),i.slice(0,s)}var of=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Ea=400,Qw=50;async function rf(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),s=require("https"),n=new URL(`${t}/api/tags`),o=n.protocol==="https:"?s:e;return((await new Promise((a,c)=>{let l=o.get(n.toString(),{timeout:2e3},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d))}catch{c(new Error("bad json"))}})});l.on("error",c),l.on("timeout",()=>{l.destroy(),c(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(of.split(":")[0]))}catch{return!1}}async function Na(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),n=require("https"),o=new URL(`${e}/api/embeddings`),r=o.protocol==="https:"?n:s,i=JSON.stringify({model:of,prompt:t});return new Promise((a,c)=>{let l=r.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},u=>{let d="";u.on("data",f=>d+=f),u.on("end",()=>{try{a(JSON.parse(d).embedding||[])}catch(f){c(f)}})});l.on("error",c),l.on("timeout",()=>{l.destroy(),c(new Error("embedding timeout"))}),l.write(i),l.end()})}function af(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,n=0,o=0;for(let i=0;i<t.length;i++)s+=t[i]*e[i],n+=t[i]*t[i],o+=e[i]*e[i];let r=Math.sqrt(n)*Math.sqrt(o);return r===0?0:s/r}function cf(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+Ea).join(" ");if(s.push({text:o,offset:n}),n+Ea>=e.length)break;n+=Ea-Qw}return s}async function lf(){let t=Ks(),e={documents:{}},s=Ra();if(je.existsSync(s))try{e=JSON.parse(je.readFileSync(s,"utf-8"))}catch{}for(let n of t){let o=e.documents[n.name];if(o&&new Date(o.modified)>=n.modified)continue;let r=je.readFileSync(n.path,"utf-8"),i=cf(r),a=[];for(let c of i){let l=await Na(c.text);a.push({text:c.text,embedding:l,offset:c.offset})}e.documents[n.name]={chunks:a,modified:n.modified.toISOString()}}for(let n of Object.keys(e.documents))t.some(o=>o.name===n)||delete e.documents[n];return je.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function uf(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=Ra();if(!je.existsSync(o))return[];let r;try{r=JSON.parse(je.readFileSync(o,"utf-8"))}catch{return[]}let i=await Na(t),a=[];for(let[c,l]of Object.entries(r.documents||{})){let u=0,d="";for(let f of l.chunks||[]){let h=af(i,f.embedding);h>u&&(u=h,d=f.text)}u>=n&&a.push({name:c,score:u,bestChunk:d})}return a.sort((c,l)=>l.score-c.score),a.slice(0,s)}function df(t,e,s={}){let{k:n=60,topK:o=3}=s,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(n+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(n+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,o)}async function ff(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=sf(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await rf()){let a=await uf(t,{topK:s});r=df(o,a,{topK:s})}}catch{}return r.map(i=>{let a=tf(i.name),c=(a.body||a.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:a.content,excerpt:c}})}var cs={queryKey:null,result:null,ts:0},e0=3e5;async function t0(t){if(!t||!t.trim())return"";let e=Gt.join(process.cwd(),".nex","brain");if(!je.existsSync(e)||Ks().length===0)return"";let n=t.trim().toLowerCase().slice(0,200);if(cs.result!==null&&cs.queryKey===n&&Date.now()-cs.ts<e0)return cs.result;let o;try{o=await ff(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let r;try{r=It().estimateTokens}catch{r=u=>Math.ceil(u.length/4)}let i=25e3,a=[],c=0;for(let u of o){let d=u.content||"",f=r(d);if(c+f>i){let g=i-c;if(g<100)break;let m=g/f;d=d.slice(0,Math.floor(d.length*m))+`
|
|
201
232
|
...(truncated)`}let h=typeof u.score=="number"?u.score.toFixed(2):String(u.score);if(a.push(`--- ${u.name} (relevance: ${h}) ---
|
|
202
|
-
${d}`),c+=r(d),c>=i)break}if(a.length===0)return
|
|
233
|
+
${d}`),c+=r(d),c>=i)break}if(a.length===0)return cs={queryKey:n,result:"",ts:Date.now()},"";let l=`KNOWLEDGE BASE (auto-selected):
|
|
203
234
|
|
|
204
235
|
${a.join(`
|
|
205
236
|
|
|
206
|
-
`)}`;return
|
|
237
|
+
`)}`;return cs={queryKey:n,result:l,ts:Date.now()},l}pf.exports={getBrainDir:ls,listDocuments:Ks,readDocument:tf,writeDocument:zw,removeDocument:Vw,buildIndex:Ta,getIndex:nf,query:ff,getBrainContext:t0,isEmbeddingAvailable:rf,generateEmbedding:Na,buildEmbeddingIndex:lf,semanticQuery:uf,cosineSimilarity:af,_keywordQuery:sf,_extractKeywords:Ca,_chunkText:cf,parseFrontmatter:zs,tokenize:Sr,_fuseResults:df}});var Js=re((mv,Sf)=>{var Le=require("fs"),ft=require("path"),n0=require("os"),{atomicWrite:Tr,withFileLockSync:hf}=mn(),Xs=["user","feedback","project","reference"],s0=50;function kn(){return ft.join(process.cwd(),".nex","memory")}function us(){return ft.join(kn(),"memory.json")}function mf(){return ft.join(kn(),"MEMORY.md")}function o0(){return ft.join(process.cwd(),"NEX.md")}function gf(){return ft.join(n0.homedir(),".nex","NEX.md")}function Rr(){let t=kn();Le.existsSync(t)||Le.mkdirSync(t,{recursive:!0})}function yf(t){let e=ft.join(kn(),t);return Le.existsSync(e)||Le.mkdirSync(e,{recursive:!0}),e}function Vs(){let t=us();if(!Le.existsSync(t))return{};try{return JSON.parse(Le.readFileSync(t,"utf-8"))}catch{return{}}}function $f(t){Rr(),Tr(us(),JSON.stringify(t,null,2))}function wf(){let t=us();if(!Le.existsSync(t))return;let e=Vs(),s=Object.keys(e);if(s.length===0){try{Le.renameSync(t,t+".bak")}catch{}return}for(let n of s){let o=e[n],r=o.value||String(o),i=n.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let a=yf("project"),c=ft.join(a,`${i}.md`),l=r.split(`
|
|
207
238
|
`)[0].slice(0,100),u=`---
|
|
208
239
|
name: ${n}
|
|
209
240
|
description: ${l}
|
|
@@ -211,7 +242,7 @@ type: project
|
|
|
211
242
|
---
|
|
212
243
|
|
|
213
244
|
${r}
|
|
214
|
-
`;
|
|
245
|
+
`;Tr(c,u)}Cr();try{Le.renameSync(t,t+".bak")}catch{}}function r0(t,e,s,n){if(!Xs.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Xs.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!s||typeof s!="string"||s.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let o=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!o)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=yf(t),i=ft.join(r,`${o}.md`);if(Le.existsSync(i))try{if(La(Le.readFileSync(i,"utf-8")).body.slice(0,200)===s.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let a=n||s.split(`
|
|
215
246
|
`)[0].slice(0,100),c=`---
|
|
216
247
|
name: ${e}
|
|
217
248
|
description: ${a}
|
|
@@ -219,11 +250,11 @@ type: ${t}
|
|
|
219
250
|
---
|
|
220
251
|
|
|
221
252
|
${s}
|
|
222
|
-
`;return
|
|
253
|
+
`;return Tr(i,c),Cr(),{ok:!0,path:i,updated:!0}}function i0(t,e){if(!Xs.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),n=ft.join(kn(),t,`${s}.md`);if(!Le.existsSync(n))return!1;try{return Le.unlinkSync(n),Cr(),!0}catch{return!1}}function La(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let s=e[1],n=(e[2]||"").trim(),o=r=>{let i=s.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:o("name"),description:o("description"),type:o("type"),body:n}}function bf(){let t=[],e=kn();for(let s of Xs){let n=ft.join(e,s);if(!Le.existsSync(n))continue;let o;try{o=Le.readdirSync(n).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of o){let i=ft.join(n,r);try{let a=Le.readFileSync(i,"utf-8"),c=La(a);t.push({type:s,name:c.name||ft.basename(r,".md"),description:c.description,filePath:i})}catch{}}}return t}function Cr(){let t=bf(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=s0+2)break;let n=`${s.type}/${ft.basename(s.filePath)}`;e.push(`- [${s.name}](${n}) \u2014 ${s.description||"(no description)"}`)}Rr(),Tr(mf(),e.join(`
|
|
223
254
|
`)+`
|
|
224
|
-
`)}function
|
|
225
|
-
${e}`);let s=
|
|
226
|
-
${s}`);let n="",o=
|
|
255
|
+
`)}function _f(){let t=mf();if(!Le.existsSync(t))return"";try{return Le.readFileSync(t,"utf-8").trim()}catch{return""}}function a0(t,e){Rr(),hf(us(),()=>{let s=Vs();s[t]={value:e,updatedAt:new Date().toISOString()},$f(s)})}function c0(t){let e=Vs();return e[t]?e[t].value:null}function l0(t){return Rr(),hf(us(),()=>{let e=Vs();return t in e?(delete e[t],$f(e),!0):!1})}function xf(){let t=Vs();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function kf(){let t=gf();if(!Le.existsSync(t))return"";try{return Le.readFileSync(t,"utf-8").trim()}catch{return""}}function vf(){let t=o0();if(!Le.existsSync(t))return"";try{return Le.readFileSync(t,"utf-8").trim()}catch{return""}}function u0(){wf();let t=[],e=kf();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
256
|
+
${e}`);let s=vf();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
257
|
+
${s}`);let n="",o=_f();if(o)n=o;else{let d=xf();d.length>0&&(n=`PROJECT MEMORY:
|
|
227
258
|
${d.map(h=>` ${h.key}: ${h.value}`).join(`
|
|
228
259
|
`)}`)}let r=t.join(`
|
|
229
260
|
|
|
@@ -232,209 +263,209 @@ ${d.map(h=>` ${h.key}: ${h.value}`).join(`
|
|
|
232
263
|
`}n=f.trimEnd()+`
|
|
233
264
|
[Memory index truncated \u2014 use delete_memory to prune old entries]`}else n.length>l&&(n="");let u=[...t];return n&&u.push(n),u.length>0&&u.push(i),u.join(`
|
|
234
265
|
|
|
235
|
-
`)}
|
|
236
|
-
`;
|
|
237
|
-
`).filter(c=>c.trim());for(let c of a)try{let l=JSON.parse(c);if(t.tool&&l.tool!==t.tool)continue;n.push(l)}catch{}if(t.date)break}return n}function
|
|
238
|
-
${i.map(c=>
|
|
239
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
266
|
+
`)}Sf.exports={saveMemory:r0,deleteMemory:i0,scanMemories:bf,rebuildIndex:Cr,loadMemoryIndex:_f,remember:a0,recall:c0,forget:l0,listMemories:xf,loadGlobalInstructions:kf,loadProjectInstructions:vf,getMemoryContext:u0,_getMemoryDir:kn,_getMemoryFile:us,_getGlobalNexMdPath:gf,_parseMemoryFile:La,_migrateIfNeeded:wf,VALID_TYPES:Xs}});var Of=re((gv,Af)=>{var Zs=require("fs"),Pa=require("path"),Ia=process.env.NEX_AUDIT!=="false",vn=null;function Ef(){return vn||(vn=Pa.join(process.cwd(),".nex","audit"),Zs.existsSync(vn)||Zs.mkdirSync(vn,{recursive:!0}),vn)}function Tf(){let t=new Date().toISOString().split("T")[0];return Pa.join(Ef(),`${t}.jsonl`)}function d0(t){if(Ia)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Rf(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},s=JSON.stringify(e)+`
|
|
267
|
+
`;Zs.appendFileSync(Tf(),s,"utf-8")}catch{}}function Rf(t){if(!t||typeof t!="object")return{};let e={};for(let[s,n]of Object.entries(t))/key|token|password|secret|credential/i.test(s)?e[s]="***":typeof n=="string"&&n.length>500?e[s]=n.substring(0,500)+`... (${n.length} chars)`:e[s]=n;return e}function Cf(t={}){let e=Ef(),s=t.days||1,n=[];for(let o=0;o<s;o++){let r=t.date||new Date(Date.now()-o*864e5).toISOString().split("T")[0],i=Pa.join(e,`${r}.jsonl`);if(!Zs.existsSync(i))continue;let a=Zs.readFileSync(i,"utf-8").split(`
|
|
268
|
+
`).filter(c=>c.trim());for(let c of a)try{let l=JSON.parse(c);if(t.tool&&l.tool!==t.tool)continue;n.push(l)}catch{}if(t.date)break}return n}function f0(t=1){let e=Cf({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let s={},n=0,o=0;for(let r of e)s[r.tool]=(s[r.tool]||0)+1,n+=r.duration||0,r.success&&o++;return{totalCalls:e.length,byTool:s,avgDuration:Math.round(n/e.length),successRate:o/e.length}}function p0(t){Ia=t}function h0(){return Ia}function m0(){vn=null}Af.exports={logToolExecution:d0,sanitizeArgs:Rf,readAuditLog:Cf,getAuditSummary:f0,setAuditEnabled:p0,isAuditEnabled:h0,getAuditLogPath:Tf,_reset:m0}});var Wf=re((wv,Bf)=>{var De=require("fs").promises,Nf=require("fs"),Ee=require("path"),Ce=require("util").promisify(require("child_process").exec),ja=require("util").promisify(require("child_process").execFile),{spawnSync:g0}=require("child_process"),Da=require("axios"),{isForbidden:y0,isSSHForbidden:$0,isDangerous:w0,isCritical:Mf,isBashPathForbidden:b0,confirm:vt}=Cs(),{showDiff:Ar,showNewFile:_0,showEditDiff:yv,confirmFileChange:Qs}=uu(),{C:ce,Spinner:x0,getToolSpinnerText:k0}=He(),{isGitRepo:qa,getCurrentBranch:Lf,getStatus:v0,getDiff:S0}=sr(),{recordChange:Or}=bu(),{fuzzyFindText:Pf,findMostSimilar:no}=Hu(),{runDiagnostics:eo}=Gu(),{findFileInIndex:E0,getFileIndex:$v}=da(),{resolveProfile:bt,sshExec:rt,scpUpload:T0,scpDownload:R0}=pa(),{resolveDeployConfig:C0,loadDeployConfigs:A0}=rd(),{getEditMode:If}=qs(),O0=/^(vim?|nano|emacs|pico|less|more|top|htop|iftop|iotop|glances|telnet\s|screen|tmux|fzf|gum|dialog|whiptail|man\s|node\s*$|python3?\s*$|irb\s*$|rails\s*c|psql\s|mysql\s|redis-cli|mongosh?|sqlite3)\b/,N0=/^ssh\s/,M0=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function pt(t){return De.access(t).then(()=>!0).catch(()=>!1)}async function Nr(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=it(e);if(s&&await pt(s))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=Ee.extname(t);if(!o)for(let i of n){let a=it(t+i);if(a&&await pt(a))return{fixedPath:a,message:`(auto-fixed: added ${i} extension)`}}if(o){let i=t.replace(/\.[^.]+$/,"");for(let a of n){if(a===o)continue;let c=it(i+a);if(c&&await pt(c))return{fixedPath:c,message:`(auto-fixed: ${o} \u2192 ${a})`}}}let r=Ee.basename(t);if(r&&r.length>2)try{let i=E0(r).map(a=>it(a));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${Ee.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
269
|
+
${i.map(c=>Ee.relative(process.cwd(),c)).map(c=>` - ${c}`).join(`
|
|
270
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function L0(t){return/\bprintenv\b/.test(t)?"printenv exposes all secrets. Use `echo $VAR_NAME` for a single variable, or `env | grep PATTERN` for filtered output.":/cat\s+.*\.env\b/.test(t)?'Reading .env directly is blocked. Use `grep -v "KEY=" .env` to inspect non-secret entries, or ask the user to share specific values.':/cat\s+.*credentials/i.test(t)?"Credentials files are blocked. Reference the variable name from the application config instead.":/python3?\s+-c\s/.test(t)?"Inline python -c is blocked. Write a temporary script file and run it with `python3 script.py` instead.":/node\s+-e\s/.test(t)?"Inline node -e is blocked. Write a temporary script file and run it with `node script.js` instead.":/curl.*-X\s*POST|curl.*--data/.test(t)?"curl POST is blocked to prevent data exfiltration. Use the application's own API client or ask the user to run the request.":/base64.*\|.*bash/.test(t)?"Piping base64-decoded content to bash is blocked. Decode the content first, inspect it, then run explicitly.":/\beval\s*\(/.test(t)?"eval is blocked. Execute the command directly without eval.":/(?:^|[;&|]\s*)history(?:\s|$)/.test(t)?"Shell history is blocked. Look at git log or project files for context instead.":/\bsed\s+-n\s+['"]?\d+,\d+p/.test(t)?'sed -n line-range scrolling floods context with irrelevant lines. Use targeted grep instead: grep -n "ERROR\\|pattern" <logfile> | tail -20':""}function qf(t,e){let s=[];if(/command not found|: not found|not recognized/i.test(t)){let n=e.match(/^(\S+)/),o=n?n[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?s.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?s.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):s.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let n=t.match(/Cannot find module '([^']+)'/),o=n?n[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?s.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):s.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&s.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let n=t.match(/port (\d+)|:(\d+)/),o=n?n[1]||n[2]:"";s.push(`HINT: Port ${o||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&s.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&s.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&s.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&s.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let n=t.match(/curl:\s*\((\d+)\)/),o=n?parseInt(n[1],10):null;o===6||/Could not resolve host/i.test(t)?s.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?s.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?s.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?s.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===35||/SSL.*error/i.test(t))&&s.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let n=t.match(/port (\d+)/),o=n?n[1]:"";s.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&s.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&s.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&s.push("HINT: The working directory was deleted during this session \u2014 bash cannot execute commands in a non-existent cwd. Previous rm/delete commands succeeded. Use list_directory or glob to verify the state instead of retrying bash."),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&s.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),s.length===0?t:t+`
|
|
240
271
|
|
|
241
272
|
`+s.join(`
|
|
242
|
-
`)}function Ef(t,e,s){let n=Qs(t,e);if(!n)return null;let o=Math.max(2,Math.ceil(e.length*.03));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var kf=!1,_n=null;function w0(){_n&&(_n(),_n=null)}var Na=null;function b0(t){Na=t}async function Oa(){if(!kf){kf=!0;try{let{stdout:t}=await Ee("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Ee('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Ee("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Ee("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var _0=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function rt(t){let e=ve.isAbsolute(t)?ve.resolve(t):ve.resolve(process.cwd(),t);for(let s of _0)if(s.test(e))return null;return e}var x0=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. You MUST use this tool at least once on a file BEFORE calling edit_file or patch_file on it \u2014 this ensures you have the exact current content and edits will match. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. You MUST call read_file on the target file first to see the exact content \u2014 never guess or recall from memory. COMMON FAILURE: old_text doesn't match because you guessed the content instead of reading the file first. If the edit fails with 'old_text not found', use the line number from the error message to re-read that specific region with line_start/line_end, then retry with the exact text. For multiple changes to the same file, prefer patch_file (single atomic operation).",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Returns paths sorted by modification time. Use this to FIND files before reading them \u2014 never guess file paths, always glob first. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to find the path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Prefer this over bash grep/rg \u2014 this tool returns structured, formatted output. Use output_mode='files_with_matches' when you only need file paths (faster, less output). Use output_mode='content' (default) for matching lines with context. Use head_limit to cap results and avoid overwhelming output on broad searches. Use include to filter by file type (e.g. '*.js'). Supports context lines (context, before_context, after_context), offset for pagination, type filter, and multiline for cross-line patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl, jarvis) that live on almalinux9/jarvis. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/jarvis/jarvis-agent). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt (package_action: check|list|install|remove|update|upgrade); user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "jarvis-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "jarvis-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function Zs(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function vf(t,e,s={}){switch(t){case"bash":{let n=e.command,o=t0(n);if(o){let d=$0(n);return`BLOCKED: Command matches forbidden pattern: ${o}${d?`
|
|
243
|
-
HINT: ${d}`:""}`}let r=
|
|
244
|
-
HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(s.autoConfirm?
|
|
245
|
-
${h}`}}case"read_file":{let n=
|
|
246
|
-
`+C.message:""}`}let r=Buffer.alloc(8192),i=await
|
|
247
|
-
`),u=await
|
|
248
|
-
`),
|
|
273
|
+
`)}function Ff(t,e,s){let n=no(t,e);if(!n)return null;let o=Math.max(2,Math.ceil(e.length*.03));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var jf=!1,Sn=null;function P0(){Sn&&(Sn(),Sn=null)}var Ba=null;function I0(t){Ba=t}async function Fa(){if(!jf){jf=!0;try{let{stdout:t}=await Ce("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Ce('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Ce("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Ce("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var j0=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function it(t){let e=Ee.isAbsolute(t)?Ee.resolve(t):Ee.resolve(process.cwd(),t);for(let s of j0)if(s.test(e))return null;return e}var D0=[{type:"function",function:{name:"bash",description:`Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. Example: use bash for "npm install" or "git status", but NOT for "cat config.json" (use read_file instead) or "grep -r 'error' src/" (use grep tool instead). AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.`,parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. ALWAYS read a file before editing it to ensure exact content matching \u2014 edit_file requires the EXACT text including whitespace and newlines. Example: read_file path=src/app.js line_start=10 line_end=20. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Concrete example: read_file(path='src/app.js', line_start=10, line_end=20) reads lines 10-20 of src/app.js. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding. IMPORTANT: If you need more than 350 lines, specify line_start and line_end explicitly \u2014 omitting them will truncate the output.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. Example: use write_file for creating a new config file like .env.example, but NOT for changing one line in an existing file (use edit_file instead). For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. ALWAYS call read_file first to get the exact content \u2014 edit_file requires the EXACT text including whitespace, indentation, and newlines. Example: edit_file(path='src/config.js', old_text='debug: false', new_text='debug: true'). IMPORTANT: old_text must match byte-for-byte \u2014 even a single space or newline difference will cause failure. If the edit fails with 'old_text not found', re-read that region with line_start/line_end then retry. For multiple replacements in one file, prefer patch_file (atomic). For new files, use write_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. Example: use list_directory to see the overall layout of the src/ directory, but NOT for finding all .js files (use glob instead). For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. Example: use search_files for finding all occurrences of 'error' in .js files, but NOT for finding all .js files (use glob instead). For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern by name or extension. Returns paths sorted by modification time. ALWAYS use this to locate files BEFORE reading them \u2014 never guess file paths. Example: glob(pattern='src/**/*.test.js') finds all test files in src directory. DO NOT use for content search (e.g. finding 'error' in files) \u2014 use grep tool instead. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to get the exact path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file CONTENTS with regex \u2014 use this when you need to find text inside files. Example: grep(pattern='callStream') finds files containing the text 'callStream'. Do NOT use glob for this \u2014 glob finds files by NAME pattern, grep searches file CONTENTS. Use output_mode='files_with_matches' for just file paths, output_mode='content' (default) for matching lines. Use include to filter by file type (e.g. '*.js'). Supports context lines, offset pagination, and multiline patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Example: when changing 3 different variables in the same function, use patch_file with an array of 3 { old_text, new_text } objects instead of 3 separate edit_file calls. This ensures either all changes are applied or none are, preventing partial edits. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl) that live on almalinux9. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/deploy/app). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt (package_action: check|list|install|remove|update|upgrade); user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "my-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "my-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function to(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function Df(t,e,s={}){switch(t){case"bash":{let n=e.command,o=y0(n);if(o){let d=L0(n);return`BLOCKED: Command matches forbidden pattern: ${o}${d?`
|
|
274
|
+
HINT: ${d}`:""}`}let r=b0(n);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
|
|
275
|
+
HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(s.autoConfirm?Mf(n):w0(n)){let d=Mf(n)?"\u26D4":"\u26A0";if(!await vt(` ${d} bash: \`${n}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Nf.accessSync(a)}catch{a=require("os").homedir(),s.silent||console.log(`${ce.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${ce.reset}`)}let c=N0.test(n.trim())&&!M0.test(n.trim());if(O0.test(n.trim())||c){s.silent||console.log(`${ce.dim} \u25B6 interactive: ${n}${ce.reset}`);let d=g0("sh",["-c",n],{stdio:"inherit",cwd:a});return d.error?`ERROR: ${d.error.message}`:d.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${d.status})`}let{ToolProgress:l}=zn(),u=s.silent?null:new l("bash",n.substring(0,40));u&&u.start();try{let{stdout:d,stderr:f}=await Ce(n,{cwd:a,timeout:9e4,maxBuffer:5242880});return u&&u.stop(),d||f||"(no output)"}catch(d){u&&u.stop();let f=(d.stderr||d.stdout||d.message||"").toString().substring(0,5e3),h=qf(f,n);return`EXIT ${d.code||1}
|
|
276
|
+
${h}`}}case"read_file":{let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await pt(n)){let C=await Nr(e.path);if(C.fixedPath)n=C.fixedPath,console.log(`${ce.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ee.relative(process.cwd(),n)}${ce.reset}`);else return`ERROR: File not found: ${e.path}${C.message?`
|
|
277
|
+
`+C.message:""}`}let r=Buffer.alloc(8192),i=await Nf.promises.open(n,"r"),{bytesRead:a}=await i.read(r,0,8192,0);await i.close();for(let C=0;C<a;C++)if(r[C]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let c=await De.readFile(n,"utf-8");if(!c&&(await De.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let l=c.split(`
|
|
278
|
+
`),u=await De.stat(n),d=l.length,f=350,h=!e.line_start&&!e.line_end,g=h&&d>f,m=(e.line_start||1)-1,b=g?f:e.line_end||l.length,x=Ee.relative(process.cwd(),n),j=g?`showing lines 1-${f} of ${d}`:e.line_start||e.line_end?`lines ${m+1}-${b} of ${d}`:`${d} lines`,G=`File: ${x} (${j}, ${u.size} bytes)`,L=l.slice(m,b).map((C,Z)=>`${m+Z+1}: ${C}`).join(`
|
|
279
|
+
`),P=g?`
|
|
249
280
|
|
|
250
281
|
[File truncated: showing lines 1-${f} of ${d} total. Use line_start/line_end to read other sections, e.g. line_start=${f+1} line_end=${Math.min(f*2,d)}]`:!h&&d>f?`
|
|
251
|
-
[Large file (${d} lines total) \u2014 use line_start/line_end for other sections]`:"";return`${
|
|
252
|
-
${L}${
|
|
253
|
-
`+u.message:""}`}let r=await
|
|
254
|
-
Most similar text (line ${
|
|
255
|
-
${
|
|
256
|
-
`),
|
|
257
|
-
`),C=`line_start=${Math.max(1,
|
|
282
|
+
[Large file (${d} lines total) \u2014 use line_start/line_end for other sections]`:"";return`${G}
|
|
283
|
+
${L}${P}`}case"write_file":{await Fa();let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await pt(n),r=null;if(s.autoConfirm)o&&(r=await De.readFile(n,"utf-8"));else if(o){r=await De.readFile(n,"utf-8");let u=await eo(n,e.content);if(Ar(n,r,e.content,{annotations:u}),!await Qs("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let u=await eo(n,e.content);if(_0(n,e.content,{annotations:u}),!await Qs("Create"))return"CANCELLED: User declined to create file."}let i=Ee.dirname(n);await pt(i)||await De.mkdir(i,{recursive:!0}),await De.writeFile(n,e.content,"utf-8");let c=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||e.content.startsWith("#!");c&&await De.chmod(n,493),Or("write_file",n,r,e.content);let l=c?" [chmod +x applied]":"";return`Written: ${n} (${e.content.length} chars)${l}`}case"edit_file":{await Fa();let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await pt(n)){let u=await Nr(e.path);if(u.fixedPath)n=u.fixedPath,console.log(`${ce.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ee.relative(process.cwd(),n)}${ce.reset}`);else return`ERROR: File not found: ${e.path}${u.message?`
|
|
284
|
+
`+u.message:""}`}let r=await De.readFile(n,"utf-8"),i=e.old_text,a=!1,c=!1;if(!r.includes(e.old_text)){let{getActiveModelId:u,getActiveProviderName:d}=Ge();if(If(u(),d())==="strict"){let g=no(r,e.old_text);return g?`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)
|
|
285
|
+
Most similar text (line ${g.line}, distance ${g.distance}):
|
|
286
|
+
${g.text}`:`ERROR: old_text not found in ${n} (strict mode \u2014 exact match required)`}let h=Pf(r,e.old_text);if(h)i=h,a=!0,console.log(`${ce.dim} \u2713 fuzzy whitespace match applied${ce.reset}`);else{let g=Ff(r,e.old_text,e.new_text);if(g){if(!s.autoConfirm){let G=await eo(n,g.content);if(Ar(n,r,g.content,{annotations:G}),!await Qs(`Apply (auto-fix, line ${g.line}, distance ${g.distance})`))return"CANCELLED: User declined to apply edit."}await De.writeFile(n,g.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||g.content.startsWith("#!"))&&await De.chmod(n,493),Or("edit_file",n,r,g.content);let j=g.matchText.length>80?g.matchText.substring(0,77)+"...":g.matchText;return console.log(`${ce.dim} \u2713 auto-fixed edit: line ${g.line}, distance ${g.distance}${ce.reset}`),`Edited: ${n} (auto-fixed, line ${g.line}, distance ${g.distance}, matched: "${j}")`}let m=no(r,e.old_text);if(m){let j=r.split(`
|
|
287
|
+
`),G=Math.max(0,m.line-6),L=Math.min(j.length,m.line+10),P=j.slice(G,L).map((Z,Y)=>`${G+Y+1}: ${Z}`).join(`
|
|
288
|
+
`),C=`line_start=${Math.max(1,m.line-5)} line_end=${Math.min(j.length,m.line+15)}`;return`ERROR: old_text not found in ${n} (most similar at line ${m.line}, distance ${m.distance})
|
|
258
289
|
|
|
259
|
-
Actual file content around line ${
|
|
260
|
-
${
|
|
290
|
+
Actual file content around line ${m.line} \u2014 use this to correct old_text:
|
|
291
|
+
${P}
|
|
261
292
|
|
|
262
293
|
Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${C}`}let b=(e.old_text||"").trim().split(`
|
|
263
|
-
`)[0].slice(0,60),
|
|
294
|
+
`)[0].slice(0,60),x=b?`
|
|
264
295
|
Recovery: grep -n "${b.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
|
|
265
|
-
Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${n}${
|
|
266
|
-
`)||"(empty)"}case"search_files":{let n=
|
|
296
|
+
Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${n}${x}`}}if(!s.autoConfirm){let u=r.split(i).join(e.new_text),d=await eo(n,u);if(Ar(n,r,u,{annotations:d}),!await Qs(a?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let l=r.split(i).join(e.new_text);return await De.writeFile(n,l,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||l.startsWith("#!"))&&await De.chmod(n,493),Or("edit_file",n,r,l),a?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await pt(n)){let l=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=it(l),d=await pt(u);if(u&&d)n=u;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let l=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${l}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let a=[],c=async(l,u,d)=>{if(u>r)return;let f;try{f=await De.readdir(l,{withFileTypes:!0})}catch{return}f=f.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of f){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let g=h.isDirectory()?"/":"";a.push(`${d}${h.name}${g}`),h.isDirectory()&&await c(Ee.join(l,h.name),u+1,d+" ")}};return await c(n,1,""),a.join(`
|
|
297
|
+
`)||"(empty)"}case"search_files":{let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn","--null","-H"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,n);try{let{stdout:r}=await ja("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),a=[];for(let c=0;c<i.length;c+=2){let l=i[c],u=i[c+1];if(l&&u){let d=u.split(`
|
|
267
298
|
`).filter(f=>f.trim());for(let f of d)if(a.push(`${l}:${f}`),a.length>=50)break}if(a.length>=50)break}return a.join(`
|
|
268
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?
|
|
269
|
-
`);return f.update({count:
|
|
270
|
-
|
|
271
|
-
\u26A0 Results truncated at 200. Use a more specific pattern.`:
|
|
272
|
-
`);for(let b of d)if(b.startsWith("diff --git")){let
|
|
273
|
-
`).filter(
|
|
274
|
-
`).filter(
|
|
275
|
-
`).trim()||"(no matches in staged files)"}let o=["-rn","-E","--null","-H"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),e.type&&o.push(`--include=*.${e.type}`);let r=20;e.context?o.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&o.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&o.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?o.push("-l"):e.output_mode==="count"&&o.push("-c"),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,n);let{ToolProgress:i}=
|
|
276
|
-
`).filter(f=>f.trim());else{let f=c.split("\0");l=[];for(let h=0;h<f.length;h+=2){let
|
|
277
|
-
`).filter(
|
|
278
|
-
`).trim()||"(no matches)"}catch(c){return a.stop(),c.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await
|
|
279
|
-
`+
|
|
299
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?it(e.path):o,i=e.pattern,a=Y=>{let ue=Y.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${ue}$`)},c=a(i),l=i.split("/").pop(),u=a(l),{ToolProgress:d}=zn(),f=new d("glob","Finding files...");f.start();let{getFileIndex:h,getIndexedCwd:g,refreshIndex:m,isIndexValid:b}=da(),x=h(),j=g();b(r)||(await m(r),x=h());let G=x.filter(Y=>c.test(Y)||u.test(Ee.basename(Y))).map(Y=>Ee.join(r,Y));if(G.length===0)return f.stop(),"(no matches)";let L=await Promise.all(G.slice(0,210).map(async Y=>{try{let ue=await De.stat(Y);return{path:Y,mtime:ue.mtimeMs}}catch{return{path:Y,mtime:0}}}));L.sort((Y,ue)=>ue.mtime-Y.mtime);let P=L.map(Y=>Y.path),C=G.length>200,Z=P.slice(0,200).join(`
|
|
300
|
+
`);return f.update({count:G.length,detail:e.pattern}),f.stop(),C?`${Z}
|
|
301
|
+
|
|
302
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:Z}case"grep":{let n=e.path?it(e.path):process.cwd();if(e.staged){let{getDiff:c}=sr(),l=await c(!0);if(!l.trim())return"(no staged changes)";let u=new Set,d=l.split(`
|
|
303
|
+
`);for(let b of d)if(b.startsWith("diff --git")){let x=b.match(/diff --git a\/(.+) b\/(.+)/);x&&u.add(x[2])}let f=["-rn","-E","--null","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&f.push("-i"),e.include&&f.push(`--include=${e.include}`),e.type&&f.push(`--include=*.${e.type}`),e.context?f.push("-C",String(e.context)):(e.before_context&&f.push("-B",String(e.before_context)),e.after_context&&f.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?f.push("-l"):e.output_mode==="count"&&f.push("-c"),f.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:h}=zn(),g=new h("grep","Searching staged content...");g.start();let m=[];for(let b of u)try{let x=Ee.join(process.cwd(),b);if(await pt(x)){let j=[...f];j.push(e.pattern,x);let{stdout:G}=await ja("grep",j,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let L=G.trim().split(`
|
|
304
|
+
`).filter(P=>P.trim());m=m.concat(L)}else{let L=G.split("\0");for(let P=0;P<L.length;P+=2){let C=L[P+1];if(C){let Z=C.split(`
|
|
305
|
+
`).filter(Y=>Y.trim());for(let Y of Z)m.push(`${b}:${Y}`)}}}}}catch{}return g.update({count:m.length,detail:"in staged files"}),g.stop(),m.join(`
|
|
306
|
+
`).trim()||"(no matches in staged files)"}let o=["-rn","-E","--null","-H"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),e.type&&o.push(`--include=*.${e.type}`);let r=20;e.context?o.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&o.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&o.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?o.push("-l"):e.output_mode==="count"&&o.push("-c"),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,n);let{ToolProgress:i}=zn(),a=new i("grep","Searching...");a.start();try{let{stdout:c}=await ja("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),l;if(e.output_mode==="files_with_matches"||e.output_mode==="count")l=c.trim().split(`
|
|
307
|
+
`).filter(f=>f.trim());else{let f=c.split("\0");l=[];for(let h=0;h<f.length;h+=2){let g=f[h],m=f[h+1];if(g&&m){let b=m.split(`
|
|
308
|
+
`).filter(x=>x.trim());for(let x of b)l.push(`${g}:${x}`)}}}let u=e.offset||0,d=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return l=l.slice(u,u+d),a.update({count:l.length,detail:`in ${n}`}),a.stop(),l.join(`
|
|
309
|
+
`).trim()||"(no matches)"}catch(c){return a.stop(),c.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Fa();let n=it(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await pt(n)){let x=await Nr(e.path);if(x.fixedPath)n=x.fixedPath,console.log(`${ce.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ee.relative(process.cwd(),n)}${ce.reset}`);else return`ERROR: File not found: ${e.path}${x.message?`
|
|
310
|
+
`+x.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await De.readFile(n,"utf-8"),{getActiveModelId:a,getActiveProviderName:c}=Ge(),l=If(a(),c()),u=[],d=!1,f=!1;for(let x=0;x<r.length;x++){let{old_text:j,new_text:G}=r[x];if(i.includes(j))u.push({old_text:j,new_text:G});else if(l==="strict"){let L=no(i,j);return L?`ERROR: Patch ${x+1} old_text not found in ${n} (strict mode \u2014 exact match required)
|
|
280
311
|
Most similar text (line ${L.line}, distance ${L.distance}):
|
|
281
|
-
${L.text}`:`ERROR: Patch ${
|
|
282
|
-
Most similar text (line ${
|
|
283
|
-
${
|
|
312
|
+
${L.text}`:`ERROR: Patch ${x+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let L=Pf(i,j);if(L)u.push({old_text:L,new_text:G}),d=!0;else{let P=no(i,j);if(P){let C=Math.max(3,Math.ceil(j.length*.05));if(P.distance<=C)u.push({old_text:P.text,new_text:G}),f=!0;else return`ERROR: Patch ${x+1} old_text not found in ${n}
|
|
313
|
+
Most similar text (line ${P.line}, distance ${P.distance}):
|
|
314
|
+
${P.text}`}else return`ERROR: Patch ${x+1} old_text not found in ${n}`}}}let h=i;for(let{old_text:x,new_text:j}of u)h=h.split(x).join(j);if(!s.autoConfirm){let x=await eo(n,h);if(Ar(n,i,h,{annotations:x}),!await Qs(d?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await De.writeFile(n,h,"utf-8");let g=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||h.startsWith("#!");g&&await De.chmod(n,493),Or("patch_file",n,i,h);let m=f?" (auto-fixed)":d?" (fuzzy match)":"",b=g?" [chmod +x applied]":"";return`Patched: ${n} (${r.length} replacements)${m}${b}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let r=await Da.get(n,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof r.data=="string"?r.data:JSON.stringify(r.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,o)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${n}: ${r.message}`}}case"web_search":{let n=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await Da.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=o.data?.choices?.[0]?.message?.content||"",i=o.data?.citations||[],a=`[Perplexity grounded search]
|
|
284
315
|
|
|
285
316
|
${r}`;return i.length>0&&(a+=`
|
|
286
317
|
|
|
287
318
|
Sources:
|
|
288
319
|
`+i.slice(0,n).map((c,l)=>`${l+1}. ${c}`).join(`
|
|
289
|
-
`)),a}catch(o){console.error(`${
|
|
320
|
+
`)),a}catch(o){console.error(`${ce.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${ce.reset}`)}try{let r=(await Da.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],a=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,c;for(;(c=a.exec(r))!==null&&i.length<n;){let l=c[1].replace(/.*uddg=/,"").split("&")[0],u=c[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:u,url:decodeURIComponent(l)})}catch{i.push({title:u,url:l})}}return i.length===0?"(no results)":i.map((l,u)=>`${u+1}. ${l.title}
|
|
290
321
|
${l.url}`).join(`
|
|
291
322
|
|
|
292
|
-
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=
|
|
323
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=Bs();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
|
|
293
324
|
|
|
294
325
|
Links:
|
|
295
326
|
`+o.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
|
|
296
327
|
`):"";return`Title: ${o.title}
|
|
297
328
|
URL: ${o.url}
|
|
298
329
|
|
|
299
|
-
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=
|
|
330
|
+
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=Bs();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
|
|
300
331
|
Title: ${o.title}
|
|
301
332
|
URL: ${o.url}
|
|
302
333
|
|
|
303
|
-
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=
|
|
334
|
+
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=Bs();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=Bs();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"ask_user":{let{question:n,options:o=[]}=e;return Ba?new Promise(r=>{Sn=()=>r("CANCELLED"),Ba(n,o).then(i=>{Sn=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});Sn=()=>{i.close(),r("CANCELLED")};let a=o.length>0?`
|
|
304
335
|
${o.map((c,l)=>` ${l+1}. ${c}`).join(`
|
|
305
336
|
`)}
|
|
306
337
|
`:"";console.log(`
|
|
307
|
-
${
|
|
338
|
+
${ce.cyan}${ce.bold} ? ${n}${ce.reset}${a}`),i.question(`${ce.cyan} > ${ce.reset}`,c=>{Sn=null,i.close(),r(c.trim()||"(no response)")})})}case"git_status":{if(!await qa())return"ERROR: Not a git repository";let n=await Lf()||"(detached)",o=await v0();if(o.length===0)return`Branch: ${n}
|
|
308
339
|
Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let i of o){let a=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${a}: ${i.file}`)}return r.join(`
|
|
309
|
-
`)}case"git_diff":{if(!await
|
|
340
|
+
`)}case"git_diff":{if(!await qa())return"ERROR: Not a git repository";let n;if(e.file){let o=["diff"];e.staged&&o.push("--cached"),o.push("--",e.file);try{n=execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{n=""}}else n=await S0(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await qa())return"ERROR: Not a git repository";let o=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&o.push("--",e.file);try{return execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:n,updateTask:o,getTaskList:r,renderTaskList:i,hasActiveTasks:a}=$a(),{getActiveTaskProgress:c}=He(),l=c();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let u=n(e.name,e.tasks);return l||console.log(`
|
|
310
341
|
`+i()),`Created task list "${e.name}" with ${u.length} tasks:
|
|
311
342
|
`+u.map(d=>` ${d.id}: ${d.description}`).join(`
|
|
312
343
|
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":o(e.task_id,e.status,e.result)?(l||console.log(`
|
|
313
344
|
`+i()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let u=r();return u.tasks.length===0?"No active tasks":(l||console.log(`
|
|
314
|
-
`+i()),JSON.stringify(u,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=
|
|
345
|
+
`+i()),JSON.stringify(u,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=Sa();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=Ge();return n(e.model)?`Switched to ${o()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let n=Math.min(e.limit||10,30),o=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:r}=await Ce(`gh ${o.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(c=>{let l=c.conclusion||c.status||"unknown",u=l==="success"?"\u2713":l==="failure"?"\u2717":l==="in_progress"?"\u283F":"\u25CB",d=c.updatedAt?new Date(c.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${u} [${c.databaseId}] ${c.name} \xB7 ${c.headBranch} \xB7 ${l} \xB7 ${d}`}).join(`
|
|
315
346
|
`)}catch(r){let i=(r.stderr||r.message||"").toString();return i.includes("not found")||i.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${i.split(`
|
|
316
|
-
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await
|
|
317
|
-
...(truncated)`:"")}let{stdout:n}=await
|
|
347
|
+
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await Ce(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
|
|
348
|
+
...(truncated)`:"")}let{stdout:n}=await Ce(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of o.jobs||[]){let a=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${a} ${i.name} (${i.conclusion||i.status})`);for(let c of i.steps||[]){if(c.conclusion==="failure"||c.conclusion==="skipped")continue;let l=c.conclusion==="success"?" \u2713":c.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${l} ${c.name}`)}}return r.join(`
|
|
318
349
|
`)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
|
|
319
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=
|
|
320
|
-
${
|
|
321
|
-
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=
|
|
322
|
-
`)[0];return a.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${a}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=
|
|
350
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Cs(),o=e.branch||await Lf()||"main",r=e.inputs?Object.entries(e.inputs).map(([c,l])=>`-f ${c}=${l}`).join(" "):"",i=`gh workflow run ${e.workflow} --ref ${o} ${r}`.trim();if(console.log(`
|
|
351
|
+
${ce.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${ce.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await Ce(i,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
352
|
+
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=to(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:a}=await Ce(r,{timeout:3e4,maxBuffer:2097152});return(i||a||"(no pods)").trim()}catch(i){let a=(i.stderr||i.message||"").toString().split(`
|
|
353
|
+
`)[0];return a.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${a}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=to(r,e);try{let{stdout:a,stderr:c}=await Ce(i,{timeout:6e4,maxBuffer:5242880}),l=(a||c||"(no logs)").trim();return l.substring(0,2e4)+(l.length>2e4?`
|
|
323
354
|
...(truncated)`:"")}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
324
355
|
`)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let n=e.namespace||"default";if(console.log(`
|
|
325
|
-
${
|
|
356
|
+
${ce.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${ce.reset}`),console.log(`${ce.dim} Command: ${e.command}${ce.reset}`),!await vt(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${n}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=to(r,e);try{let{stdout:a,stderr:c}=await Ce(i,{timeout:6e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
326
357
|
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let n=!!e.dry_run;if(!n){let i=e.file;if(console.log(`
|
|
327
|
-
${
|
|
358
|
+
${ce.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${ce.reset}`),!await vt(" Apply to cluster?"))return"CANCELLED: User declined."}let o=`apply -f ${e.file}`;e.namespace&&(o+=` -n ${e.namespace}`),n&&(o+=" --dry-run=client");let r=to(o,e);try{let{stdout:i,stderr:a}=await Ce(r,{timeout:12e4,maxBuffer:2097152});return(i||a||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
|
|
328
359
|
`)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let n=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let a=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
|
|
329
|
-
${
|
|
330
|
-
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=
|
|
360
|
+
${ce.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${n})${ce.reset}`),!await vt(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=to(r,e);try{let{stdout:a,stderr:c}=await Ce(i,{timeout:12e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
361
|
+
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=Ma(),{name:r,content:i,mode:a}=e;if(a==="create"&&o(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(a==="append"){let c=o(r),l=c.content?c.content+`
|
|
331
362
|
|
|
332
|
-
`+i:i;return n(r,l),`Appended to brain document: ${r}.md`}return n(r,i),`${a==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n
|
|
363
|
+
`+i:i;return n(r,l),`Appended to brain document: ${r}.md`}return n(r,i),`${a==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=bt(e.server)}catch(C){return`ERROR: ${C.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=$0(o);if(a)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(o)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
|
|
333
364
|
grep -n "pattern" /path/to/file -A 50
|
|
334
365
|
or to read the whole file:
|
|
335
366
|
cat /path/to/file
|
|
336
367
|
NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${a}
|
|
337
|
-
HINT: Do not read .env, credentials, or private key files via ssh_exec \u2014 secrets would appear in tool output. Reference variable names or file paths instead.`;if(o=o.replace(/(-[BAC])\s*(\d+)/g,(C,
|
|
338
|
-
${
|
|
368
|
+
HINT: Do not read .env, credentials, or private key files via ssh_exec \u2014 secrets would appear in tool output. Reference variable names or file paths instead.`;if(o=o.replace(/(-[BAC])\s*(\d+)/g,(C,Z,Y)=>{let ue=Math.min(Number(Y),20);return`${Z} ${ue}`}),o=o.replace(/(--(?:before|after|context)=)(\d+)/g,(C,Z,Y)=>Z+Math.min(Number(Y),20)),/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(o)){let C=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
369
|
+
${ce.yellow} \u26A0 Remote command on ${C}: ${o}${ce.reset}`),!await vt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await rt(n,o,{timeout:i,sudo:r}),h=[l,u].filter(Boolean).join(`
|
|
339
370
|
`).trim();if(d!==0)return`EXIT ${d}
|
|
340
|
-
${f||h||"(no output)"}`;let
|
|
371
|
+
${f||h||"(no output)"}`;let g=/\bgrep\b/.test(o),m=h;g&&(m=m.split(`
|
|
341
372
|
`).filter(C=>C!=="--").join(`
|
|
342
|
-
`));let b=
|
|
343
|
-
`);
|
|
344
|
-
`+
|
|
345
|
-
`));let
|
|
346
|
-
`),L=[],
|
|
347
|
-
`)||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n
|
|
348
|
-
${
|
|
349
|
-
${h.slice(-2e3)}`:h.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let n=["status","start","stop","restart","reload","enable","disable"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!o)try{i
|
|
350
|
-
${
|
|
351
|
-
${d}`}}else{let{stdout:c,stderr:l,exitCode:u,error:d}=await
|
|
373
|
+
`));let b=g?60:100,x=m.split(`
|
|
374
|
+
`);x.length>b&&(m=`(${x.length-b} earlier lines omitted \u2014 showing last ${b})
|
|
375
|
+
`+x.slice(-b).join(`
|
|
376
|
+
`));let j=4,G=m.split(`
|
|
377
|
+
`),L=[],P=0;for(;P<G.length;){let C=P+1;for(;C<G.length&&G[C]===G[P];)C++;let Z=C-P;if(L.push(G[P]),Z>j)L.push(`... (${Z-1} identical lines omitted)`);else for(let Y=1;Y<Z;Y++)L.push(G[P]);P=C}return L.join(`
|
|
378
|
+
`)||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=bt(e.server)}catch(i){return`ERROR: ${i.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
379
|
+
${ce.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${ce.reset}`),!await vt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await T0(n,e.local_path,e.remote_path)}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let n;try{n=bt(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await R0(n,e.remote_path,e.local_path)}catch(o){return`ERROR: ${o.message}`}}case"remote_agent":{let n=require("path").join(process.cwd(),".nex","servers.json"),o=null;try{o=JSON.parse(require("fs").readFileSync(n,"utf-8"))[e.server]||null}catch{}let r=o?`${o.user||"root"}@${o.host}`:e.server,i=o?.key?["-i",o.key]:[],a=e.project_path||o?.home||"~",c=e.model||"",u=["TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt)",`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${a}" 2>/dev/null || true`,c?`nex-code --prompt-file "$TMPFILE" --auto --model "${c}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:d}=require("child_process"),f=d("ssh",[...i,"-o","StrictHostKeyChecking=no","-o","ConnectTimeout=10",r,`bash -c '${u}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(f.error)return`ERROR: SSH connection failed: ${f.error.message}`;let h=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
|
|
380
|
+
${h.slice(-2e3)}`:h.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let n=["status","start","stop","restart","reload","enable","disable"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!o)try{i=bt(e.server)}catch(c){return`ERROR: ${c.message}`}if(!r){let c=o?"local machine":i.user?`${i.user}@${i.host}`:i.host;if(console.log(`
|
|
381
|
+
${ce.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${c}${ce.reset}`),!await vt(" Execute?"))return"CANCELLED: User declined service action."}let a=`systemctl ${e.action} ${e.service}`;if(o){let l=e.action!=="status"?`sudo ${a}`:a;try{let{stdout:u,stderr:d}=await Ce(l,{timeout:15e3});return(u||d||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(u){let d=(u.stderr||u.message||"").toString().trim();return/not found|loaded.*not-found/i.test(d)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${u.code||1}
|
|
382
|
+
${d}`}}else{let{stdout:c,stderr:l,exitCode:u,error:d}=await rt(i,a,{timeout:15e3,sudo:!0}),f=[c,l].filter(Boolean).join(`
|
|
352
383
|
`).trim();return u!==0?/not found|loaded.*not-found/i.test(f)?`ERROR: Service "${e.service}" not found on ${i.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${u}
|
|
353
|
-
${d||f||"(no output)"}`:f||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",a=`journalctl -u ${e.service} -n ${o} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:
|
|
354
|
-
${(
|
|
384
|
+
${d||f||"(no output)"}`:f||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",a=`journalctl -u ${e.service} -n ${o} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:g,stderr:m}=await Ce(a,{timeout:15e3});return(g||m||"(no log output)").trim()}catch(g){return`EXIT ${g.code||1}
|
|
385
|
+
${(g.stderr||g.message||"").toString().trim()}`}let c;try{c=bt(e.server)}catch(g){return`ERROR: ${g.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await rt(c,a,{timeout:2e4}),h=[l,u].filter(Boolean).join(`
|
|
355
386
|
`).trim();return d!==0?`EXIT ${d}
|
|
356
|
-
${f||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:f,stderr:h}=await
|
|
357
|
-
${(f.stderr||f.message||"").toString().trim()}`}let i;try{i
|
|
387
|
+
${f||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:f,stderr:h}=await Ce(r,{timeout:1e4});return(f||h||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
|
|
388
|
+
${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=bt(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:c,exitCode:l,error:u}=await rt(i,r,{timeout:15e3}),d=[a,c].filter(Boolean).join(`
|
|
358
389
|
`).trim();return l!==0?`EXIT ${l}
|
|
359
|
-
${u||d}`:d||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:h,stderr:
|
|
360
|
-
${(h.stderr||h.message||"").toString().trim()}`}let a;try{a
|
|
390
|
+
${u||d}`:d||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:h,stderr:g}=await Ce(i,{timeout:15e3});return(h||g||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
391
|
+
${(h.stderr||h.message||"").toString().trim()}`}let a;try{a=bt(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await rt(a,i,{timeout:2e4}),f=[c,l].filter(Boolean).join(`
|
|
361
392
|
`).trim();return u!==0?`EXIT ${u}
|
|
362
|
-
${d||f}`:f||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!o.test(e.command.trim())){let
|
|
363
|
-
${
|
|
364
|
-
${(
|
|
393
|
+
${d||f}`:f||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!o.test(e.command.trim())){let g=n?"local":e.server;if(console.log(`
|
|
394
|
+
${ce.yellow} \u26A0 docker exec in ${e.container} on ${g}: ${e.command}${ce.reset}`),!await vt(" Execute?"))return"CANCELLED: User declined."}let i=(e.container||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(!i)return"ERROR: Invalid container name";let a=`docker exec ${i} sh -c ${JSON.stringify(e.command)}`;if(n)try{let{stdout:g,stderr:m}=await Ce(a,{timeout:3e4});return(g||m||"(no output)").trim()}catch(g){return`EXIT ${g.code||1}
|
|
395
|
+
${(g.stderr||g.message||"").toString().trim()}`}let c;try{c=bt(e.server)}catch(g){return`ERROR: ${g.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await rt(c,a,{timeout:35e3}),h=[l,u].filter(Boolean).join(`
|
|
365
396
|
`).trim();return d!==0?`EXIT ${d}
|
|
366
|
-
${f||h}`:h||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let
|
|
367
|
-
${
|
|
368
|
-
${(
|
|
397
|
+
${f||h}`:h||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let g=o?"local":e.server;if(console.log(`
|
|
398
|
+
${ce.yellow} \u26A0 docker ${e.action} ${e.container} on ${g}${ce.reset}`),!await vt(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,a=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(o)try{let{stdout:g,stderr:m}=await Ce(a,{timeout:3e4});return(g||m||`docker ${e.action} ${e.container}: OK`).trim()}catch(g){return`EXIT ${g.code||1}
|
|
399
|
+
${(g.stderr||g.message||"").toString().trim()}`}let c;try{c=bt(e.server)}catch(g){return`ERROR: ${g.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await rt(c,a,{timeout:35e3}),h=[l,u].filter(Boolean).join(`
|
|
369
400
|
`).trim();return d!==0?`EXIT ${d}
|
|
370
|
-
${f||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...
|
|
371
|
-
${
|
|
372
|
-
${
|
|
401
|
+
${f||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...C0(e.config),...e},delete e.config,delete e._name}catch(u){return`ERROR: ${u.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let n=e.method||"rsync";if(n==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let o;try{o=bt(e.server)}catch(u){return`ERROR: ${u.message}`}let r=o.user?`${o.user}@${o.host}`:o.host;if(!e.dry_run&&!s.autoConfirm){if(n==="git"){let d=e.branch?` (branch: ${e.branch})`:"";console.log(`
|
|
402
|
+
${ce.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${d}${ce.reset}`)}else{let d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
|
|
403
|
+
${ce.yellow} \u26A0 Deploy [rsync]: ${d} \u2192 ${r}:${e.remote_path}${ce.reset}`)}if(e.deploy_script&&console.log(`${ce.yellow} Then run: ${e.deploy_script}${ce.reset}`),e.health_check&&console.log(`${ce.yellow} Health check: ${e.health_check}${ce.reset}`),!await vt(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(n==="git"){let u=(e.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(e.branch&&u!==e.branch)return`ERROR: Invalid branch name: ${e.branch}`;let d=(e.remote_path||"").replace(/'/g,"'\\''"),f=u?`cd '${d}' && git fetch origin && git checkout '${u}' && git pull origin '${u}'`:`cd '${d}' && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
|
|
373
404
|
${f}${e.deploy_script?`
|
|
374
|
-
${e.deploy_script}`:""}`;let{stdout:h,stderr:
|
|
375
|
-
`).trim(),
|
|
376
|
-
${b||i}`}else{let u=o.key?`-e "ssh -i ${o.key.replace(/^~/,require("os").homedir())}${o.port&&Number(o.port)!==22?` -p ${o.port}`:""}"`:o.port&&Number(o.port)!==22?`-e "ssh -p ${o.port}"`:"",d=(e.exclude||[]).map(
|
|
377
|
-
${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:h}=await
|
|
405
|
+
${e.deploy_script}`:""}`;let{stdout:h,stderr:g,exitCode:m,error:b}=await rt(o,f,{timeout:12e4});if(i=[h,g].filter(Boolean).join(`
|
|
406
|
+
`).trim(),m!==0)return`ERROR (git pull, exit ${m}):
|
|
407
|
+
${b||i}`}else{let u=o.key?`-e "ssh -i ${o.key.replace(/^~/,require("os").homedir())}${o.port&&Number(o.port)!==22?` -p ${o.port}`:""}"`:o.port&&Number(o.port)!==22?`-e "ssh -p ${o.port}"`:"",d=(e.exclude||[]).map(m=>`--exclude="${m}"`).join(" "),f=e.dry_run?"--dry-run":"",h=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,g=`rsync -avz --delete ${f} ${d} ${u} ${h} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:m,stderr:b}=await Ce(g,{timeout:12e4});i=(m||b||"").trim()}catch(m){return`ERROR (rsync): ${(m.stderr||m.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
|
|
408
|
+
${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:u,stderr:d,exitCode:f,error:h}=await rt(o,e.deploy_script,{timeout:12e4}),g=[u,d].filter(Boolean).join(`
|
|
378
409
|
`).trim();if(f!==0)return`${n==="git"?"git pull":"rsync"} OK
|
|
379
410
|
|
|
380
411
|
ERROR (deploy_script, exit ${f}):
|
|
381
|
-
${h||
|
|
412
|
+
${h||g}`;a=`
|
|
382
413
|
|
|
383
414
|
Deploy script output:
|
|
384
|
-
${
|
|
415
|
+
${g||"(no output)"}`}let c="";if(e.health_check){let u=e.health_check.trim();if(/^https?:\/\//.test(u))try{let f=require("node-fetch"),h=await Promise.race([f(u),new Promise((g,m)=>setTimeout(()=>m(new Error("timeout")),15e3))]);if(h.ok)c=`
|
|
385
416
|
|
|
386
417
|
Health check: \u2713 ${u} \u2192 ${h.status}`;else return c=`
|
|
387
418
|
|
|
388
419
|
Health check FAILED: ${u} \u2192 HTTP ${h.status}`,(n==="git"?"git pull OK":"rsync OK")+i+a+c}catch(f){return c=`
|
|
389
420
|
|
|
390
|
-
Health check FAILED: ${u} \u2192 ${f.message}`,(n==="git"?"git pull OK":"rsync OK")+i+a+c}else{let{stdout:f,stderr:h,exitCode:
|
|
391
|
-
`).trim();if(
|
|
421
|
+
Health check FAILED: ${u} \u2192 ${f.message}`,(n==="git"?"git pull OK":"rsync OK")+i+a+c}else{let{stdout:f,stderr:h,exitCode:g}=await rt(o,u,{timeout:15e3}),m=[f,h].filter(Boolean).join(`
|
|
422
|
+
`).trim();if(g!==0)return c=`
|
|
392
423
|
|
|
393
|
-
Health check FAILED (exit ${
|
|
424
|
+
Health check FAILED (exit ${g}): ${m}`,(n==="git"?"git pull OK":"rsync OK")+i+a+c;c=`
|
|
394
425
|
|
|
395
|
-
Health check: \u2713 ${
|
|
396
|
-
${i}${a}${c}`.trim()}case"deployment_status":{let n=
|
|
426
|
+
Health check: \u2713 ${m||"(exit 0)"}`}}let l=n==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${n}] ${l}
|
|
427
|
+
${i}${a}${c}`.trim()}case"deployment_status":{let n=A0(),o=e.config?[e.config]:Object.keys(n);if(o.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of o){let a=n[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let c=bt(a.server||i),u=(await rt(c,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let h=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(h)try{d=(await rt(c,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let h=a.health_check.trim();if(/^https?:\/\//.test(h))try{let g=require("node-fetch"),m=await Promise.race([g(h),new Promise((b,x)=>setTimeout(()=>x(new Error("timeout")),1e4))]);f=m.ok?"healthy":`HTTP ${m.status}`}catch(g){f=`unhealthy: ${g.message.substring(0,50)}`}else try{f=(await rt(c,h,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{f="unhealthy"}}r.push(`${i}: server=${u?"reachable":"unreachable"} service=${d} health=${f}`)}catch(c){r.push(`${i}: ERROR \u2014 ${c.message}`)}}return`Deployment Status:
|
|
397
428
|
${r.join(`
|
|
398
|
-
`)}`}case"frontend_recon":{let n=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(L,
|
|
399
|
-
`),
|
|
400
|
-
`);return
|
|
401
|
-
... (${
|
|
402
|
-
`).filter(Boolean)}catch{return[]}},u=async(L,
|
|
429
|
+
`)}`}case"frontend_recon":{let n=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(L,P=120)=>{try{let C=Ee.isAbsolute(L)?L:Ee.join(n,L),Y=(await De.readFile(C,"utf8")).split(`
|
|
430
|
+
`),ue=Y.slice(0,P).join(`
|
|
431
|
+
`);return Y.length>P?ue+`
|
|
432
|
+
... (${Y.length-P} more lines \u2014 use read_file for full content)`:ue}catch{return null}},c=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(L=>`-not -path "*/${L}/*"`).join(" "),l=async L=>{try{let{stdout:P}=await Ce(`find "${n}" -type f -name "${L}" ${c} 2>/dev/null | head -10`,{timeout:8e3});return P.trim().split(`
|
|
433
|
+
`).filter(Boolean)}catch{return[]}},u=async(L,P)=>{try{let{stdout:C}=await Ce(`grep -rl "${L}" "${n}" --include="${P}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return C.trim().split(`
|
|
403
434
|
`).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
|
|
404
|
-
`);let d=[...await l("tailwind.config.js"),...await l("tailwind.config.ts"),...await l("tailwind.config.mjs")];if(d.length>0){let L=await i(d[0],80);L&&r.push(`### Tailwind config (${
|
|
435
|
+
`);let d=[...await l("tailwind.config.js"),...await l("tailwind.config.ts"),...await l("tailwind.config.mjs")];if(d.length>0){let L=await i(d[0],80);L&&r.push(`### Tailwind config (${Ee.relative(n,d[0])})
|
|
405
436
|
\`\`\`js
|
|
406
437
|
${L}
|
|
407
|
-
\`\`\``)}else r.push("(no tailwind.config found)");let f=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],h=!1;for(let L of f){let
|
|
438
|
+
\`\`\``)}else r.push("(no tailwind.config found)");let f=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],h=!1;for(let L of f){let P=await l(L);for(let C of P){let Z=await i(C,100);if(Z&&Z.includes(":root")){r.push(`### CSS Variables (${Ee.relative(n,C)})
|
|
408
439
|
\`\`\`css
|
|
409
|
-
${
|
|
410
|
-
\`\`\``),h=!0;break}}if(h)break}if(!h){let L=await u(":root","*.css");if(L.length>0){let
|
|
440
|
+
${Z}
|
|
441
|
+
\`\`\``),h=!0;break}}if(h)break}if(!h){let L=await u(":root","*.css");if(L.length>0){let P=await i(L[0],100);P&&r.push(`### CSS Variables (${Ee.relative(n,L[0])})
|
|
411
442
|
\`\`\`css
|
|
412
|
-
${
|
|
443
|
+
${P}
|
|
413
444
|
\`\`\``),h=!0}}h||r.push("(no CSS custom properties / :root found)"),r.push(`
|
|
414
445
|
## STEP 2: Main Layout / Index Page
|
|
415
|
-
`);let
|
|
446
|
+
`);let g=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],m=!1;for(let L of g){let P=await l(L);if(P.length>0){let C=await i(P[0],150);if(C){r.push(`### Main layout: ${Ee.relative(n,P[0])}
|
|
416
447
|
\`\`\`html
|
|
417
448
|
${C}
|
|
418
|
-
\`\`\``),
|
|
449
|
+
\`\`\``),m=!0;break}}}m||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
|
|
419
450
|
## STEP 3: Reference Component (same type)
|
|
420
|
-
`);let b=[];if(o){for(let L of["*.html","*.vue","*.jsx","*.tsx"])if(b=await u(o,L),b.length>0)break}if(b.length===0)try{let{stdout:L}=await
|
|
421
|
-
`).filter(Boolean)}catch{b=[]}if(b.length>0){let L=b[0],
|
|
451
|
+
`);let b=[];if(o){for(let L of["*.html","*.vue","*.jsx","*.tsx"])if(b=await u(o,L),b.length>0)break}if(b.length===0)try{let{stdout:L}=await Ce(`find "${n}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});b=L.trim().split(`
|
|
452
|
+
`).filter(Boolean)}catch{b=[]}if(b.length>0){let L=b[0],P=await i(L,150);P?r.push(`### Reference: ${Ee.relative(n,L)}
|
|
422
453
|
\`\`\`html
|
|
423
|
-
${
|
|
454
|
+
${P}
|
|
424
455
|
\`\`\``):r.push("(reference file found but could not be read)")}else r.push("(no reference component found \u2014 check manually with glob or list_directory)");r.push(`
|
|
425
456
|
## STEP 4: Framework Stack
|
|
426
|
-
`);let
|
|
457
|
+
`);let x=[],j=await i(Ee.join(n,"package.json"),999);if(j){if((j.includes('"react"')||j.includes("'react'"))&&x.push("React"),j.includes('"vue"')||j.includes("'vue'")){let P=j.match(/"vue":\s*"[\^~]?(\d+)/);x.push(P?`Vue.js v${P[1]}`:"Vue.js")}let L=j.match(/"alpinejs":\s*"[\^~]?(\d+)/);L&&x.push(`Alpine.js v${L[1]} (\u26A0 v2 vs v3 API differs!)`),(j.includes('"htmx')||j.includes("'htmx"))&&x.push("HTMX"),j.includes('"tailwindcss"')&&x.push("Tailwind CSS"),j.includes('"bootstrap"')&&x.push("Bootstrap")}if((await pt(Ee.join(n,"manage.py"))||(await i(Ee.join(n,"requirements.txt"),50)||"").includes("Django"))&&x.push("Django (server-rendered templates)"),!x.some(L=>L.includes("Alpine"))){let L=await u("alpinejs","*.html");if(L.length>0){let C=(await i(L[0],30)||"").match(/alpinejs[@/]v?(\d)/);x.push(C?`Alpine.js v${C[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return x.some(L=>L.includes("HTMX"))||(await u("htmx","*.html")).length>0&&x.push("HTMX (via CDN)"),x.length>0?(r.push(x.map(L=>`- ${L}`).join(`
|
|
427
458
|
`)),r.push(`
|
|
428
459
|
\u26A0 Use ONLY the frameworks listed above. Do NOT mix (e.g. no fetch() when HTMX is used for the same action).`)):r.push("(framework not detected \u2014 check package.json or script tags manually)"),r.push(`
|
|
429
460
|
---
|
|
430
461
|
\u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
|
|
431
|
-
`)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let n=!e.server||e.server==="local"||e.server==="localhost",o;if(!n)try{o
|
|
462
|
+
`)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let n=!e.server||e.server==="local"||e.server==="localhost",o;if(!n)try{o=bt(e.server)}catch(c){return`ERROR: ${c.message}`}let r=async(c,l=3e4)=>{if(n)try{let{stdout:u,stderr:d}=await Ce(c,{timeout:l});return{out:(u||d||"").trim(),exitCode:0}}catch(u){return{out:(u.stderr||u.message||"").toString().trim(),exitCode:u.code||1}}else{let{stdout:u,stderr:d,exitCode:f,error:h}=await rt(o,c,{timeout:l}),g=[u,d].filter(Boolean).join(`
|
|
432
463
|
`).trim();return{out:h&&f!==0&&!u.trim()?(h+`
|
|
433
|
-
`+
|
|
464
|
+
`+g).trim():g,exitCode:f}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!s.autoConfirm){let c=n?"local":e.server;if(!await vt(`sysadmin [${e.action}] on ${c} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let c=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:l,exitCode:u}=await r(c,45e3);return l||`EXIT ${u}
|
|
434
465
|
(no output)`}case"disk_usage":{let c=e.path||"/",l=`df -h ${c}; echo '--- Top subdirs ---'; du -d1 -x -h ${c} 2>/dev/null | sort -rh | head -20`,{out:u,exitCode:d}=await r(l,3e4);return d!==0?`EXIT ${d}
|
|
435
466
|
${u}`:u}case"process_list":{let c=e.sort_by==="mem"?"4":"3",l=(e.limit||20)+1,u=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${l} || ps aux | awk 'NR==1{print; next} {print | "sort -k${c} -rn"}' | head -${l}`,{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
|
|
436
467
|
${d}`:d}case"network_status":{let c="ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null; echo '--- Active connections ---'; ss -tnp 2>/dev/null | head -30",{out:l,exitCode:u}=await r(c,15e3);return u!==0?`EXIT ${u}
|
|
437
|
-
${l}`:l}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:c}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),l=c.includes("dnf")?"dnf":c.includes("apt")?"apt":null;if(!l)return"ERROR: No supported package manager found (dnf/apt)";let u=(e.packages||[]).join(" "),d;switch(e.package_action){case"list":d=l==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let
|
|
468
|
+
${l}`:l}case"package":{if(!e.package_action)return"ERROR: package_action is required for action=package";let{out:c}=await r("which dnf 2>/dev/null && echo dnf || (which apt-get 2>/dev/null && echo apt) || echo unknown",1e4),l=c.includes("dnf")?"dnf":c.includes("apt")?"apt":null;if(!l)return"ERROR: No supported package manager found (dnf/apt)";let u=(e.packages||[]).join(" "),d;switch(e.package_action){case"list":d=l==="dnf"?"dnf list installed 2>/dev/null | head -60":"dpkg -l | head -60";break;case"check":{let g=l==="dnf"?'dnf check-update 2>/dev/null; EC=$?; [ $EC -eq 100 ] && echo "EXIT_STATUS: updates_available" || ([ $EC -eq 0 ] && echo "EXIT_STATUS: up_to_date" || echo "EXIT_STATUS: error $EC")':"apt-get -s upgrade 2>/dev/null | tail -5",{out:m}=await r(g,6e4);return m||"(no output from package check)"}case"install":if(!u)return"ERROR: packages required for install";d=l==="dnf"?`dnf install -y ${u}`:`apt-get install -y ${u}`;break;case"remove":if(!u)return"ERROR: packages required for remove";d=l==="dnf"?`dnf remove -y ${u}`:`apt-get remove -y ${u}`;break;case"update":if(!u)return"ERROR: packages required for update (use upgrade for full system upgrade)";d=l==="dnf"?`dnf update -y ${u}`:`apt-get install -y --only-upgrade ${u}`;break;case"upgrade":d=l==="dnf"?"dnf upgrade -y":"DEBIAN_FRONTEND=noninteractive apt-get upgrade -y";break;default:return`ERROR: Unknown package_action: ${e.package_action}`}let{out:f,exitCode:h}=await r(d,12e4);return h!==0?`EXIT ${h}
|
|
438
469
|
${f}`:f||`${e.package_action} OK`}case"user_manage":{if(!e.user_action)return"ERROR: user_action is required for action=user_manage";switch(e.user_action){case"list":{let c=`awk -F: '$3 >= 1000 && $1 != "nobody" {print $1, "uid="$3, "gid="$4, "shell="$7}' /etc/passwd`,{out:l,exitCode:u}=await r(c,1e4);return u!==0?`EXIT ${u}
|
|
439
470
|
${l}`:l||"(no regular users)"}case"info":{if(!e.user)return"ERROR: user is required for user_action=info";let c=`id ${e.user} && echo '--- Groups ---' && groups ${e.user} && echo '--- Last login ---' && lastlog -u ${e.user} 2>/dev/null`,{out:l,exitCode:u}=await r(c,1e4);return u!==0?`EXIT ${u}
|
|
440
471
|
${l}`:l}case"create":{if(!e.user)return"ERROR: user is required for user_action=create";let l=`useradd -m ${(e.groups||[]).map(f=>`-G ${f}`).join(" ")} ${e.user} && echo "User ${e.user} created"`,{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
|
|
@@ -472,8 +503,8 @@ ${u}`:u||"(empty log)"}case"find_large":{let c=e.path||"/",l=e.limit||20,u=e.min
|
|
|
472
503
|
${f}`:f||`(no files larger than ${u} in ${c})`}case"service":{if(!e.service_action)return"ERROR: service_action is required for action=service";if(e.service_action!=="list_failed"&&!e.service_name)return"ERROR: service_name is required (except for list_failed)";let c=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",l;switch(e.service_action){case"status":l=`systemctl status ${c} --no-pager -l 2>&1 | head -40`;break;case"list_failed":l="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":l=`systemctl start ${c} && systemctl status ${c} --no-pager -l 2>&1 | head -20`;break;case"stop":l=`systemctl stop ${c} && echo "${c} stopped"`;break;case"restart":l=`systemctl restart ${c} && systemctl status ${c} --no-pager -l 2>&1 | head -20`;break;case"reload":l=`systemctl reload ${c} 2>&1 || systemctl reload-or-restart ${c} 2>&1`;break;case"enable":l=`systemctl enable ${c} && echo "${c} enabled"`;break;case"disable":l=`systemctl disable ${c} && echo "${c} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:u,exitCode:d}=await r(l,3e4);return d===0||e.service_action==="status"&&d===3?u||`service ${e.service_action} OK`:`EXIT ${d}
|
|
473
504
|
${u}`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let c=e.signal||"SIGTERM",l;e.pid?l=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${c} ${e.pid} && echo "Sent ${c} to PID ${e.pid}"`:l=`pgrep -a "${e.process_name}" 2>/dev/null | head -5 && pkill -${c} "${e.process_name}" && echo "Sent ${c} to all '${e.process_name}' processes"`;let{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
|
|
474
505
|
${u}`:u}case"journalctl":{let c=e.lines||100,l=["journalctl","--no-pager","-n",String(c)];e.unit&&l.push("-u",e.unit.includes(".")?e.unit:`${e.unit}.service`),e.priority&&l.push("-p",e.priority),e.since&&l.push(`--since="${e.since}"`),l.push('2>/dev/null || echo "(journalctl not available)"');let{out:u,exitCode:d}=await r(l.join(" "),2e4);return d!==0?`EXIT ${d}
|
|
475
|
-
${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:n}=
|
|
476
|
-
`)}function
|
|
506
|
+
${u}`:u||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:n}=Js(),o=n(e.type,e.name,e.content,e.description);return o.ok?o.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${o.path}`:`ERROR: ${o.error}`}case"delete_memory":{let{deleteMemory:n}=Js();return n(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:n}=cr(),o=await n(t,e,s);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function q0(t,e,s={}){let{emit:n}=cr(),{logToolExecution:o}=Of(),r=Date.now(),i=s.silent?null:k0(t,e);if(!i){let c=await Df(t,e,s);return o({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:c}),c}let a=new x0(i);a.start();try{let c=await Df(t,e,s);return a.stop(),o({tool:t,args:e,result:c,duration:Date.now()-r,success:!c.startsWith?.("ERROR")}),await n("onToolResult",{tool:t,args:e,result:c}),c}catch(c){throw a.stop(),o({tool:t,args:e,result:c.message,duration:Date.now()-r,success:!1}),c}}Bf.exports={TOOL_DEFINITIONS:D0,executeTool:q0,resolvePath:it,autoFixPath:Nr,autoFixEdit:Ff,enrichBashError:qf,cancelPendingAskUser:P0,setAskUserHandler:I0,fileExists:pt}});var ts=re((bv,Uf)=>{Uf.exports=Wf()});var Ua=re((xv,Hf)=>{var{loadServerProfiles:so,resolveProfile:_v,sshExec:F0}=pa(),Wa={almalinux9:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all. Open port: firewall-cmd --permanent --add-port=PORT/tcp && firewall-cmd --reload.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent | audit2why. Fix context: restorecon -Rv /path.","Nginx config: /etc/nginx/. Test: nginx -t. Reload: systemctl reload nginx.","Process list: ps aux. Ports: ss -tuln.","Python: python3. Pip: pip3. Virtualenv: python3 -m venv."],almalinux8:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent."],ubuntu:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw. Status: ufw status. Allow port: ufw allow PORT/tcp.","SELinux NOT active by default (AppArmor instead). Check: aa-status."],debian:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw or iptables."],macos:["Package manager: Homebrew (brew). Install: brew install <pkg>. Update: brew update && brew upgrade.","Service manager: launchctl (NOT systemctl). Start: brew services start <name>. List: brew services list.",`No systemd. No journalctl. Use: log show --predicate 'process == "nginx"' --last 1h instead.`,"Firewall: macOS built-in (pfctl or System Settings). Check: pfctl -s rules.","Process list: ps aux. Ports: lsof -i -n -P | grep LISTEN."]};function B0(){let t=so();if(Object.keys(t).length===0)return null;let s=["## Remote Servers (.nex/servers.json)"];s.push(""),s.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[o,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,a=r.port&&Number(r.port)!==22?`:${r.port}`:"",c=r.os?` \u2014 OS: ${r.os}`:"",l=r.sudo?", sudo available":"";s.push(`- **${o}**: ${i}${a}${c}${l}`)}let n=new Set;for(let o of Object.values(t))o.os&&Wa[o.os]&&n.add(o.os);if(n.size>0){s.push("");for(let o of n){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;s.push(`### ${r} Notes`);for(let i of Wa[o])s.push(`- ${i}`)}}return s.join(`
|
|
507
|
+
`)}function W0(t){let e=so();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function U0(){return Object.keys(so())}function H0(){let t=require("fs"),s=require("path").join(process.cwd(),"NEX.md"),n="";try{n=t.readFileSync(s,"utf-8")}catch{}let o=so(),r=Object.keys(o);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],a=n.toLowerCase();if(!i.some(f=>a.includes(f)))return null;let l=r.map(f=>{let h=o[f],g=h.user?`${h.user}@${h.host}`:h.host,m=h.port&&Number(h.port)!==22?`:${h.port}`:"";return` - **${f}**: ${g}${m}${h.os?` (${h.os})`:""}`}).join(`
|
|
477
508
|
`),u=r.map(f=>o[f].log_path).filter(Boolean),d=u.length>0?`
|
|
478
509
|
- Server log paths: ${u.join(", ")}`:"";return`# Deployment Context (Auto-detected)
|
|
479
510
|
|
|
@@ -491,42 +522,44 @@ ${l}
|
|
|
491
522
|
- \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
|
|
492
523
|
- \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
|
|
493
524
|
|
|
494
|
-
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${
|
|
525
|
+
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${Y0(o)}`}function Y0(t){return Object.values(t).some(s=>s.host==="94.130.37.43")?`
|
|
495
526
|
|
|
496
|
-
##
|
|
527
|
+
## Server Debugging Rules
|
|
497
528
|
|
|
498
|
-
-
|
|
499
|
-
- ALWAYS use ssh_exec to investigate: ssh_exec on 94.130.37.43, check /home/
|
|
500
|
-
- NEVER run local bash/find/sqlite3 commands when debugging
|
|
501
|
-
- Local
|
|
502
|
-
- CRITICAL: When the user pastes a
|
|
503
|
-
- LOG FILES: Always check the CURRENT log first: /home/
|
|
529
|
+
- Server errors (set_reminder, cron, Google Auth, SmartThings) come from the DEPLOYED server at 94.130.37.43
|
|
530
|
+
- ALWAYS use ssh_exec to investigate: ssh_exec on 94.130.37.43, check /home/deploy/server-agent/logs/
|
|
531
|
+
- NEVER run local bash/find/sqlite3 commands when debugging server issues
|
|
532
|
+
- Local server-agent/ is just source code \u2014 the running system is on the server
|
|
533
|
+
- CRITICAL: When the user pastes a server error message (error logs), this is NEVER a "simple question" to answer from training knowledge. You MUST ssh_exec to verify if the error is still occurring BEFORE writing any explanation. Do NOT explain from memory \u2014 investigate first, always.
|
|
534
|
+
- LOG FILES: Always check the CURRENT log first: /home/deploy/server-agent/logs/api-error.log (no date suffix). Log files WITH a date suffix (e.g. api-error.log-20260322) are ROTATED/OLD \u2014 errors there may already be fixed. Only look at dated logs if the current log is empty or the error is absent from the current log.
|
|
504
535
|
- FIX WORKFLOW (YOLO): Once you identify a fixable bug via SSH investigation: (1) edit the file on server using ssh_exec with tee or sed -i (NOT sed -n), (2) restart the affected service with systemctl restart, (3) verify with tail logs. Do NOT produce a report \u2014 execute the fix.
|
|
505
|
-
- READING REMOTE FILES: NEVER use sed -n (always blocked). To read a specific function in a remote file: ssh_exec 'grep -n "functionName" /path/file -A 50'. To read the whole file: ssh_exec 'cat /path/file'. These are the only two options.`:""}async function
|
|
506
|
-
`+i.trim()}catch{return null}}
|
|
507
|
-
`).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function
|
|
508
|
-
`)}var
|
|
536
|
+
- READING REMOTE FILES: NEVER use sed -n (always blocked). To read a specific function in a remote file: ssh_exec 'grep -n "functionName" /path/file -A 50'. To read the whole file: ssh_exec 'cat /path/file'. These are the only two options.`:""}async function G0(t){if(typeof t!="string")return null;let e=[...t.matchAll(/https?:\/\/([a-zA-Z0-9._-]+)/g)];if(e.length===0)return null;let s=so();if(Object.keys(s).length===0)return null;let n=null,o=null;for(let[,i]of e){let a=i.toLowerCase().split(".");for(let[c,l]of Object.entries(s))if(a.includes(c.toLowerCase())){n=l,o=c;break}if(n)break;for(let[c,l]of Object.entries(s))if(l.host===i){n=l,o=c;break}if(n)break}if(!n||!o)return null;let r=["ss -tlnp 2>/dev/null | awk 'NR>1{print $4}' | grep -oE ':[0-9]+$' | sort -u | head -8","echo '---services---'","ps aux 2>/dev/null | grep -E '(node |python3 |gunicorn|uvicorn|ruby |java )' | grep -v grep | awk '{print $11, $12, $13}' | head -6","echo '---data---'","find /home -maxdepth 5 -name 'data' -type d 2>/dev/null | head -6"].join("; ");try{let{stdout:i}=await F0(n,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let a=n.user?`${n.user}@${n.host}`:n.host;return`[Server context for "${o}" (${a}) \u2014 probed at task start]
|
|
537
|
+
`+i.trim()}catch{return null}}Hf.exports={getServerContext:B0,getDeploymentContextBlock:H0,hasServerOS:W0,getProfileNames:U0,probeUrlServer:G0,OS_HINTS:Wa}});var zf=re((kv,Kf)=>{var St=require("fs").promises,Yf=require("fs"),nt=require("path"),Mr=require("util").promisify(require("child_process").exec),{C:ds}=He(),{getMergeConflicts:Gf}=sr(),{getServerContext:K0}=Ua(),z0=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function X0(t){try{return Yf.readFileSync(t,"utf-8").split(`
|
|
538
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function V0(t,e){for(let s of e)if(s===t||s.includes("*")&&new RegExp("^"+s.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function J0(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:n=[]}={}){let o=nt.join(t,".gitignore"),r=[...n,...X0(o)],i=0,a=[nt.basename(t)+"/"];function c(l,u,d){if(d>e||i>=s)return;let f;try{f=Yf.readdirSync(l,{withFileTypes:!0})}catch{return}f.sort((g,m)=>g.isDirectory()!==m.isDirectory()?g.isDirectory()?-1:1:g.name.localeCompare(m.name));let h=f.filter(g=>!(z0.has(g.name)||g.name.startsWith(".")&&g.name!==".env.example"||V0(g.name,r)));for(let g=0;g<h.length;g++){if(i>=s){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let m=h[g],b=g===h.length-1,x=b?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",j=u+(b?" ":"\u2502 "),G=m.isDirectory()?m.name+"/":m.name;a.push(`${u}${x}${G}`),i++,m.isDirectory()&&c(nt.join(l,m.name),j,d+1)}}return c(t,"",1),a.join(`
|
|
539
|
+
`)}var Ha=new Map,fs=new Map,Lr=null,Z0=3e4;async function tn(t){try{return await t()}catch{return null}}async function Q0(){if(!Lr||Date.now()>Lr)return!1;let t=[nt.join(process.cwd(),"package.json"),nt.join(process.cwd(),"README.md"),nt.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await St.stat(e),n=fs.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(fs.has(e))return!1}try{let e=nt.join(process.cwd(),".git","HEAD"),s=await St.stat(e),n=fs.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function eb(){let t=[nt.join(process.cwd(),"package.json"),nt.join(process.cwd(),"README.md"),nt.join(process.cwd(),".gitignore"),nt.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await St.stat(e);fs.set(e,s.mtimeMs)}catch{fs.delete(e)}}async function tb(t){let e="fileContext",s=Ha.get(e),n=!1;if(s&&await Q0()&&(n=!0),!n){let l=[],u=nt.join(t,"package.json");if(await tn(()=>St.access(u).then(()=>!0).catch(()=>!1)))try{let b=await St.readFile(u,"utf-8"),x=JSON.parse(b),j={name:x.name,version:x.version};x.scripts&&(j.scripts=Object.keys(x.scripts).slice(0,15)),x.dependencies&&(j.deps=Object.keys(x.dependencies).length),x.devDependencies&&(j.devDeps=Object.keys(x.devDependencies).length),l.push(`PACKAGE: ${JSON.stringify(j)}`)}catch{}let f=nt.join(t,"README.md");if(await tn(()=>St.access(f).then(()=>!0).catch(()=>!1))){let x=(await St.readFile(f,"utf-8")).split(`
|
|
509
540
|
`).slice(0,50);l.push(`README (first 50 lines):
|
|
510
|
-
${
|
|
511
|
-
`)}`)}let
|
|
541
|
+
${x.join(`
|
|
542
|
+
`)}`)}let g=nt.join(t,".gitignore");if(await tn(()=>St.access(g).then(()=>!0).catch(()=>!1))){let b=await St.readFile(g,"utf-8");l.push(`GITIGNORE:
|
|
512
543
|
${b.trim()}`)}s=l.join(`
|
|
513
544
|
|
|
514
|
-
`),
|
|
545
|
+
`),Ha.set(e,s),Lr=Date.now()+Z0,await eb()}let o=[s],[r,i,a,c]=await Promise.all([tn(async()=>{let{stdout:l}=await Mr("git branch --show-current",{cwd:t,timeout:5e3});return l.trim()}),tn(async()=>{let{stdout:l}=await Mr("git status --short",{cwd:t,timeout:5e3});return l.trim()}),tn(async()=>{let{stdout:l}=await Mr("git log --oneline -5",{cwd:t,timeout:5e3});return l.trim()}),Gf()]);if(r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
|
|
515
546
|
${i}`),a&&o.push(`RECENT COMMITS:
|
|
516
547
|
${a}`),c&&c.length>0){let l=c.map(u=>` ${u.file}`).join(`
|
|
517
548
|
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
518
|
-
${l}`)}try{let l=
|
|
549
|
+
${l}`)}try{let l=K0();l&&o.push(l)}catch{}return o.join(`
|
|
519
550
|
|
|
520
|
-
`)}async function F0(t){let e=tt.join(t,"package.json"),s="";if(await Qt(()=>vt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await vt.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([Qt(async()=>{let{stdout:i}=await Ar("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Nf()]);if(r&&r.length>0){console.log(`${as.red} \u26A0 ${r.length} unresolved merge conflict(s):${as.reset}`);for(let i of r)console.log(`${as.red} ${i.file}${as.reset}`);console.log(`${as.yellow} \u2192 Resolve conflicts before starting tasks${as.reset}`)}console.log()}Mf.exports={gatherProjectContext:q0,printContext:F0,generateFileTree:P0,_clearContextCache:()=>{Pa.clear(),cs.clear(),Or=null}}});var Mr=se((sv,jf)=>{var St=require("fs"),Nr=require("path"),{atomicWrite:B0}=fn();function no(){return Nr.join(process.cwd(),".nex","sessions")}function Ia(){let t=no();St.existsSync(t)||St.mkdirSync(t,{recursive:!0})}function ja(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Nr.join(no(),`${e}.json`)}function Da(t,e,s={}){Ia();let n=ja(t),o={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return B0(n,JSON.stringify(o,null,2)),{path:n,name:t}}function Pf(t){let e=ja(t);if(!St.existsSync(e))return null;try{return JSON.parse(St.readFileSync(e,"utf-8"))}catch{return null}}function If(){Ia();let t=no(),e=St.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(St.readFileSync(Nr.join(t,n),"utf-8"));s.push({name:o.name||n.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider,score:o.score!=null?o.score:null,scoreGrade:o.scoreGrade||null})}catch{}return s.sort((n,o)=>(o.updatedAt||"").localeCompare(n.updatedAt||""))}function W0(t){let e=ja(t);return St.existsSync(e)?(St.unlinkSync(e),!0):!1}function U0(){let t=If();return t.length===0?null:Pf(t[0].name)}var xn=null,Yt=null,to=null;function H0(t,e={}){t.length!==0&&(xn&&clearTimeout(xn),Yt=t,to=e||{},xn=setTimeout(()=>{Yt&&Yt.length>0&&Da("_autosave",Yt,to),xn=null,Yt=null,to=null},5e3))}function G0(){xn&&(clearTimeout(xn),xn=null),Yt&&Yt.length>0&&(Da("_autosave",Yt,to),Yt=null,to=null)}function Y0(){Ia();let t=no(),e=St.readdirSync(t).filter(r=>r.endsWith(".json")),s=new Date,n=new Date(s.getTime()-720*60*60*1e3),o=0;for(let r of e){let i=Nr.join(t,r);try{let a=St.statSync(i);new Date(a.mtime)<n&&(St.unlinkSync(i),o++)}catch{}}return o}jf.exports={saveSession:Da,loadSession:Pf,listSessions:If,deleteSession:W0,getLastSession:U0,autoSave:H0,flushAutoSave:G0,clearOldSessions:Y0,_getSessionsDir:no}});var Lr=se((ov,Gf)=>{"use strict";var so=require("fs"),Df=require("path");function qf(t){let e=[];return t.forEach((s,n)=>{s.role==="assistant"&&(Array.isArray(s.content)&&s.content.forEach(o=>{o&&o.type==="tool_use"&&e.push({name:o.name||"",input:o.input||{},index:n,id:o.id||null})}),Array.isArray(s.tool_calls)&&s.tool_calls.forEach(o=>{let r=o.function?.name||o.name||"",i={};try{i=typeof o.function?.arguments=="string"?JSON.parse(o.function.arguments):o.function?.arguments||o.input||{}}catch{}e.push({name:r,input:i,index:n,id:o.id||null})}))}),e}function K0(t){let e=new Set;return t.forEach(s=>{s.role==="tool"&&typeof s.content=="string"&&s.content.startsWith("BLOCKED:")&&s.tool_call_id&&e.add(s.tool_call_id),s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(n=>{n&&n.type==="tool_result"&&n.tool_use_id&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&e.add(n.tool_use_id)})}),e}function Ff(t){let e=[];return t.forEach((s,n)=>{if(s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(o=>{if(o&&o.type==="tool_result"){let r=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(o.content||"");e.push({content:r,index:n})}}),s.role==="tool"){let o=typeof s.content=="string"?s.content:JSON.stringify(s.content||"");e.push({content:o,index:n})}}),e}function Bf(t){for(let e=t.length-1;e>=0;e--){let s=t[e];if(s.role==="assistant"){if(typeof s.content=="string")return s.content.trim();if(Array.isArray(s.content)){let n=s.content.filter(o=>o&&(o.type==="text"||typeof o=="string")).map(o=>typeof o=="string"?o:o.text||"").join("").trim();if(n)return n}}}return""}function Wf(t,e){let s=[];for(let n=t.length-1;n>=0&&s.length<e;n--){let o=t[n];if(o.role!=="assistant")continue;let r="";typeof o.content=="string"?r=o.content.trim():Array.isArray(o.content)&&(r=o.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&s.push(r)}return s}function Uf(t){let e=new Map;for(let s of t){let n;try{n=JSON.stringify(s.input)}catch{n=String(s.input)}let o=`${s.name}|${n}`;e.set(o,(e.get(o)||0)+1)}return e}function Hf(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,s=[],n=qf(t),o=Ff(t),r=n.length,i=K0(t),a=n.filter(w=>!w.id||!i.has(w.id));t.some(w=>w.role==="user"&&typeof w.content=="string"&&w.content.startsWith("[SYSTEM WARNING]")&&(w.content.includes("edited")||w.content.includes("bash command")||w.content.includes("grep pattern")||w.content.includes("re-read")||w.content.includes("already in your context")))&&(e-=2,s.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let l=n.find(w=>{let P=w.input?.command||w.input?.cmd||"";return/\bsed\s+-n\b/.test(P)});if(l){let w=(l.input?.command||l.input?.cmd||"").slice(0,80);o.some(k=>k.content.includes("BLOCKED: sed -n is forbidden")||k.content.includes("BLOCKED: sed -n"))?(e-=.25,s.push(`sed -n attempted but blocked by agent guard: ${w}`)):(e-=1.5,s.push(`sed -n anti-pattern used: ${w}`))}n.find(w=>{if(w.name!=="grep"&&w.name!=="bash"&&w.name!=="ssh_exec")return!1;let P=w.input?.command||w.input?.cmd||"",k=w.input?.pattern||"",N=`${P} ${k}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(N)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(N)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some(w=>w.role==="assistant"),f=Bf(t),m=Wf(t,3).some(w=>w.length>100&&!/^[^.!]{0,40}\?$/.test(w));if(d&&!m&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let w=f.length>0?`"${f.slice(0,60)}..."`:"(no assistant text found)";s.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${w}`)}r>40?(e-=1.5,s.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,s.push(`High tool call count: ${r} (>25 threshold)`)),t.some(w=>{let P=typeof w.content=="string"?w.content:Array.isArray(w.content)?w.content.map(k=>typeof k=="string"?k:k.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(P)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let v=Uf(a),O=0,U="";for(let[w,P]of v)P>O&&(O=P,U=w);if(O>=3){let[w]=U.split("|");e-=1,s.push(`Same tool call repeated ${O}\xD7 (tool: ${w})`)}let L=!1,R=t.findIndex(w=>w.role==="user"&&typeof w.content=="string"&&w.content.includes("[SYSTEM STOP]")&&w.content.includes('"valid":true'));R>=0&&n.filter(P=>P.index>R).length>0&&(L=!0),L&&(e-=1.5,s.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let C=n.filter(w=>w.name==="ssh_exec");if(C.length>=8){let w=0,P=1;for(let k=1;k<C.length;k++)C[k].index<=C[k-1].index+2?P++:(w=Math.max(w,P),P=1);w=Math.max(w,P),w>=8&&(e-=.5,s.push(`SSH reconnect storm: ${w} consecutive SSH calls`))}d&&C.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(f)&&(e-=2,s.push("Surrender: model asked user to manually provide server output instead of gathering it"));let K=new Map;for(let w of a)if(w.name==="read_file"&&w.input?.path){let P=w.input.path;K.has(P)||K.set(P,{count:0,ranges:[]});let k=K.get(P);if(k.count++,w.input.line_start!=null){let N=w.input.line_start||1,T=w.input.line_end||N+350;k.ranges.push([N,T])}}function Q(w,P,k){for(let[N,T]of k){let S=Math.max(w,N),J=Math.min(P,T);if(J>S){let Re=J-S,Ce=P-w||1;if(Re/Ce>=.7)return!0}}return!1}let re=0,V="";for(let[w,P]of K){if(P.count<3)continue;if(P.ranges.length===P.count){let T=!1,S=[];for(let[J,Re]of P.ranges){if(S.length>0&&Q(J,Re,S)){T=!0;break}S.push([J,Re])}if(!T)continue}if(P.count-P.ranges.length<=2&&P.ranges.length>=1){let T=!1,S=[];for(let[J,Re]of P.ranges){if(S.length>0&&Q(J,Re,S)){T=!0;break}S.push([J,Re])}if(!T)continue}P.count>re&&(re=P.count,V=w)}if(re>=3){e-=1;let w=V.split("/").slice(-2).join("/");s.push(`read_file loop: "${w}" read ${re}\xD7 (file already in context)`)}let H=0,_="";for(let[w,P]of K){if(P.ranges.length<4)continue;let k=[],N=!1;for(let[T,S]of P.ranges){if(k.length>0&&Q(T,S,k)){N=!0;break}k.push([T,S])}!N&&P.ranges.length>H&&(H=P.ranges.length,_=w)}if(H>=4){e-=.5;let w=_.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${w}" read in ${H} sequential sections \u2014 use grep instead`)}let he=new Map;for(let w of a)if(w.name==="grep"&&w.input?.path&&w.input?.pattern){let P=w.input.path;he.has(P)||he.set(P,new Set),he.get(P).add(w.input.pattern)}let de=0,me="";for(let[w,P]of he)w.split("/").pop().includes(".")&&P.size>de&&(de=P.size,me=w);if(de>=3){e-=.75;let w=me.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${w}" searched ${de}\xD7 with different patterns (file already in context)`)}{let w=new Set,P=new Set,k=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let T of n){if(T.name==="write_file"&&T.input?.path){let S=T.input.path.split("/").pop(),J=T.input.path.includes("/tests/");k.test(S)&&!J&&w.add(T.input.path)}if((T.name==="bash"||T.name==="ssh_exec")&&T.input?.command){let S=T.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(S)for(let J of S){let Re=J.split(/\s+/),Ce=Re[Re.length-1];for(let ye of w)(ye.endsWith(Ce)||Ce.endsWith(ye.split("/").pop()))&&P.add(ye)}}}let N=P.size;if(N>=1){let T=Math.min(N*.25,.5);e-=T;let S=[...P].map(J=>J.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${S} \u2014 write inline logic or use tests/ instead`)}}let ge=o.filter(w=>w.content.startsWith("EXIT")).length;ge>=10?(e-=1,s.push(`Bash exit-error storm: ${ge} tool results started with EXIT (repeated failing commands)`)):ge>=5&&(e-=.5,s.push(`Repeated bash errors: ${ge} tool results with non-zero exit code`));for(let w of t){if(w.role!=="assistant")continue;let P="";if(typeof w.content=="string"?P=w.content:Array.isArray(w.content)&&(P=w.content.filter(Ce=>Ce&&(Ce.type==="text"||typeof Ce=="string")).map(Ce=>typeof Ce=="string"?Ce:Ce.text||"").join("")),P.length<=5e3)continue;let k=P.split(/(?<=\. )/).filter(Ce=>Ce.trim().length>0);if(k.length<6)continue;let N=new Map;for(let Ce=0;Ce<=k.length-3;Ce++){let ye=k.slice(Ce,Ce+3).join("").trim();ye.length>30&&N.set(ye,(N.get(ye)||0)+1)}let T=0,S="";for(let[Ce,ye]of N)ye>T&&(T=ye,S=Ce);if(T<3)continue;let Re=S.length*T/P.length;if(Re>=.4||T>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${T}\xD7 same paragraph, ${Math.round(Re*100)}% repeated)`);break}}{let w=new Set(["read_file","list_directory","search_files","glob","grep"]),P=t.some(N=>Array.isArray(N.tool_calls)?N.tool_calls.some(T=>w.has(T.function?.name)):Array.isArray(N.content)?N.content.some(T=>T.type==="tool_use"&&w.has(T.name)):!1);t.some(N=>N.role==="assistant"&&typeof N.content=="string"&&(N.content.includes("## Steps")||N.content.includes("/plan approve")))&&!P&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let we=o.filter(w=>w.content.startsWith("BLOCKED:")&&!w.content.includes("BLOCKED: sed -n")&&!w.content.includes("SSH paused")&&!w.content.includes("SSH temporarily paused"));if(we.length>0){let w=Math.min(we.length*.5,1.5);e-=w,s.push(`${we.length} tool call${we.length===1?"":"s"} blocked (agent attempted denied actions)`)}let Se=t.filter(w=>{let P=typeof w.content=="string"?w.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(P)}).length;if(Se>0){let w=Math.min(Se*1,2);e-=w,s.push(`Super-nuclear context wipe fired ${Se}\xD7 (context collapse \u2014 task too large or read loops)`)}{let w=!1,P=!1,k=!1;for(let T of n){if(T.name!=="bash")continue;let S=(T.input?.command||T.input?.cmd||"").trim();!(/cat\s*>/.test(S)||/<</.test(S))&&/\bcat\s+\S/.test(S)&&(w=!0),/^\s*ls(\s|$)/.test(S)&&!/npm|yarn|pnpm|make|git\b/.test(S)&&(P=!0),/\bfind\s+\S/.test(S)&&!/git\b|npm\b|-exec\b/.test(S)&&(k=!0)}let N=[w,P,k].filter(Boolean).length;if(N>0){let T=Math.min(N*.25,.75);e-=T;let S=[];w&&S.push("cat (use read_file)"),P&&S.push("ls (use list_directory)"),k&&S.push("find (use glob)"),s.push(`bash used instead of dedicated tool: ${S.join(", ")}`)}}{let w=n.some(S=>(S.name==="write_file"||S.name==="Write")&&S.input?.path&&(S.input.path.endsWith("requirements.txt")||S.input.path.endsWith("Pipfile")||S.input.path.endsWith("pyproject.toml"))),P=n.some(S=>(S.name==="write_file"||S.name==="Write")&&S.input?.path&&S.input.path.endsWith("package.json")),k=n.filter(S=>(S.name==="bash"||S.name==="Bash")&&S.input?.command).map(S=>S.input.command),N=k.some(S=>/pip\s+install|python\s+-m\s+venv/.test(S)),T=k.some(S=>/npm\s+install/.test(S));w&&!N?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):P&&!T&&n.some(J=>(J.name==="write_file"||J.name==="Write")&&J.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(J.input.path))&&(e-=.75,s.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let w=t.find(S=>S.role==="assistant"),P="";w&&(typeof w.content=="string"?P=w.content:Array.isArray(w.content)&&(P=w.content.filter(S=>S&&(S.type==="text"||typeof S=="string")).map(S=>typeof S=="string"?S:S.text||"").join("")));let k=P.slice(0,400),N=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,T=k.split(`
|
|
521
|
-
`).find(
|
|
522
|
-
`)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${
|
|
523
|
-
`).filter(
|
|
551
|
+
`)}async function nb(t){let e=nt.join(t,"package.json"),s="";if(await tn(()=>St.access(e).then(()=>!0).catch(()=>!1)))try{let i=await St.readFile(e,"utf-8"),a=JSON.parse(i);s=`${a.name||"?"} v${a.version||"?"}`}catch{}let[o,r]=await Promise.all([tn(async()=>{let{stdout:i}=await Mr("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Gf()]);if(r&&r.length>0){console.log(`${ds.red} \u26A0 ${r.length} unresolved merge conflict(s):${ds.reset}`);for(let i of r)console.log(`${ds.red} ${i.file}${ds.reset}`);console.log(`${ds.yellow} \u2192 Resolve conflicts before starting tasks${ds.reset}`)}console.log()}Kf.exports={gatherProjectContext:tb,printContext:nb,generateFileTree:J0,_clearContextCache:()=>{Ha.clear(),fs.clear(),Lr=null}}});var Ir=re((vv,Jf)=>{var Et=require("fs"),Pr=require("path"),{atomicWrite:sb}=mn();function ro(){return Pr.join(process.cwd(),".nex","sessions")}function Ya(){let t=ro();Et.existsSync(t)||Et.mkdirSync(t,{recursive:!0})}function Ga(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Pr.join(ro(),`${e}.json`)}function Ka(t,e,s={}){Ya();let n=Ga(t),o={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return sb(n,JSON.stringify(o,null,2)),{path:n,name:t}}function Xf(t){let e=Ga(t);if(!Et.existsSync(e))return null;try{return JSON.parse(Et.readFileSync(e,"utf-8"))}catch{return null}}function Vf(){Ya();let t=ro(),e=Et.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Et.readFileSync(Pr.join(t,n),"utf-8"));s.push({name:o.name||n.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider,score:o.score!=null?o.score:null,scoreGrade:o.scoreGrade||null})}catch{}return s.sort((n,o)=>(o.updatedAt||"").localeCompare(n.updatedAt||""))}function ob(t){let e=Ga(t);return Et.existsSync(e)?(Et.unlinkSync(e),!0):!1}function rb(){let t=Vf();return t.length===0?null:Xf(t[0].name)}var En=null,Kt=null,oo=null;function ib(t,e={}){t.length!==0&&(En&&clearTimeout(En),Kt=t,oo=e||{},En=setTimeout(()=>{Kt&&Kt.length>0&&Ka("_autosave",Kt,oo),En=null,Kt=null,oo=null},5e3))}function ab(){En&&(clearTimeout(En),En=null),Kt&&Kt.length>0&&(Ka("_autosave",Kt,oo),Kt=null,oo=null)}function cb(){Ya();let t=ro(),e=Et.readdirSync(t).filter(r=>r.endsWith(".json")),s=new Date,n=new Date(s.getTime()-720*60*60*1e3),o=0;for(let r of e){let i=Pr.join(t,r);try{let a=Et.statSync(i);new Date(a.mtime)<n&&(Et.unlinkSync(i),o++)}catch{}}return o}Jf.exports={saveSession:Ka,loadSession:Xf,listSessions:Vf,deleteSession:ob,getLastSession:rb,autoSave:ib,flushAutoSave:ab,clearOldSessions:cb,_getSessionsDir:ro}});var jr=re((Sv,rp)=>{"use strict";var io=require("fs"),Zf=require("path");function Qf(t){let e=[];return t.forEach((s,n)=>{s.role==="assistant"&&(Array.isArray(s.content)&&s.content.forEach(o=>{o&&o.type==="tool_use"&&e.push({name:o.name||"",input:o.input||{},index:n,id:o.id||null})}),Array.isArray(s.tool_calls)&&s.tool_calls.forEach(o=>{let r=o.function?.name||o.name||"",i={};try{i=typeof o.function?.arguments=="string"?JSON.parse(o.function.arguments):o.function?.arguments||o.input||{}}catch{}e.push({name:r,input:i,index:n,id:o.id||null})}))}),e}function lb(t){let e=new Set;return t.forEach(s=>{s.role==="tool"&&typeof s.content=="string"&&s.content.startsWith("BLOCKED:")&&s.tool_call_id&&e.add(s.tool_call_id),s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(n=>{n&&n.type==="tool_result"&&n.tool_use_id&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&e.add(n.tool_use_id)})}),e}function ep(t){let e=[];return t.forEach((s,n)=>{if(s.role==="user"&&Array.isArray(s.content)&&s.content.forEach(o=>{if(o&&o.type==="tool_result"){let r=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(o.content||"");e.push({content:r,index:n})}}),s.role==="tool"){let o=typeof s.content=="string"?s.content:JSON.stringify(s.content||"");e.push({content:o,index:n})}}),e}function tp(t){for(let e=t.length-1;e>=0;e--){let s=t[e];if(s.role==="assistant"){if(typeof s.content=="string")return s.content.trim();if(Array.isArray(s.content)){let n=s.content.filter(o=>o&&(o.type==="text"||typeof o=="string")).map(o=>typeof o=="string"?o:o.text||"").join("").trim();if(n)return n}}}return""}function np(t,e){let s=[];for(let n=t.length-1;n>=0&&s.length<e;n--){let o=t[n];if(o.role!=="assistant")continue;let r="";typeof o.content=="string"?r=o.content.trim():Array.isArray(o.content)&&(r=o.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&s.push(r)}return s}function sp(t){let e=new Map;for(let s of t){let n;try{n=JSON.stringify(s.input)}catch{n=String(s.input)}let o=`${s.name}|${n}`;e.set(o,(e.get(o)||0)+1)}return e}function op(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,s=[],n=Qf(t),o=ep(t),r=n.length,i=lb(t),a=n.filter(w=>!w.id||!i.has(w.id));t.some(w=>w.role==="user"&&typeof w.content=="string"&&w.content.startsWith("[SYSTEM WARNING]")&&(w.content.includes("edited")||w.content.includes("bash command")||w.content.includes("grep pattern")||w.content.includes("re-read")||w.content.includes("already in your context")))&&(e-=2,s.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let l=n.find(w=>{let I=w.input?.command||w.input?.cmd||"";return/\bsed\s+-n\b/.test(I)});if(l){let w=(l.input?.command||l.input?.cmd||"").slice(0,80);o.some(v=>v.content.includes("BLOCKED: sed -n is forbidden")||v.content.includes("BLOCKED: sed -n"))?(e-=.25,s.push(`sed -n attempted but blocked by agent guard: ${w}`)):(e-=1.5,s.push(`sed -n anti-pattern used: ${w}`))}n.find(w=>{if(w.name!=="grep"&&w.name!=="bash"&&w.name!=="ssh_exec")return!1;let I=w.input?.command||w.input?.cmd||"",v=w.input?.pattern||"",O=`${I} ${v}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(O)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(O)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some(w=>w.role==="assistant"),f=tp(t),g=np(t,3).some(w=>w.length>100&&!/^[^.!]{0,40}\?$/.test(w));if(d&&!g&&(f.length<80||/^[^.!]{0,40}\?$/.test(f))){e-=2;let w=f.length>0?`"${f.slice(0,60)}..."`:"(no assistant text found)";s.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${w}`)}r>40?(e-=1.5,s.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,s.push(`High tool call count: ${r} (>25 threshold)`)),t.some(w=>{let I=typeof w.content=="string"?w.content:Array.isArray(w.content)?w.content.map(v=>typeof v=="string"?v:v.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(I)})&&(e-=.5,s.push("Auto-compress triggered (context flood indicator)"));let x=sp(a),j=0,G="";for(let[w,I]of x)I>j&&(j=I,G=w);if(j>=3){let[w]=G.split("|");e-=1,s.push(`Same tool call repeated ${j}\xD7 (tool: ${w})`)}let L=!1,P=t.findIndex(w=>w.role==="user"&&typeof w.content=="string"&&w.content.includes("[SYSTEM STOP]")&&w.content.includes('"valid":true'));P>=0&&n.filter(I=>I.index>P).length>0&&(L=!0),L&&(e-=1.5,s.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let C=n.filter(w=>w.name==="ssh_exec");if(C.length>=8){let w=0,I=1;for(let v=1;v<C.length;v++)C[v].index<=C[v-1].index+2?I++:(w=Math.max(w,I),I=1);w=Math.max(w,I),w>=8&&(e-=.5,s.push(`SSH reconnect storm: ${w} consecutive SSH calls`))}d&&C.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(f)&&(e-=2,s.push("Surrender: model asked user to manually provide server output instead of gathering it"));let Z=new Map;for(let w of a)if(w.name==="read_file"&&w.input?.path){let I=w.input.path;Z.has(I)||Z.set(I,{count:0,ranges:[]});let v=Z.get(I);if(v.count++,w.input.line_start!=null){let O=w.input.line_start||1,R=w.input.line_end||O+350;v.ranges.push([O,R])}}function Y(w,I,v){for(let[O,R]of v){let k=Math.max(w,O),H=Math.min(I,R);if(H>k){let Se=H-k,xe=I-w||1;if(Se/xe>=.7)return!0}}return!1}let ue=0,ie="";for(let[w,I]of Z){if(I.count<3)continue;if(I.ranges.length===I.count){let R=!1,k=[];for(let[H,Se]of I.ranges){if(k.length>0&&Y(H,Se,k)){R=!0;break}k.push([H,Se])}if(!R)continue}if(I.count-I.ranges.length<=2&&I.ranges.length>=1){let R=!1,k=[];for(let[H,Se]of I.ranges){if(k.length>0&&Y(H,Se,k)){R=!0;break}k.push([H,Se])}if(!R)continue}I.count>ue&&(ue=I.count,ie=w)}if(ue>=3){e-=1;let w=ie.split("/").slice(-2).join("/");s.push(`read_file loop: "${w}" read ${ue}\xD7 (file already in context)`)}let se=0,T="";for(let[w,I]of Z){if(I.ranges.length<4)continue;let v=[],O=!1;for(let[R,k]of I.ranges){if(v.length>0&&Y(R,k,v)){O=!0;break}v.push([R,k])}!O&&I.ranges.length>se&&(se=I.ranges.length,T=w)}if(se>=4){e-=.5;let w=T.split("/").slice(-2).join("/");s.push(`File-scroll pattern: "${w}" read in ${se} sequential sections \u2014 use grep instead`)}let Te=new Map;for(let w of a)if(w.name==="grep"&&w.input?.path&&w.input?.pattern){let I=w.input.path;Te.has(I)||Te.set(I,new Set),Te.get(I).add(w.input.pattern)}let K=0,X="";for(let[w,I]of Te)w.split("/").pop().includes(".")&&I.size>K&&(K=I.size,X=w);if(K>=3){e-=.75;let w=X.split("/").slice(-2).join("/");s.push(`grep flood on single file: "${w}" searched ${K}\xD7 with different patterns (file already in context)`)}{let w=new Set,I=new Set,v=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let R of n){if(R.name==="write_file"&&R.input?.path){let k=R.input.path.split("/").pop(),H=R.input.path.includes("/tests/");v.test(k)&&!H&&w.add(R.input.path)}if((R.name==="bash"||R.name==="ssh_exec")&&R.input?.command){let k=R.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(k)for(let H of k){let Se=H.split(/\s+/),xe=Se[Se.length-1];for(let ge of w)(ge.endsWith(xe)||xe.endsWith(ge.split("/").pop()))&&I.add(ge)}}}let O=I.size;if(O>=1){let R=Math.min(O*.25,.5);e-=R;let k=[...I].map(H=>H.split("/").pop()).join(", ");s.push(`Temp file write-then-delete: ${k} \u2014 write inline logic or use tests/ instead`)}}let me=o.filter(w=>w.content.startsWith("EXIT")).length;me>=10?(e-=1,s.push(`Bash exit-error storm: ${me} tool results started with EXIT (repeated failing commands)`)):me>=5&&(e-=.5,s.push(`Repeated bash errors: ${me} tool results with non-zero exit code`));for(let w of t){if(w.role!=="assistant")continue;let I="";if(typeof w.content=="string"?I=w.content:Array.isArray(w.content)&&(I=w.content.filter(xe=>xe&&(xe.type==="text"||typeof xe=="string")).map(xe=>typeof xe=="string"?xe:xe.text||"").join("")),I.length<=5e3)continue;let v=I.split(/(?<=\. )/).filter(xe=>xe.trim().length>0);if(v.length<6)continue;let O=new Map;for(let xe=0;xe<=v.length-3;xe++){let ge=v.slice(xe,xe+3).join("").trim();ge.length>30&&O.set(ge,(O.get(ge)||0)+1)}let R=0,k="";for(let[xe,ge]of O)ge>R&&(R=ge,k=xe);if(R<3)continue;let Se=k.length*R/I.length;if(Se>=.4||R>=10){e-=1.5,s.push(`llm output loop: assistant message repeated content detected (${R}\xD7 same paragraph, ${Math.round(Se*100)}% repeated)`);break}}{let w=new Set(["read_file","list_directory","search_files","glob","grep"]),I=t.some(O=>Array.isArray(O.tool_calls)?O.tool_calls.some(R=>w.has(R.function?.name)):Array.isArray(O.content)?O.content.some(R=>R.type==="tool_use"&&w.has(R.name)):!1);t.some(O=>O.role==="assistant"&&typeof O.content=="string"&&(O.content.includes("## Steps")||O.content.includes("/plan approve")))&&!I&&(e-=2,s.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let fe=o.filter(w=>w.content.startsWith("BLOCKED:")&&!w.content.includes("BLOCKED: sed -n")&&!w.content.includes("SSH paused")&&!w.content.includes("SSH temporarily paused"));if(fe.length>0){let w=Math.min(fe.length*.5,1.5);e-=w,s.push(`${fe.length} tool call${fe.length===1?"":"s"} blocked (agent attempted denied actions)`)}let $e=t.filter(w=>{let I=typeof w.content=="string"?w.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(I)}).length;if($e>0){let w=Math.min($e*1,2);e-=w,s.push(`Super-nuclear context wipe fired ${$e}\xD7 (context collapse \u2014 task too large or read loops)`)}{let w=!1,I=!1,v=!1;for(let R of n){if(R.name!=="bash")continue;let k=(R.input?.command||R.input?.cmd||"").trim();!(/cat\s*>/.test(k)||/<</.test(k))&&/\bcat\s+\S/.test(k)&&(w=!0),/^\s*ls(\s|$)/.test(k)&&!/npm|yarn|pnpm|make|git\b/.test(k)&&(I=!0),/\bfind\s+\S/.test(k)&&!/git\b|npm\b|-exec\b/.test(k)&&(v=!0)}let O=[w,I,v].filter(Boolean).length;if(O>0){let R=Math.min(O*.25,.75);e-=R;let k=[];w&&k.push("cat (use read_file)"),I&&k.push("ls (use list_directory)"),v&&k.push("find (use glob)"),s.push(`bash used instead of dedicated tool: ${k.join(", ")}`)}}{let w=n.some(k=>(k.name==="write_file"||k.name==="Write")&&k.input?.path&&(k.input.path.endsWith("requirements.txt")||k.input.path.endsWith("Pipfile")||k.input.path.endsWith("pyproject.toml"))),I=n.some(k=>(k.name==="write_file"||k.name==="Write")&&k.input?.path&&k.input.path.endsWith("package.json")),v=n.filter(k=>(k.name==="bash"||k.name==="Bash")&&k.input?.command).map(k=>k.input.command),O=v.some(k=>/pip\s+install|python\s+-m\s+venv/.test(k)),R=v.some(k=>/npm\s+install/.test(k));w&&!O?(e-=1,s.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):I&&!R&&n.some(H=>(H.name==="write_file"||H.name==="Write")&&H.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(H.input.path))&&(e-=.75,s.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(d){let w=t.find(k=>k.role==="assistant"),I="";w&&(typeof w.content=="string"?I=w.content:Array.isArray(w.content)&&(I=w.content.filter(k=>k&&(k.type==="text"||typeof k=="string")).map(k=>typeof k=="string"?k:k.text||"").join("")));let v=I.slice(0,400),O=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,R=v.split(`
|
|
552
|
+
`).find(k=>{let H=k.trim();return H.length>0&&H.length<=30&&/^\d/.test(H)&&/=/.test(H)&&!/[a-zA-Z]/.test(H)});if(O.test(v)||R){e-=1.5;let k=(R||v.split(`
|
|
553
|
+
`)[0]).trim().slice(0,40);s.push(`Thinking-chain leak: non-sequitur artifact at response start: "${k}"`)}}if(d&&r>0){let w=t.findIndex(v=>v.role==="assistant"),I=t.findIndex(v=>!!(Array.isArray(v.tool_calls)&&v.tool_calls.length>0||Array.isArray(v.content)&&v.content.some(O=>O&&O.type==="tool_use")));if(w!==-1&&I!==-1&&w<I){let v=t[w],O="";typeof v.content=="string"?O=v.content:Array.isArray(v.content)&&(O=v.content.filter(H=>H&&(H.type==="text"||typeof H=="string")).map(H=>typeof H=="string"?H:H.text||"").join(""));let R=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(O),k=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(O);(R||k)&&(e-=1,s.push("Answer-before-verify: model gave concrete file paths/SSH commands before making any tool calls (paths guessed, not verified)"))}}if(d){let w=f;if(w.length>100){let v=(w.match(/^```/gm)||[]).length%2!==0,O=/"\s*:\s*$/.test(w.trimEnd()),R=/[,\[{]\s*$/.test(w.trimEnd());(v||O||R)&&(e-=.75,s.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let w=[];t.forEach((v,O)=>{let R=[];Array.isArray(v.tool_calls)&&v.tool_calls.forEach(k=>{if((k.function?.name||k.name||"")==="read_file"){let Se={};try{Se=typeof k.function?.arguments=="string"?JSON.parse(k.function.arguments):k.function?.arguments||{}}catch{}(Se.path||"").endsWith(".json")&&R.push({id:k.id,path:Se.path})}}),Array.isArray(v.content)&&v.content.forEach(k=>{k&&k.type==="tool_use"&&k.name==="read_file"&&(k.input?.path||"").endsWith(".json")&&R.push({id:k.id,path:k.input.path})}),R.forEach(k=>w.push({...k,msgIdx:O}))});let I=0;for(let v of w){let O=null;for(let k of t){if(k.role==="tool"&&k.tool_call_id===v.id&&typeof k.content=="string"){O=k.content;break}if(k.role==="user"&&Array.isArray(k.content)){let H=k.content.find(Se=>Se&&Se.type==="tool_result"&&Se.tool_use_id===v.id);if(H){O=typeof H.content=="string"?H.content:"";break}}}if(!O)continue;O.split(`
|
|
554
|
+
`).filter(k=>k.trim()).length<5&&/^\s*\[/.test(O)&&!/\]\s*$/.test(O.trimEnd())&&I++}I>=1&&(e-=.75,s.push(`Shallow JSON read: ${I} .json file${I>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let w=o.filter(I=>/argument errors?/i.test(I.content)||/missing required (argument|parameter)/i.test(I.content)||/invalid argument/i.test(I.content));w.length>=3?(e-=.75,s.push(`Repeated tool argument errors: ${w.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):w.length>=2&&(e-=.25,s.push(`Tool argument errors: ${w.length} tool calls returned argument errors`))}{let w=!1,I=0,v=0;for(let O of a){if((O.name==="bash"||O.name==="Bash")&&O.input?.command&&/git\s+commit\b/.test(O.input.command)){w&&(v=Math.max(v,I)),w=!0,I=0;continue}w&&(O.name==="bash"||O.name==="Bash")&&O.input?.command&&/git\s+(status|diff|log|show)\b/.test(O.input.command)&&I++}v=Math.max(v,I),v>=3&&(e-=.75,s.push(`Post-commit verification waste: ${v} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let pe=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",Re=s.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${s.length} issue${s.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:pe,issues:s,summary:Re}}function ub(t){try{let{loadSession:e}=Ir(),s=e(t);return s?op(s.messages||[]):null}catch{return null}}function db(t,e=null){let{score:s,issues:n}=t,o=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(s>=8||n.length===0)return"";let a=n.map(u=>u.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(s>=6){let u=a.slice(0,3),d=a.length-u.length,f=u.join(" \xB7 ");return d>0&&(f+=` (+${d})`),`
|
|
524
555
|
${o}${f}${r}`}let c="";for(let u of a.slice(0,4))c+=`
|
|
525
556
|
${i}\u26A0${r} ${o}${u}${r}`;let l=a.length-4;return l>0&&(c+=`
|
|
526
|
-
${o}(+${l} more)${r}`),c}function
|
|
557
|
+
${o}(+${l} more)${r}`),c}function fb(t,e={}){try{let s=Zf.join(process.cwd(),".nex");io.existsSync(s)||io.mkdirSync(s,{recursive:!0});let n=Zf.join(s,"benchmark-history.json"),o=[];if(io.existsSync(n))try{o=JSON.parse(io.readFileSync(n,"utf-8"))}catch{o=[]}Array.isArray(o)||(o=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};o.push(i),o.length>100&&(o=o.slice(o.length-100)),io.writeFileSync(n,JSON.stringify(o,null,2))}catch{}}rp.exports={scoreMessages:op,scoreSession:ub,formatScore:db,appendScoreHistory:fb,_extractToolCalls:Qf,_extractToolResults:ep,_getLastAssistantText:tp,_getLastNAssistantTexts:np,_countDuplicateToolCalls:sp}});var ps=re((Ev,up)=>{"use strict";var pb=require("os"),za=require("path"),nn=require("fs"),ao=za.join(pb.homedir(),".nex-code","model-routing.json"),Dr={frontend:{id:"frontend",label:"Frontend",icon:"\u2B21",envVar:"NEX_ROUTE_FRONTEND",pattern:/\b(react|vue|angular|svelte|jsx|tsx|html|css|scss|sass|tailwind|bootstrap|component|dom\b|ui\s|button|modal|navbar|sidebar|stylesheet|responsive|flexbox|grid|animation|frontend|front.end|onclick|hover|transition|web\s+design|landing\s+page|browser\s+event)\b/i},sysadmin:{id:"sysadmin",label:"Sysadmin",icon:"\u2699",envVar:"NEX_ROUTE_SYSADMIN",pattern:/\b(nginx|apache|docker|kubernetes|k8s|systemd|systemctl|deploy(ment)?|server\s+config|firewall|iptables\b|ssh\s+key|cron(job)?|ansible|terraform|ci\/cd|pipeline|container\b|pod\b|apt\s+install|yum\s+install|daemon|pm2|supervisor|logrotate|ssl\s+cert|lets.encrypt|reverse\s+proxy|load\s+balanc|haproxy|vhost|virtual\s+host)\b/i},data:{id:"data",label:"Data",icon:"\u2B21",envVar:"NEX_ROUTE_DATA",pattern:/\b(sql\b|mysql|postgres(ql)?|sqlite|mongodb|redis\b|query\b|database|db\s+migration|schema\s+change|table\s+join|aggregate\b|pandas\b|dataframe|\.csv\b|etl\b|data\s+transform|data\s+pipeline|analytics|data\s+warehouse|dbt\b|orm\b|knex|sequelize|prisma\s+schema)\b/i},agentic:{id:"agentic",label:"Agentic",icon:"\u2B21",envVar:"NEX_ROUTE_AGENTIC",pattern:/\b(spawn\s+agent|agent\s+swarm|multi.?agent|parallel\s+agent|orchestrat|coordinate\s+multiple\s+agent|delegate.+agent|sub.?agent|architect.*coder)\b/i},coding:{id:"coding",label:"Coding",icon:"\u2B21",envVar:"NEX_ROUTE_CODING",pattern:null}},ip=["agentic","frontend","sysadmin","data","coding"];function hb(t){if(!t||t.length<8)return null;for(let e of ip){let s=Dr[e];if(!s.pattern||s.pattern.test(t))return s}return Dr.coding}function co(){try{if(nn.existsSync(ao))return JSON.parse(nn.readFileSync(ao,"utf-8"))}catch{}return{}}function ap(t){let e=Dr[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:co()[t]||null}var cp={plan:10,implement:35,verify:8},Xa={plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function lp(){let t=co();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=Ge();if(e()==="ollama")return Xa}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Xa:null}function mb(t,e){let s=lp();return s?.[t]?s[t]:e?ap(e):null}function gb(t){return co().phaseBudgets?.[t]||cp[t]||20}function yb(){return process.env.NEX_PHASE_ROUTING==="0"?!1:lp()!==null}function $b(t){let e=za.dirname(ao);nn.existsSync(e)||nn.mkdirSync(e,{recursive:!0});let s=co(),n={...s,...t};!t.phases&&s.phases&&(n.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(n.phaseBudgets=s.phaseBudgets),nn.writeFileSync(ao,JSON.stringify(n,null,2));try{let o=za.join(e,".env"),r="";nn.existsSync(o)&&(r=nn.readFileSync(o,"utf-8"));let i=r.split(/\r?\n/),a=(c,l)=>{let u=i.findIndex(d=>d.startsWith(c+"="));u>=0?i[u]=`${c}=${l}`:i.push(`${c}=${l}`)};n.coding&&a("NEX_ROUTE_CODING",n.coding),n.frontend&&a("NEX_ROUTE_FRONTEND",n.frontend),n.sysadmin&&a("NEX_ROUTE_SYSADMIN",n.sysadmin),n.data&&a("NEX_ROUTE_DATA",n.data),n.agentic&&a("NEX_ROUTE_AGENTIC",n.agentic),n.phases&&(n.phases.plan&&a("NEX_PHASE_PLAN_MODEL",n.phases.plan),n.phases.implement&&a("NEX_PHASE_IMPLEMENT_MODEL",n.phases.implement),n.phases.verify&&a("NEX_PHASE_VERIFY_MODEL",n.phases.verify)),nn.writeFileSync(o,i.filter(c=>c.trim()!=="").join(`
|
|
558
|
+
`)+`
|
|
559
|
+
`)}catch{}}up.exports={CATEGORIES:Dr,DETECTION_ORDER:ip,detectCategory:hb,getModelForCategory:ap,getModelForPhase:mb,getPhaseBudget:gb,isPhaseRoutingEnabled:yb,DEFAULT_PHASE_BUDGETS:cp,BUILTIN_PHASE_DEFAULTS:Xa,saveRoutingConfig:$b,loadRoutingConfig:co,ROUTING_CONFIG_PATH:ao}});var hp=re((Tv,pp)=>{"use strict";var Tn=require("fs"),lo=require("path"),wb=require("os"),{detectCategory:bb}=ps(),hs=lo.join(wb.homedir(),".nex-code","examples"),Va=lo.join(__dirname,"..","examples");function dp(t){try{let s=Tn.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),n=s.match(/^user:\s*(.+)$/m);if(!n)return null;let o=n[1].trim(),r=s.indexOf(`
|
|
527
560
|
A: |`);if(r===-1)return null;let i=s.slice(r+5),a=[],c=0;for(let u of i.split(`
|
|
528
561
|
`))if(u.startsWith(" ")){for(;c>0;)a.push(""),c--;a.push(u.slice(2))}else if(u.trim()==="")a.length>0&&c++;else break;if(a.length===0)return null;let l=a.join(`
|
|
529
|
-
`).trim();return{user:o,assistant:l}}catch{return null}}function
|
|
562
|
+
`).trim();return{user:o,assistant:l}}catch{return null}}function fp(t){let e=`${t}.md`,s=lo.join(hs,e);if(Tn.existsSync(s)){let o=dp(s);if(o)return o}let n=lo.join(Va,e);return Tn.existsSync(n)?dp(n):null}function _b(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=bb(t);return e?fp(e.id):null}function xb(){let t=new Set;for(let e of[hs,Va])try{for(let s of Tn.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function kb(t,e){Tn.existsSync(hs)||Tn.mkdirSync(hs,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
|
|
530
563
|
|
|
531
564
|
user: ${e.user}
|
|
532
565
|
|
|
@@ -534,14 +567,14 @@ A: |
|
|
|
534
567
|
${e.assistant.split(`
|
|
535
568
|
`).map(n=>` ${n}`).join(`
|
|
536
569
|
`)}
|
|
537
|
-
`;
|
|
538
|
-
${
|
|
539
|
-
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${
|
|
540
|
-
`)}function
|
|
570
|
+
`;Tn.writeFileSync(lo.join(hs,`${t}.md`),s,"utf-8")}pp.exports={getFewShotForInput:_b,loadExampleForCategory:fp,listAvailableExamples:xb,savePrivateExample:kb,PRIVATE_EXAMPLES_DIR:hs,BUNDLED_EXAMPLES_DIR:Va}});var bp=re((Cv,wp)=>{var ht=require("fs"),ms=require("path"),{C:Rv}=He(),{atomicWrite:vb,withFileLockSync:Sb}=mn(),qr={bash:"ask",read_file:"allow",write_file:"ask",edit_file:"ask",list_directory:"allow",search_files:"allow",glob:"allow",grep:"allow",patch_file:"ask",web_fetch:"allow",web_search:"allow",ask_user:"allow",task_list:"allow",spawn_agents:"ask",ssh_exec:"allow",ssh_upload:"ask",ssh_download:"ask"},gs={...qr};function mp(){let t=ms.join(process.cwd(),".nex","config.json");if(ht.existsSync(t))try{let e=JSON.parse(ht.readFileSync(t,"utf-8"));e.permissions&&(gs={...qr,...e.permissions})}catch{}}function Eb(){let t=ms.join(process.cwd(),".nex"),e=ms.join(t,"config.json");ht.existsSync(t)||ht.mkdirSync(t,{recursive:!0}),Sb(e,()=>{let s={};if(ht.existsSync(e))try{s=JSON.parse(ht.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=gs,vb(e,JSON.stringify(s,null,2))})}function gp(t){return gs[t]||"ask"}function Tb(t,e){return["allow","ask","deny"].includes(e)?(gs[t]=e,!0):!1}function Rb(t){return gp(t)}function Cb(){return Object.entries(gs).map(([t,e])=>({tool:t,mode:e}))}function Ab(){gs={...qr}}var uo={readonly:{description:"Read-only access \u2014 can search and read but not modify",allowedTools:["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","ask_user","web_fetch","web_search","browser_open","browser_screenshot","task_list"],blockedTools:["bash","write_file","edit_file","patch_file","deploy","ssh_exec","service_manage","container_manage","container_exec","remote_agent"],autoConfirm:!1,allowDangerous:!1},developer:{description:"Standard developer access \u2014 can read, write, and run commands",allowedTools:null,blockedTools:["deploy","service_manage","container_manage","remote_agent"],autoConfirm:!1,allowDangerous:!1},admin:{description:"Full access \u2014 all tools, including deployment and infrastructure",allowedTools:null,blockedTools:[],autoConfirm:!1,allowDangerous:!0}};function yp(){let t=ms.join(process.cwd(),".nex","config.json");try{return ht.existsSync(t)&&JSON.parse(ht.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function Ob(t){let e=ms.join(process.cwd(),".nex"),s=ms.join(e,"config.json");ht.existsSync(e)||ht.mkdirSync(e,{recursive:!0});let n={};try{ht.existsSync(s)&&(n=JSON.parse(ht.readFileSync(s,"utf-8")))}catch{n={}}n.teamPermissions=t,ht.writeFileSync(s,JSON.stringify(n,null,2),"utf-8")}function $p(){let t=yp();if(!t)return uo.admin;let e=t.role||"admin",s=uo[e]||uo.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function Nb(t){let e=$p();return e.blockedTools&&e.blockedTools.includes(t)?{allowed:!1,reason:`Tool "${t}" is blocked by permission preset "${e.description||"custom"}"`}:e.allowedTools&&!e.allowedTools.includes(t)?{allowed:!1,reason:`Tool "${t}" is not in the allowed list for this permission level`}:{allowed:!0}}function Mb(){return Object.entries(uo).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}mp();wp.exports={getPermission:gp,setPermission:Tb,checkPermission:Rb,listPermissions:Cb,loadPermissions:mp,savePermissions:Eb,resetPermissions:Ab,DEFAULT_PERMISSIONS:qr,PERMISSION_PRESETS:uo,loadPresetConfig:yp,savePresetConfig:Ob,getEffectivePreset:$p,isToolAllowed:Nb,listPresets:Mb}});var Wr=re((Ov,Sp)=>{var Cn=require("fs"),Fr=require("path"),Av=require("readline"),{C:ve}=He(),_e=null,Za=!1,Qa=null,_p=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Br(){return Fr.join(process.cwd(),".nex","plans")}function xp(){let t=Br();Cn.existsSync(t)||Cn.mkdirSync(t,{recursive:!0})}function Lb(t,e=[]){return _e={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(s=>({description:s.description||s,files:s.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},_e}function Pb(){return _e}function Ib(t){Za=t}function jb(){return Za}function Db(){return!_e||_e.status!=="draft"?!1:(_e.status="approved",_e.updatedAt=new Date().toISOString(),!0)}function qb(){return!_e||_e.status!=="approved"?!1:(_e.status="executing",!0)}function Ja(t,e){return!_e||t<0||t>=_e.steps.length?!1:(_e.steps[t].status=e,_e.updatedAt=new Date().toISOString(),_e.steps.every(s=>s.status==="done"||s.status==="skipped")&&(_e.status="completed"),!0)}function Fb(t){if(!t)return`${ve.dim}No active plan${ve.reset}`;let e={draft:`${ve.yellow}DRAFT${ve.reset}`,approved:`${ve.green}APPROVED${ve.reset}`,executing:`${ve.blue}EXECUTING${ve.reset}`,completed:`${ve.green}COMPLETED${ve.reset}`},s=[];s.push(`
|
|
571
|
+
${ve.bold}${ve.cyan}Plan: ${t.task}${ve.reset}`),s.push(`${ve.dim}Status: ${e[t.status]||t.status}${ve.reset}
|
|
572
|
+
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${ve.green}\u2713${ve.reset}`;break;case"in_progress":r=`${ve.blue}\u2192${ve.reset}`;break;case"skipped":r=`${ve.dim}\u25CB${ve.reset}`;break;default:r=`${ve.dim} ${ve.reset}`}s.push(` ${r} ${ve.bold}Step ${n+1}:${ve.reset} ${o.description}`),o.files.length>0&&s.push(` ${ve.dim}Files: ${o.files.join(", ")}${ve.reset}`)}return s.push(""),s.join(`
|
|
573
|
+
`)}function Bb(t){if(t||(t=_e),!t)return null;xp();let e=Fr.join(Br(),`${t.name}.json`);return Cn.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function Wb(t){let e=Fr.join(Br(),`${t}.json`);if(!Cn.existsSync(e))return null;try{let s=JSON.parse(Cn.readFileSync(e,"utf-8"));return _e=s,s}catch{return null}}function Ub(){xp();let t=Br(),e=Cn.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Cn.readFileSync(Fr.join(t,n),"utf-8"));s.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return s.sort((n,o)=>(o.createdAt||"").localeCompare(n.createdAt||""))}function Hb(t){if(!t)return[];let e=[],s=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),n=s?s[1]:t,o=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=o.exec(n))!==null;){let a=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let a=r[1].replace(/\*\*/g,"").trim();a.length>3&&e.push({description:a,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,a=[...t.matchAll(i)];for(let c=0;c<Math.min(e.length,a.length);c++){let l=a[c][1];e[c].files=l.split(/[,\s]+/).filter(u=>/[./]/.test(u)).slice(0,5)}}return e}function Yb(t){Qa=t}function Gb(){return Qa}function Kb(){_e=null,Za=!1,Qa=null,Jb()}function zb(){return`
|
|
541
574
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
542
575
|
|
|
543
576
|
# Allowed Tools (read-only)
|
|
544
|
-
You may ONLY use these tools: ${[...
|
|
577
|
+
You may ONLY use these tools: ${[..._p].join(", ")}
|
|
545
578
|
Any other tool call will be blocked and returned with an error.
|
|
546
579
|
|
|
547
580
|
# MANDATORY: Read Before You Plan
|
|
@@ -585,23 +618,23 @@ Bullet list of potential issues and mitigations.
|
|
|
585
618
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
586
619
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
587
620
|
- Do NOT make any file changes \u2014 your role is analysis and planning only.
|
|
588
|
-
- Do NOT call ask_user. If anything is ambiguous, add an "## Assumptions" section to the plan and state your assumption. The user approves or rejects the whole plan \u2014 that is the only gate.`}var
|
|
589
|
-
`),s=[],n=!1,o="";for(let r of e){let i=
|
|
590
|
-
`)}function
|
|
621
|
+
- Do NOT call ask_user. If anything is ambiguous, add an "## Assumptions" section to the plan and state your assumption. The user approves or rejects the whole plan \u2014 that is the only gate.`}var Rn=0;function Xb(){!_e||_e.status!=="executing"||(Rn>0&&Ja(Rn-1,"done"),Rn<_e.steps.length&&(Ja(Rn,"in_progress"),Rn++))}function Vb(){if(!_e||_e.status!=="executing"||_e.steps.length===0)return null;let t=Math.min(Rn,_e.steps.length),e=_e.steps.length,s=Math.max(0,t-1),n=_e.steps[s]?.description||"";return{current:t,total:e,description:n}}function Jb(){Rn=0}var kp=["interactive","semi-auto","autonomous"],vp="interactive";function Zb(t){return kp.includes(t)?(vp=t,!0):!1}function Qb(){return vp}Sp.exports={createPlan:Lb,getActivePlan:Pb,setPlanMode:Ib,isPlanMode:jb,approvePlan:Db,startExecution:qb,updateStep:Ja,formatPlan:Fb,savePlan:Bb,loadPlan:Wb,listPlans:Ub,clearPlan:Kb,getPlanModePrompt:zb,setPlanContent:Yb,getPlanContent:Gb,extractStepsFromText:Hb,advancePlanStep:Xb,getPlanStepInfo:Vb,PLAN_MODE_ALLOWED_TOOLS:_p,setAutonomyLevel:Zb,getAutonomyLevel:Qb,AUTONOMY_LEVELS:kp}});var Ip=re((Nv,Pp)=>{var{C:_}=He();function Ep(){return Math.max(10,(process.stdout.columns||80)-2)}function e_(t){if(!t)return"";let e=t.split(`
|
|
622
|
+
`),s=[],n=!1,o="";for(let r of e){let i=Ep();if(r.trim().startsWith("```")){if(n)s.push(`${_.dim}${"\u2500".repeat(40)}${_.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";s.push(`${_.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${_.reset}`)}continue}if(n){s.push(` ${tc(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${_.bold}${_.cyan} ${An(r.substring(4))}${_.reset}`);continue}if(r.startsWith("## ")){s.push(`${_.bold}${_.cyan} ${An(r.substring(3))}${_.reset}`);continue}if(r.startsWith("# ")){s.push(`${_.bold}${_.cyan}${An(r.substring(2))}${_.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,""),l=`${a}${_.cyan}\u2022${_.reset} ${On(c)}`;s.push(Nn(l,i,a+" "));continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){let c=a[1],l=a[2],u=a[3],d=`${c}${_.cyan}${l}.${_.reset} ${On(u)}`,f=c+" ".repeat(l.length+2);s.push(Nn(d,i,f));continue}}s.push(Nn(On(r),i))}return s.join(`
|
|
623
|
+
`)}function An(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function On(t){return t?t.replace(/`([^`]+)`/g,`${_.cyan}$1${_.reset}`).replace(/\*\*([^*]+)\*\*/g,`${_.bold}$1${_.reset}`).replace(/\*([^*]+)\*/g,`${_.dim}$1${_.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${_.cyan}$1${_.reset} ${_.dim}($2)${_.reset}`):""}function tc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Tp(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Rp(t):e==="json"||e==="jsonc"?Cp(t):e==="python"||e==="py"?Ap(t):e==="go"||e==="golang"?Op(t):e==="rust"||e==="rs"?Np(t):e==="css"||e==="scss"||e==="less"?Mp(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Lp(t):t:""}function Tp(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(o,`${_.yellow}$1${_.reset}`),r=r.replace(e,`${_.magenta}$1${_.reset}`),r=r.replace(s,`${_.green}$&${_.reset}`),r=r.replace(n,`${_.dim}$1${_.reset}`),r}function Rp(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${_.cyan}$1${_.reset}`),r=r.replace(e,`$1${_.green}$2${_.reset}`),r=r.replace(n,`${_.yellow}$&${_.reset}`),r=r.replace(o,`${_.dim}$1${_.reset}`),r}function Cp(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${_.cyan}$1${_.reset}:`),r=r.replace(s,`: ${_.green}$1${_.reset}`),r=r.replace(n,`: ${_.yellow}$1${_.reset}`),r=r.replace(o,`: ${_.magenta}$1${_.reset}`),r}function Ap(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,n=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(o,`${_.yellow}$1${_.reset}`),i=i.replace(e,`${_.magenta}$1${_.reset}`),i=i.replace(r,`${_.cyan}$1${_.reset}`),i=i.replace(s,`${_.green}$&${_.reset}`),i=i.replace(n,`${_.dim}$1${_.reset}`),i}function Op(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${_.yellow}$1${_.reset}`),i=i.replace(s,`${_.cyan}$1${_.reset}`),i=i.replace(e,`${_.magenta}$1${_.reset}`),i=i.replace(n,`${_.green}$&${_.reset}`),i=i.replace(o,`${_.dim}$1${_.reset}`),i}function Np(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,a=t;return a=a.replace(r,`${_.yellow}$1${_.reset}`),a=a.replace(s,`${_.cyan}$1${_.reset}`),a=a.replace(e,`${_.magenta}$1${_.reset}`),a=a.replace(i,`${_.yellow}$1${_.reset}`),a=a.replace(n,`${_.green}$&${_.reset}`),a=a.replace(o,`${_.dim}$1${_.reset}`),a}function Mp(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,n=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,a=t;return a=a.replace(i,`${_.yellow}$1${_.reset}`),a=a.replace(o,`${_.yellow}$1${_.reset}`),a=a.replace(e,`$1${_.cyan}$2${_.reset}:`),a=a.replace(n,`$1${_.magenta}$&${_.reset}`),a=a.replace(r,`${_.dim}$1${_.reset}`),a}function Lp(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(o,`${_.dim}$1${_.reset}`),i=i.replace(n,`${_.green}$&${_.reset}`),i=i.replace(e,`<${_.magenta}$1${_.reset}`),i=i.replace(s,` ${_.cyan}$1${_.reset}=`),i=i.replace(r,`${_.yellow}$1${_.reset}`),i}function Nn(t,e,s=""){if(!e||e<10)return t;let n="",o=0,r=-1,i=0,a=0,c=t.length;for(;i<c;){if(t[i]==="\x1B"){let l=i+1;if(l<c&&t[l]==="["){for(l++;l<c&&!/[a-zA-Z]/.test(t[l]);)l++;l<c&&l++}i=l;continue}if(t[i]===" "&&(r=i),o++,o>e&&r!==-1){n+=t.slice(a,r)+`
|
|
591
624
|
`+s,a=r+1,i=a,o=s.length,r=-1;continue}o>e&&r===-1&&(n+=t.slice(a,i)+`
|
|
592
|
-
`+s,a=i,o=s.length+1),i++}return n+=t.slice(a),n}function
|
|
593
|
-
`)}function
|
|
594
|
-
`))!==-1;){let n=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(n)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${
|
|
595
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=
|
|
596
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let o=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${
|
|
597
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
598
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${
|
|
599
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${
|
|
600
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${
|
|
601
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${
|
|
602
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let o=e.match(/^(\s*)(\d+)\.\s(.*)/);if(o){let r=o[1],i=o[2],a=o[3],c=`${r}${
|
|
603
|
-
`);return}}let n=
|
|
604
|
-
`)}};
|
|
625
|
+
`+s,a=i,o=s.length+1),i++}return n+=t.slice(a),n}function t_(t,e){if(!t||t.length===0)return"";let s=t.map((i,a)=>{let c=e.reduce((l,u)=>Math.max(l,(u[a]||"").length),0);return Math.max(i.length,c)}),n=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),o=t.map((i,a)=>` ${_.bold}${i.padEnd(s[a])}${_.reset} `).join("\u2502"),r=[];r.push(`${_.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${_.reset}`),r.push(`${_.dim}\u2502${_.reset}${o}${_.dim}\u2502${_.reset}`),r.push(`${_.dim}\u251C${n}\u2524${_.reset}`);for(let i of e){let a=t.map((c,l)=>` ${(i[l]||"").padEnd(s[l])} `).join(`${_.dim}\u2502${_.reset}`);r.push(`${_.dim}\u2502${_.reset}${a}${_.dim}\u2502${_.reset}`)}return r.push(`${_.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${_.reset}`),r.join(`
|
|
626
|
+
`)}function n_(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),i=n-r,a=o>=100?_.green:o>50?_.yellow:_.cyan;return` ${t} ${a}${"\u2588".repeat(r)}${_.dim}${"\u2591".repeat(i)}${_.reset} ${o}% (${e}/${s})`}var ec=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}_cursorWrite(e){try{process.stderr.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let s=[0,1,2,3,4,3,2,1],n=s[this._cursorFrame%s.length],o="";for(let r=0;r<5;r++)o+=r===n?"\x1B[36m\u25CF\x1B[0m":" ";this._cursorWrite(`\x1B[2K\r${o}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let s;for(;(s=this.buffer.indexOf(`
|
|
627
|
+
`))!==-1;){let n=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(n)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${_.dim}${"\u2500".repeat(40)}${_.reset}
|
|
628
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=Ep();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${_.dim}${"\u2500".repeat(40)}${_.reset}
|
|
629
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let o=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${_.dim}${"\u2500".repeat(3)}${o}${"\u2500".repeat(Math.max(0,37-o.length))}${_.reset}
|
|
630
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${tc(e,this.codeBlockLang)}
|
|
631
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${_.bold}${_.cyan} ${An(e.substring(4))}${_.reset}
|
|
632
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${_.bold}${_.cyan} ${An(e.substring(3))}${_.reset}
|
|
633
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${_.bold}${_.cyan}${An(e.substring(2))}${_.reset}
|
|
634
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${_.cyan}\u2022${_.reset} ${On(r)}`,a=Nn(i,s,o+" ");this._safeWrite(`${a}
|
|
635
|
+
`);return}if(/^\s*\d+\.\s/.test(e)){let o=e.match(/^(\s*)(\d+)\.\s(.*)/);if(o){let r=o[1],i=o[2],a=o[3],c=`${r}${_.cyan}${i}.${_.reset} ${On(a)}`,l=r+" ".repeat(i.length+2),u=Nn(c,s,l);this._safeWrite(`${u}
|
|
636
|
+
`);return}}let n=Nn(On(e),s);this._safeWrite(`${n}
|
|
637
|
+
`)}};Pp.exports={renderMarkdown:e_,renderInline:On,stripHeadingMarkers:An,highlightCode:tc,highlightJS:Tp,highlightBash:Rp,highlightJSON:Cp,highlightPython:Ap,highlightGo:Op,highlightRust:Np,highlightCSS:Mp,highlightHTML:Lp,renderTable:t_,renderProgress:n_,wrapAnsi:Nn,StreamRenderer:ec}});var Bp=re((Mv,Fp)=>{var{execSync:s_}=require("child_process"),nc=require("path"),fo=require("fs"),sc=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function jp(){return nc.join(process.cwd(),".nex","hooks")}function o_(){return nc.join(process.cwd(),".nex","config.json")}function Dp(){let t=o_();if(!fo.existsSync(t))return{};try{return JSON.parse(fo.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Ur(t){if(!sc.includes(t))return[];let e=[],s=jp(),n=nc.join(s,t);fo.existsSync(n)&&e.push(n);let o=Dp();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function qp(t,e={},s=3e4){try{return{success:!0,exitCode:0,output:s_(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){let o=typeof n.status=="number"?n.status:1;return{success:!1,exitCode:o,blocked:o===2,output:n.stdout?n.stdout.trim():"",error:n.stderr?n.stderr.trim():n.message}}}function r_(t,e={}){let s=Ur(t);if(s.length===0)return{results:[],blocked:!1};let n={};for(let[r,i]of Object.entries(e))n[`NEX_${r.toUpperCase()}`]=String(i);let o=[];for(let r of s){let i=qp(r,n);if(o.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let a=i.output||i.error||"hook blocked tool call";return{results:o,blocked:!0,blockReason:a}}if(!i.success&&t.startsWith("pre-"))break}return{results:o,blocked:!1}}function i_(t){return Ur(t).length>0}function a_(){let t=[];for(let e of sc){let s=Ur(e);s.length>0&&t.push({event:e,commands:s})}return t}function c_(){let t=jp();return fo.existsSync(t)||fo.mkdirSync(t,{recursive:!0}),t}Fp.exports={HOOK_EVENTS:sc,loadHookConfig:Dp,getHooksForEvent:Ur,executeHook:qp,runHooks:r_,hasHooks:i_,listHooks:a_,initHooksDir:c_}});var nh=re((jv,th)=>{"use strict";var{callWithRetry:Up,runSubAgent:l_,clearAllLocks:u_}=Sa(),{parseModelSpec:Hp,getActiveProviderName:Lv,getActiveModelId:Pv}=Ge(),{detectCategory:d_,getModelForCategory:Wp}=ps(),{MultiProgress:f_,C:de}=He(),{getModelBriefing:Iv}=wr(),Yp=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Hr=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Gp="devstral-2:123b",Kp="kimi-k2.5",zp=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
|
|
605
638
|
|
|
606
639
|
RULES:
|
|
607
640
|
- Output ONLY a JSON array, no markdown fences, no explanation.
|
|
@@ -616,7 +649,7 @@ RULES:
|
|
|
616
649
|
- If the request is simple (single goal), return an array with exactly 1 item.
|
|
617
650
|
|
|
618
651
|
USER REQUEST:
|
|
619
|
-
{prompt}`,
|
|
652
|
+
{prompt}`,Xp=`You are a result synthesis engine. Given the results of multiple sub-agents that worked on parts of a larger task, produce a unified summary.
|
|
620
653
|
|
|
621
654
|
RULES:
|
|
622
655
|
- Output ONLY a JSON object with these fields:
|
|
@@ -630,16 +663,16 @@ ORIGINAL REQUEST:
|
|
|
630
663
|
{prompt}
|
|
631
664
|
|
|
632
665
|
SUB-AGENT RESULTS:
|
|
633
|
-
{results}`;async function
|
|
634
|
-
${e.slice(0,200)}`)}async function
|
|
666
|
+
{results}`;async function Vp(t,e=1,s=2e3){for(let n=0;n<=e;n++)try{return await t()}catch(o){if(n===e)throw o;await new Promise(r=>setTimeout(r,s))}}function Jp(t){let e=0,s=[];return function(){return new Promise(o=>{let r=()=>{e<t?(e++,o(()=>{e--,s.length>0&&s.shift()()})):s.push(r)};r()})}}function p_(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,s=[],n=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);n&&n.length>=2&&(e=Math.max(e,n.length),s.push(`${n.length} numbered items`));let o=t.match(/(?:^|\n)\s*[-*]\s+\S/g);o&&o.length>=3&&(e=Math.max(e,o.length),s.push(`${o.length} bullet points`));let r=t.split(/;\s*/).filter(l=>l.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),s.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),s.push(`${i.length} transition keywords`));let a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=a,estimatedGoals:e,reason:s.length>0?s.join(", "):"single goal"}}function oc(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let s=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(s)try{return JSON.parse(s[1].trim())}catch{}let n=e.search(/[[\{]/);if(n>=0){let o=e.slice(n);try{return JSON.parse(o)}catch{}}throw new Error(`Could not extract valid JSON from response:
|
|
667
|
+
${e.slice(0,200)}`)}async function Zp(t,e,s={}){let n=s.maxSubTasks||Hr,r=[{role:"system",content:zp.replace("{maxSubTasks}",String(n)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let m=Hp(e);m.provider&&(i.provider=m.provider),m.model&&(i.model=m.model)}let c=(await Up(r,[],i)).content||"",l=oc(c);if(!Array.isArray(l))throw new Error(`Decompose returned non-array: ${typeof l}`);let u=10,f=l.slice(0,n).map((m,b)=>({id:m.id||`t${b+1}`,task:String(m.task||""),scope:Array.isArray(m.scope)?m.scope:[],estimatedCalls:typeof m.estimatedCalls=="number"?Math.min(m.estimatedCalls,u):8,priority:typeof m.priority=="number"?m.priority:b+1})).filter(m=>m.task.length>0),h=f.reduce((m,b)=>m+b.estimatedCalls,0),g=Hr*u;if(h>g){let{debugLog:m}=Zo();m(`\x1B[33m \u26A0 Orchestrator: total estimated calls ${h} > ${g} \u2014 consider raising maxSubTasks\x1B[0m`)}return f}async function Qp(t,e,s){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let n=t.map((u,d)=>{let f=u.status==="done"?"SUCCESS":u.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${d+1} [${f}] ---
|
|
635
668
|
Task: ${u.task}
|
|
636
669
|
Result: ${u.result}
|
|
637
670
|
Tools: ${(u.toolsUsed||[]).join(", ")||"none"}`}).join(`
|
|
638
671
|
|
|
639
|
-
`),r=[{role:"system",content:
|
|
640
|
-
${
|
|
641
|
-
`),i("decomposing"),console.log(`${
|
|
642
|
-
`);let u=Date.now(),d=
|
|
672
|
+
`),r=[{role:"system",content:Xp.replace("{prompt}",e).replace("{results}",n)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let u=Hp(s);u.provider&&(i.provider=u.provider),u.model&&(i.model=u.model)}let c=(await Up(r,[],i)).content||"",l=oc(c);return{summary:String(l.summary||""),conflicts:Array.isArray(l.conflicts)?l.conflicts:[],commitMessage:String(l.commitMessage||""),filesChanged:Array.isArray(l.filesChanged)?l.filesChanged:[]}}async function h_(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Kp,n=e.workerModel||Gp,o=e.maxParallel||Yp,r=e.maxSubTasks||Hr,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
|
|
673
|
+
${de.bold}Orchestrator${de.reset} ${de.dim}model: ${s} | workers: ${n} | max parallel: ${o}${de.reset}
|
|
674
|
+
`),i("decomposing"),console.log(`${de.dim}Phase 1: Decomposing prompt into sub-tasks...${de.reset}`);let c;try{c=await Zp(t,s,{maxSubTasks:r})}catch(K){return console.log(`${de.red}Decompose failed: ${K.message}${de.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${K.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a}}if(c.length===0)return console.log(`${de.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${de.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:a};console.log(`${de.green}Decomposed into ${c.length} sub-tasks:${de.reset}`);for(let K of c){console.log(` ${de.dim}${K.id}:${de.reset} ${K.task}`);let X=K.scope.filter(Boolean);X.length>0&&console.log(` ${de.dim}scope: ${X.join(", ")}${de.reset}`)}console.log("");let l=new Map;for(let K=0;K<c.length;K++)for(let X of c[K].scope)X&&!l.has(X)&&l.set(X,K);i("executing"),console.log(`${de.dim}Phase 2: Running ${c.length} sub-agents (max ${o} parallel)...${de.reset}
|
|
675
|
+
`);let u=Date.now(),d=Jp(o),f={findings:[],_lock:!1},h=c.map(K=>{let X=d_(K.task);return(X?Wp(X.id):null)||n}),g=c.map((K,X)=>{let me=`Agent ${X+1} [${h[X]}]: `,fe=Math.max(20,60-me.length),$e=K.task.substring(0,fe)+(K.task.length>fe?"...":"");return me+$e}),m=new f_(g);m.start();let b=`
|
|
643
676
|
You are a focused coding agent executing ONE specific sub-task.
|
|
644
677
|
Your scope is limited to the files listed in your task definition.
|
|
645
678
|
|
|
@@ -660,40 +693,40 @@ RULES:
|
|
|
660
693
|
- If your task says "add X to README" \u2014 add it, don't check if it exists first.
|
|
661
694
|
- Max 10 tool calls. If you need more, you are doing too much \u2014 narrow your scope.
|
|
662
695
|
- When done: stop calling tools and write a one-line summary of what you changed.
|
|
663
|
-
`,
|
|
664
|
-
`)
|
|
665
|
-
${
|
|
666
|
-
`:"",
|
|
667
|
-
`)),
|
|
668
|
-
`):void 0,max_iterations:Math.min(
|
|
669
|
-
`),conflicts:[],commitMessage:"",resourcesChanged:[]}}let
|
|
670
|
-
${
|
|
671
|
-
`),{results:
|
|
672
|
-
`)}var
|
|
673
|
-
|
|
674
|
-
[SYSTEM: Output repetition detected \u2014 response truncated (${o}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let c=0,l=-1,u=0;for(;c<2;){let d=t.indexOf(r,u);if(d===-1)break;c++,l=d+r.length,u=d+1}a=l>0?t.slice(0,l)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:o}}function
|
|
696
|
+
`,x=new Map;for(let K=0;K<c.length;K++){let X=c[K].priority||1;x.has(X)||x.set(X,[]),x.get(X).push({st:c[K],idx:K})}let j=[...x.keys()].sort((K,X)=>K-X),G=new Array(c.length);for(let K of j){let me=x.get(K).map(async({st:fe,idx:$e})=>{let pe=await d();try{let Re=await L(fe,$e,{acquire:d,subTaskModels:h,labels:g,progress:m,sharedContext:f,_fileOwnership:l,workerModel:n,WORKER_SYSTEM_PROMPT:b});return G[$e]=Re,Re}finally{pe()}});await Promise.all(me)}async function L(K,X,me){try{let fe=f.findings.filter(H=>H.agentId!==K.id).map(H=>`Agent ${H.agentId} found: ${H.summary}`).join(`
|
|
697
|
+
`),$e=[...l.entries()].filter(([,H])=>H===X).map(([H])=>H),pe=[...l.entries()].filter(([,H])=>H!==X).map(([H])=>H),Re=[fe?`Prior agent findings:
|
|
698
|
+
${fe}
|
|
699
|
+
`:"",K.scope.length>0?`Focus on files: ${K.scope.join(", ")}`:"",$e.length>0?`You OWN these files (may read+write): ${$e.join(", ")}`:"",pe.length>0?`READ ONLY (owned by other agents, do NOT write): ${pe.join(", ")}`:""].filter(Boolean),w=eh(K.task),I=h[X],v=process.env.NEX_FALLBACK_MODEL||Wp("agentic")||n,O=0,R=await Vp(async()=>{let H=O>0;H&&(m.update(X,"retry"),process.stderr.write(` ${de.dim}[Agent ${X+1}] retrying after error...${de.reset}
|
|
700
|
+
`)),O++;let Se=H&&I!==v?v:I;return l_({task:K.task,type:w,context:Re.length>0?Re.join(`
|
|
701
|
+
`):void 0,max_iterations:Math.min(K.estimatedCalls||10,15),model:Se,_skipLog:!0,_systemPrompt:b,_readOnlyFiles:pe},{onUpdate:xe=>{if(xe&&xe.type==="tool_call"&&process.stderr.isTTY){let ge=`Agent ${X+1} [${Se}]`,fi=xe.tool||"...";m.labels[X]=`${ge}: ${fi}`}}})},1,2e3),k=typeof R.result=="string"?R.result.slice(0,200):String(R.result||"").slice(0,200);return f.findings.push({agentId:K.id,summary:k,files:Array.isArray(K.scope)?K.scope:[]}),m.labels[X]=g[X],m.update(X,R.status==="failed"?"error":"done"),a.input+=R.tokensUsed?.input||0,a.output+=R.tokensUsed?.output||0,R.tokensUsed?._estimated&&(a._estimated=!0),{...R,_scope:K.scope,_idx:X}}catch(fe){return m.labels[X]=g[X],m.update(X,"error"),{task:K.task,status:"failed",result:`Error: ${fe.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let P;try{P=G}finally{m.stop({silent:!0}),u_()}console.log("");let C=Math.round((Date.now()-u)/1e3),Z=C>=60?`${Math.floor(C/60)}m ${C%60}s`:`${C}s`;for(let K=0;K<P.length;K++){let X=P[K],fe=X.status==="done"||X.status==="truncated"&&X.result&&!X.result.startsWith("Error")?`${de.green}\u2713${de.reset}`:`${de.red}\u2717${de.reset}`,$e=X._scope&&X._scope.length>0?X._scope.map(w=>w.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],pe=$e.length>0?$e.join(", "):X.task.substring(0,35)+(X.task.length>35?"...":""),Re=K===P.length-1;console.log(` ${fe} Agent ${K+1} ${de.dim}${pe}${de.reset}${Re?` ${de.dim}${Z}${de.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${de.dim}Phase 3: Synthesizing results...${de.reset}`);let Y;try{Y=await Qp(P,t,s)}catch(K){console.log(`${de.yellow}Synthesize failed: ${K.message} \u2014 using raw results.${de.reset}`),Y={summary:P.map(X=>X.result).join(`
|
|
702
|
+
`),conflicts:[],commitMessage:"",resourcesChanged:[]}}let ue=f.findings.flatMap(K=>K.files),ie=new Map;for(let K of ue)ie.set(K,(ie.get(K)||0)+1);let se=[...ie.values()].some(K=>K>1),T=f.findings.length>1&&se?` ${de.dim}(agents shared context)${de.reset}`:"";if(console.log(`
|
|
703
|
+
${de.bold}Summary:${de.reset} ${Y.summary}${T}`),Y.conflicts.length>0){console.log(`${de.yellow}Conflicts:${de.reset}`);for(let K of Y.conflicts)console.log(` - ${K}`)}Y.commitMessage&&console.log(`${de.dim}Suggested commit: ${Y.commitMessage}${de.reset}`);let Te=a.input===0&&a.output===0?"n/a (provider does not report token counts)":a._estimated?`~${a.input} input / ~${a.output} output (est.)`:`${a.input} input + ${a.output} output`;return console.log(`${de.dim}Tokens: ${Te}${de.reset}
|
|
704
|
+
`),{results:P,synthesis:Y,totalTokens:a}}var m_=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,g_=/\b(fix|implement|create|add|update|modify|change|write|refactor|remove|delete|install|configure|setup|deploy|build|migrate|optimize|improve|patch|rewrite|replace)\b/i;function eh(t){if(!t)return"implement";let e=m_.test(t);return g_.test(t)?"implement":e?"explore":"implement"}th.exports={runOrchestrated:h_,decompose:Zp,synthesize:Qp,detectComplexPrompt:p_,extractJSON:oc,createSemaphore:Jp,DECOMPOSE_PROMPT:zp,SYNTHESIZE_PROMPT:Xp,DEFAULT_ORCHESTRATOR_MODEL:Kp,DEFAULT_WORKER_MODEL:Gp,DEFAULT_MAX_PARALLEL:Yp,DEFAULT_MAX_SUBTASKS:Hr,withRetry:Vp,_classifyWorkerType:eh}});var kh=re((Uv,xh)=>{var{C:p,Spinner:$s,TaskProgress:y_,formatToolCall:$_,formatToolSummary:yc,formatSectionHeader:Yr,formatMilestone:w_,setActiveTaskProgress:Dv,getThinkingVerb:rc,setActiveModelForSpinner:b_}=He(),{debugLog:F,warnLog:qv}=Zo(),{MilestoneTracker:__}=eu(),{callStream:sh}=Ge(),{parseToolArgs:x_}=Rs(),{executeTool:k_}=ts(),{gatherProjectContext:v_}=zf(),{fitToContext:S_,forceCompress:jt,getUsage:Tt,estimateTokens:E_,buildProgressSnapshot:T_}=It(),{autoSave:R_,flushAutoSave:C_}=Ir(),{scoreMessages:A_,formatScore:O_,appendScoreHistory:N_}=jr(),{detectCategory:M_,getModelForPhase:$c,getPhaseBudget:Mn,isPhaseRoutingEnabled:L_}=ps();function qe(t){R_(t),C_()}function P_(t){if(!t||typeof t!="string")return!0;let e=t.trim();return!!(e.length<80||/^(done|complete|finished|all done|analysis complete|finally done)[.!]*$/i.test(e)||/^[^.!]{0,40}\?$/.test(e))}function ic(t){try{if(!t.some(n=>n.role!=="assistant"?!1:!!(Array.isArray(n.content)&&n.content.some(o=>o&&o.type==="tool_use")||Array.isArray(n.tool_calls)&&n.tool_calls.length>0)))return;let s=A_(t);if(!s)return;console.log(O_(s,p));try{let{_getSessionsDir:n}=Ir(),o=require("fs"),r=require("path").join(n(),"_autosave.json");if(o.existsSync(r)){let i=JSON.parse(o.readFileSync(r,"utf-8"));i.score=s.score,i.scoreGrade=s.grade,i.scoreIssues=s.issues,o.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:n}=Rs(),o=Lo();N_(s.score,{version:o.version,model:n?n():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:I_}=Js(),{getDeploymentContextBlock:j_,probeUrlServer:D_}=Ua(),{getFewShotForInput:q_}=hp(),{checkPermission:F_,setPermission:B_,savePermissions:W_}=bp(),{confirm:mh,setAllowAlwaysHandler:U_,getAutoConfirm:H_}=Cs(),{isPlanMode:_o,getPlanModePrompt:Y_,PLAN_MODE_ALLOWED_TOOLS:gh,setPlanContent:G_,extractStepsFromText:K_,createPlan:z_,getActivePlan:Fv,startExecution:Bv,advancePlanStep:X_,getPlanStepInfo:V_}=Wr(),{StreamRenderer:J_}=Ip(),{runHooks:oh}=Bp(),{routeMCPCall:Z_,getMCPToolDefinitions:Q_}=na(),{getSkillInstructions:ex,getSkillToolDefinitions:tx,routeSkillCall:nx,matchSkillTriggers:sx}=ea(),{trackUsage:rh,estimateTokens:ih}=Jo();function ah(t){return!t||typeof t!="string"?0:typeof ih=="function"?ih(t):Math.ceil(t.length/4)}var{validateToolArgs:ox}=ra(),{filterToolsForModel:ch,getModelTier:rx,PROVIDER_DEFAULT_TIER:Wv}=qs(),{getConfiguredProviders:ix,getActiveProviderName:ws,getActiveModelId:At,setActiveModel:lh,MODEL_EQUIVALENTS:oi}=Ge(),{getModelProfile:ax,getModelBriefing:cx}=wr(),Ac=require("fs"),Oc=require("path"),lx=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function ux(t){let e=w_(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
|
|
705
|
+
`)}var uh=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function dx(t){let e=[],s;for(uh.lastIndex=0;(s=uh.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):Oc.resolve(n);Ac.existsSync(o)&&e.push({raw:n,abs:o})}return e}function fx(t){let e=Ac.readFileSync(t),s=Oc.extname(t).toLowerCase().replace(".",""),n=s==="jpg"||s==="jpeg"?"image/jpeg":s==="png"?"image/png":s==="gif"?"image/gif":s==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:n}}function yh(t){let e=dx(t);if(e.length===0)return t;let s=[{type:"text",text:t}];for(let n of e)try{let{data:o,media_type:r}=fx(n.abs);s.push({type:"image",media_type:r,data:o})}catch{}return s.length>1?s:t}function px(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let s=t.split(/(?<=\. )/).filter(c=>c.trim().length>0);if(s.length<6)return{text:t,truncated:!1,repeatCount:0};let n=new Map;for(let c=0;c<=s.length-3;c++){let l=s.slice(c,c+3).join("").trim();l.length>30&&n.set(l,(n.get(l)||0)+1)}let o=0,r="";for(let[c,l]of n)l>o&&(o=l,r=c);if(o<3)return{text:t,truncated:!1,repeatCount:o};let i=`
|
|
706
|
+
|
|
707
|
+
[SYSTEM: Output repetition detected \u2014 response truncated (${o}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=t.slice(0,3e3)+i;else{let c=0,l=-1,u=0;for(;c<2;){let d=t.indexOf(r,u);if(d===-1)break;c++,l=d+r.length,u=d+1}a=l>0?t.slice(0,l)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:o}}function wc(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
|
|
675
708
|
`),n=new Map;for(let d of s){let f=d.trim();f.length>=20&&n.set(f,(n.get(f)||0)+1)}let o=0,r="";for(let[d,f]of n)f>o&&(o=f,r=d);if(o<=e)return{text:t,truncated:!1,repeatCount:o};let i=`
|
|
676
709
|
|
|
677
|
-
\u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,a=0,c=-1,l=0;for(;a<e;){let d=t.indexOf(r,l);if(d===-1)break;a++,c=d+r.length,l=d+1}return{text:c>0?t.slice(0,c)+i:t.slice(0,2e3)+i,truncated:!0,repeatCount:o}}var
|
|
710
|
+
\u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,a=0,c=-1,l=0;for(;a<e;){let d=t.indexOf(r,l);if(d===-1)break;a++,c=d+r.length,l=d+1}return{text:c>0?t.slice(0,c)+i:t.slice(0,2e3)+i,truncated:!0,repeatCount:o}}var ac=null,cc=null,lc=null;function Qe(){if(ac===null){let{TOOL_DEFINITIONS:t}=ts();ac=t}return cc===null&&(cc=tx()),lc===null&&(lc=Q_()),[...ac,...cc,...lc]}var bc=50;function hx(t){Number.isFinite(t)&&t>0&&(bc=t)}var zr=()=>null;function mx(t){zr=t}var mo=null,_c=null,bs=null,Xr=new Map,gx=1e4,yx=6e3,$x=/\b((?:API|ACCESS|AUTH|BEARER|CLIENT|GITHUB|GITLAB|SLACK|STRIPE|TWILIO|SENDGRID|AWS|GCP|AZURE|OPENAI|ANTHROPIC|GEMINI|OLLAMA)[_A-Z0-9]*(?:KEY|TOKEN|SECRET|PASS(?:WORD)?|CREDENTIAL)[_A-Z0-9]*)\s*=\s*["']?([A-Za-z0-9\-_.+/=]{10,})["']?/g;function wx(t){return!t||typeof t!="string"?t:t.replace($x,(e,s)=>`${s}=***REDACTED***`)}var bx=7e3,_x=4e3;function xx(t,e=null){let s=wx(t),n=E_(s),o=e==="read_file"?bx:gx,r=e==="read_file"?_x:yx;if(n>o)try{let{compressToolResult:i}=It();return i(s,r)}catch{return s}return s}function $h(t){try{let{getActiveModel:e}=Ge(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Xr.has(n))return Xr.get(n);let o=ch(t);return Xr.set(n,o),o}catch{return ch(t)}}function kx(){Xr.clear()}var go={hash:null,ts:0},vx=3e4;async function wh(){if(go.hash&&Date.now()-go.ts<vx)return go.hash;try{let t=require("fs").promises,e=require("path"),s=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],o=(await Promise.allSettled(s.map(i=>t.stat(i).then(a=>`${i}:${a.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=Js(),a=i();a&&o.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Ac.existsSync(i)){let a=await t.stat(i);o.push(`brain:${a.mtimeMs}`)}}catch{}let r=o.join("|");return go={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function xc(){mo=null,_c=null,go={hash:null,ts:0},bs=null}var Sx=new Set(["spawn_agents"]),uc=5,dc=3,Gr=2,dh=6e4,fc=12e4,Ex=process.env.NEX_STALE_AUTO_SWITCH!=="0";function Tx(t){try{let e=require("fs"),s=require("path"),n=s.join(process.cwd(),".nex","plans");e.existsSync(n)||e.mkdirSync(n,{recursive:!0});let o=s.join(n,"current-plan.md");e.writeFileSync(o,t,"utf-8")}catch{}}U_(t=>{B_(t,"allow"),W_(),console.log(`${p.green} \u2713 ${t}: always allow${p.reset}`)});async function Rx(t){let e=t.function.name,s=x_(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let u=Qe().find(f=>f.function.name===e),d=u?JSON.stringify(u.function.parameters,null,2):"unknown";return F(`${p.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${p.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
678
711
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
679
712
|
|
|
680
713
|
Expected JSON schema for "${e}":
|
|
681
714
|
${d}
|
|
682
715
|
|
|
683
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=
|
|
684
|
-
`)[0]}${p.reset}`);let l=(
|
|
716
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=ox(e,s);if(!o.valid){F(`${p.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
717
|
+
`)[0]}${p.reset}`);let l=(ph.get(e)||0)+1;ph.set(e,l);let u=l>=2?`${o.error}
|
|
685
718
|
|
|
686
|
-
[SYSTEM: This is argument error #${l} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:o.error;return{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:u,tool_call_id:n}}}let r=o.corrected||s;if(o.corrected){let l=Object.keys(s),u=Object.keys(o.corrected),d=l.filter(f=>!u.includes(f));d.length&&console.log(`${p.dim} \u2713 ${e}: corrected args (${d.join(", ")})${p.reset}`)}if(
|
|
687
|
-
...(truncated ${
|
|
688
|
-
`)[0],a
|
|
689
|
-
HINT: use read_file instead of bash cat \u2014 it is faster, context-efficient, and the preferred tool for reading files.`:/^\s*ls(\s|$)/.test(
|
|
690
|
-
HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(
|
|
691
|
-
HINT: use glob instead of bash find for file discovery \u2014 it is faster and the preferred tool (e.g. glob('**/*.jsx')).`)}return{msg:{role:"tool",content:
|
|
692
|
-
`)):(
|
|
693
|
-
`)}function
|
|
694
|
-
${
|
|
719
|
+
[SYSTEM: This is argument error #${l} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:o.error;return{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:u,tool_call_id:n}}}let r=o.corrected||s;if(o.corrected){let l=Object.keys(s),u=Object.keys(o.corrected),d=l.filter(f=>!u.includes(f));d.length&&console.log(`${p.dim} \u2713 ${e}: corrected args (${d.join(", ")})${p.reset}`)}if(_o()&&!gh.has(e))return console.log(`${p.yellow} \u2717 ${e}: blocked in plan mode${p.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:n}};let i=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),a=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]);if(we&&Pe==="plan"&&!i.has(e)&&!e.startsWith("skill_"))return rn++,F(`${p.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${rn})${p.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${e}' is blocked. Analyze the codebase using read-only tools, then present your findings as text. Edits happen in the next phase.`,tool_call_id:n}};if(we&&Pe==="verify"&&!a.has(e)&&!e.startsWith("skill_"))return F(`${p.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${p.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${e}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:n}};let c=F_(e);if(c==="deny")return console.log(`${p.red} \u2717 ${e}: denied by permissions${p.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(c==="ask"){let l=` Allow ${e}?`;return e==="bash"&&r.command&&(l=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await mh(l,{toolName:e})?{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:n,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:n}}}return{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function Cx(t,e,s={}){let n=await nx(t,e);if(n!==null)return n;let o=await Z_(t,e);return o!==null?o:k_(t,e,s)}function Ax(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function pc(t,e=!1){e||console.log($_(t.fnName,t.args));let s=oh("pre-tool",{tool_name:t.fnName}),n=s.results;if(s.blocked){let m=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${s.blockReason}`;e||console.log(`${p.yellow} [hook pre-tool] BLOCKED: ${s.blockReason}${p.reset}`);let b=yc(t.fnName,t.args,m,!0);return e||console.log(b),{msg:{role:"tool",content:m,tool_call_id:t.callId},summary:b}}if(!e&&n.length>0)for(let m of n)m.success?console.log(`${p.dim} [hook pre-tool] ${m.command} \u2192 ${m.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook pre-tool] ${m.command} \u2192 ERROR: ${m.error}${p.reset}`);Ft?.onToolStart&&Ft.onToolStart(t.fnName,t.args);let o=await Cx(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=String(o??""),i=r.length>5e4?r.substring(0,5e4)+`
|
|
720
|
+
...(truncated ${r.length-5e4} chars)`:r,a=i.split(`
|
|
721
|
+
`)[0],c=a.startsWith("ERROR")||a.includes("CANCELLED")||a.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(i)&&/✗ Agent/.test(i),l=yc(t.fnName,t.args,i,c);e||console.log(l),Ft?.onToolEnd&&Ft.onToolEnd(t.fnName,l,!c);let d=oh("post-tool",{tool_name:t.fnName}).results;if(!e&&d.length>0)for(let m of d)m.success?console.log(`${p.dim} [hook post-tool] ${m.command} \u2192 ${m.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook post-tool] ${m.command} \u2192 ERROR: ${m.error}${p.reset}`);let h=xx(i,t.fnName);if(t.fnName==="bash"&&t.args?.command){let m=t.args.command.trim();!/cat\s*>|<</.test(m)&&/\bcat\s+\S/.test(m)?h+=`
|
|
722
|
+
HINT: use read_file instead of bash cat \u2014 it is faster, context-efficient, and the preferred tool for reading files.`:/^\s*ls(\s|$)/.test(m)&&!/npm|yarn|pnpm|make|git\b/.test(m)?h+=`
|
|
723
|
+
HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(m)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test(m)&&(h+=`
|
|
724
|
+
HINT: use glob instead of bash find for file discovery \u2014 it is faster and the preferred tool (e.g. glob('**/*.jsx')).`)}return{msg:{role:"tool",content:h,tool_call_id:t.callId},summary:l}}var Ox=[{re:/TypeError:\s*([^\n]{0,120})/i,label:"TypeError"},{re:/SyntaxError:\s*([^\n]{0,120})/i,label:"SyntaxError"},{re:/ReferenceError:\s*([^\n]{0,120})/i,label:"ReferenceError"},{re:/Cannot find module\s*'([^']+)'/i,label:"Cannot find module"},{re:/Error:\s*ENOENT[^\n]{0,120}/i,label:"ENOENT"},{re:/Error:\s*EACCES[^\n]{0,120}/i,label:"EACCES"},{re:/Error:\s*EADDRINUSE[^\n]{0,120}/i,label:"EADDRINUSE"},{re:/ImportError:\s*([^\n]{0,120})/i,label:"ImportError"},{re:/ModuleNotFoundError:\s*([^\n]{0,120})/i,label:"ModuleNotFoundError"},{re:/NameError:\s*([^\n]{0,120})/i,label:"NameError"},{re:/AttributeError:\s*([^\n]{0,120})/i,label:"AttributeError"},{re:/KeyError:\s*([^\n]{0,120})/i,label:"KeyError"},{re:/ValueError:\s*([^\n]{0,120})/i,label:"ValueError"},{re:/panic:\s*([^\n]{0,120})/i,label:"Go panic"},{re:/java\.lang\.\w+Exception[^\n]{0,80}/i,label:"Java exception"}];function hc(t){for(let{re:e,label:s}of Ox){let n=t.match(e);if(n){let o=(n[1]||"").trim();return o?`${s}: ${o}`:s}}return null}async function Nx(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],i=null;if(e&&!s.skipSpinner){let c=t.filter(l=>l.canExecute);if(c.length>0){let l;if(c.length===1){let u=c[0],d=Ax(u.fnName,u.args);l=`\u23FA ${u.fnName}${d?`(${d})`:""}`}else{let u=c.map(d=>d.fnName).join(", ");l=`\u23FA ${c.length} tools: ${u.length>60?u.substring(0,57)+"\u2026":u}`}i=new $s(l),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let c=r[0],{msg:l,summary:u}=await pc(t[c],e);n[c]=l,o.push(u)}else{let c=r.map(u=>pc(t[u],e)),l=await Promise.all(c);for(let u=0;u<r.length;u++)n[r[u]]=l[u].msg,o.push(l[u].summary)}r=[]}}for(let c=0;c<t.length;c++){let l=t[c];if(!l.canExecute){await a(),n[c]=l.errorResult,o.push(yc(l.fnName,l.args||{},l.errorResult.content,!0));continue}if(Sx.has(l.fnName)){await a(),l.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await pc(l,e);n[c]=u,o.push(d)}else r.push(c)}if(await a(),i&&i.stop(),e&&o.length>0&&!s.skipSummaries)for(let c of o)console.log(c);return{results:n,summaries:o}}var q=[],fh=300,bh=900*1e3;function Dt(t,e){let s=t.get(e);return s?Date.now()-s.ts>bh?(t.delete(e),0):s.count:0}function Ln(t,e){let s=t.get(e),n=s&&Date.now()-s.ts<=bh?s.count+1:1;return t.set(e,{count:n,ts:Date.now()}),n}function mc(t,e,s){t.set(e,{count:s,ts:Date.now()})}var Nc=new Map,Mc=new Map,xo=new Map,Lc=new Map,ko=new Map,on=new Map,zt=new Map,Pc=new Map,Pn=new Map,qn=new Map,ph=new Map,ri=new Map,ii=new Map,_t=0,yo=0,Vr=0,kc="",Jr=0,mt=!1,Kr=0,Zr=0,In=-1,vc=!1,Qr=0,ei=!1,qt=0,Rt=!1,Xt=0,Ct=0,ze=!1,at="",$o=0,sn=0,ti="",jn=0,Dn=0,ni="",xt=!1,Sc=!1,vo=new Map,So=new Set,wo=null,gc=!1,po=0,hh=!1,Pe="plan",ai=0,we=!1,rn=0,Vt=null,Ec=null,Tc=null,bo=0,_s=null;function ys(t,e){t===kc?(Jr++,Zo().DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${Jr})${p.reset}
|
|
725
|
+
`)):(kc=t,Jr=1,F(`${e} \u26A0 ${t}${p.reset}`))}var si=[];function Mx(t){si.push(t.trim())}function Lx(){return si.length===0?null:si.splice(0,si.length).join(`
|
|
726
|
+
`)}function ho(t,e,s,n){if(!we)return null;let o=Pe;Pe=t,ai=0,Vt=$c(t,_s),qt=0,Rt=!1,Xt=0,Ct=0,on.clear(),zt.clear(),qn.clear(),ri.clear(),ii.clear(),Mc.clear(),xo.clear(),Lc.clear(),ko.clear(),Nc.clear(),Pc.clear();let r;if(t==="implement")Ec=e?.slice(0,800)||"",r=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
|
|
727
|
+
${Ec}
|
|
695
728
|
|
|
696
|
-
Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`;else if(t==="verify"){
|
|
729
|
+
Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`;else if(t==="verify"){Tc=e?.slice(0,500)||"";let i=s?[...s].join(", "):"none";r=`[PHASE: VERIFICATION] Implementation complete. Verify the changes:
|
|
697
730
|
1. Read each modified file and confirm changes are correct
|
|
698
731
|
2. If test command exists (npm test / pytest): run it
|
|
699
732
|
3. If linter exists: run it
|
|
@@ -701,18 +734,18 @@ Now implement the fix/changes. Do not investigate further \u2014 edit files dire
|
|
|
701
734
|
Report PASS (all good) or FAIL (list specific issues).
|
|
702
735
|
|
|
703
736
|
Files modified: ${i}
|
|
704
|
-
Summary: ${
|
|
737
|
+
Summary: ${Tc}`}return F(`${p.cyan} \u21B3 Phase transition: ${o} \u2192 ${t} (model: ${Vt||"default"})${p.reset}`),r?{role:"user",content:r}:null}function Px(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,n=!t||t==="auto"?null:t,o=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
705
738
|
`];n?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),o.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files): paste the COMPLETE file content in a fenced code block in your TEXT RESPONSE \u2014 writing a file with a tool does NOT make it visible. The fenced code block MUST appear in your response, not just via write_file."),o.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),o.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),o.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),o.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),o.push(' \u2022 For Makefiles, paste the COMPLETE Makefile code DIRECTLY in your text response \u2014 every target, recipe, dependency, and .PHONY line. Writing the Makefile with a tool does NOT count as showing it. The Makefile MUST appear verbatim in your chat text as a code block, even if you also wrote it to a file. Never describe structure without showing the actual code. CRITICAL: use EXACTLY the command specified \u2014 if the task says "runs jest", write "jest" in the recipe, NEVER "npm test". npm test is NOT jest. Recipes need real TAB indentation. ONE .PHONY line listing ALL phony targets.'),o.push(" \u2022 For dataclasses, paste the COMPLETE dataclass code DIRECTLY in your text response \u2014 @dataclass decorator, all fields with types and defaults, full __post_init__ validation. Writing the file with a tool does NOT count as showing the code. The code MUST appear verbatim in your chat text, even if you also wrote it to a file."),o.push(" \u2022 For cron expressions, re-read the exact time boundaries in the task before writing. If asked for 8-18h, the range is 8,9,...,18 \u2014 write exactly what was asked, not an approximation."),o.push(' \u2022 When a task explicitly specifies a tool (e.g., "use tsc"), NEVER mention alternatives (e.g., "swc build") \u2014 use exactly what was requested.'),o.push(' \u2022 In Makefile prerequisites, NEVER use shell glob patterns like src/**/*.ts \u2014 make does not expand these natively. Keep prerequisite lists explicit or omit them. When a Makefile target says "runs jest", call jest directly in the recipe (not npm test).'),o.push(" \u2022 For bash in-place text replacements with backups: use ONLY ONE backup method \u2014 either sed -i.bak (let sed create the backup) OR cp file file.bak followed by sed -i (no extension). Never use both cp and sed -i.bak together \u2014 that produces redundant double backups (file.bak and file.bak.bak)."),o.push(" \u2022 For iterative array-flattening (flattenDeep): use push() and reverse() at the end \u2014 NEVER unshift(). unshift is O(n) per call making the whole function O(n^2). The iterative version MUST use a loop (while/for) and an explicit stack array \u2014 zero recursive calls. If a function calls itself, it is recursive regardless of its name. Never label a recursive function as iterative."),o.push(" \u2022 FORBIDDEN: when refactoring callbacks to async/await, NEVER write try { ... } catch(e) { throw e } \u2014 this is an explicit anti-pattern. WRONG: async function f() { try { const d = await readFile(..); await writeFile(.., d); } catch(e) { throw e; } } \u2014 RIGHT: async function f() { const d = await readFile(..); await writeFile(.., d); } \u2014 omit the try-catch entirely, let rejections propagate."),o.push(' \u2022 Docker HEALTHCHECK: always include --start-period=30s (or appropriate startup time) so the container has time to initialise before failures are counted. Also note that curl may not be available in minimal Node.js images \u2014 offer wget or "node -e" as alternatives.'),o.push(' \u2022 When fixing a bash word-splitting bug like "for f in $(ls *.txt)": replace the entire $(ls *.txt) with a bare glob directly \u2014 "for f in *.txt". The fix is eliminating the ls command and $() subshell entirely. Emphasise this in the explanation: the glob in the for loop prevents word splitting because the shell expands the glob into separate words before the loop \u2014 there is no subshell output to split. CRITICAL: NEVER suggest "ls -N" or any ls variant as a fix \u2014 ls -N outputs filenames one per line, but word splitting still occurs on each line when used in a subshell expansion. The only correct fix is the bare glob pattern.');let r=e||"English";o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let i=s||"English";return o.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),n&&o.push(`
|
|
706
739
|
This is a hard requirement. Always respond in ${n}. Do NOT switch to any other language \u2014 even if the user writes to you in German, French, or any other language, your reply MUST be in ${n}.`),o.join(`
|
|
707
740
|
`)+`
|
|
708
741
|
|
|
709
|
-
`}function
|
|
742
|
+
`}function Ix(){if(bs!==null)return bs;try{let e=ix().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:rx(r.id,o.name),name:r.name})));if(e.length<2)return bs="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
|
|
710
743
|
# Sub-Agent Model Routing
|
|
711
744
|
|
|
712
745
|
`;n+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',n+=`| Model | Tier | Auto-assigned for |
|
|
713
746
|
|---|---|---|
|
|
714
747
|
`;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
|
|
715
|
-
`;return
|
|
748
|
+
`;return bs=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),bs="",""}}var Rc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function jx(t){let e=t.indexOf(Rc);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+Rc.length).trimStart()}}async function Cc(){let t=await wh()+":"+At();if(mo!==null&&t===_c)return mo;let e=await v_(process.cwd()),s=I_(),n=ex(),o=_o()?Y_():"",r=Px(),i=j_(),a=cx(At());return mo=`${a?`## Model Briefing
|
|
716
749
|
${a}
|
|
717
750
|
|
|
718
751
|
---
|
|
@@ -733,18 +766,19 @@ ${o}
|
|
|
733
766
|
${r?`${r}
|
|
734
767
|
`:""}${i?`${i}
|
|
735
768
|
|
|
736
|
-
`:""}${
|
|
769
|
+
`:""}${H_()?`# YOLO Mode \u2014 Auto-Execute
|
|
737
770
|
|
|
738
771
|
You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
|
|
739
772
|
- NEVER ask for confirmation \u2014 just execute tasks directly
|
|
740
773
|
- NEVER end responses with questions like "Soll ich...?", "M\xF6chtest du...?", "Shall I...?"
|
|
741
774
|
- When you have enough information, implement the fix immediately \u2014 do not propose or ask
|
|
742
775
|
- If something is ambiguous, make a reasonable assumption and state it, then proceed
|
|
743
|
-
- OVERRIDE "simple questions": If the user pastes any server error
|
|
776
|
+
- OVERRIDE "simple questions": If the user pastes any server error message, SSH investigate FIRST \u2014 NEVER answer from training knowledge alone
|
|
744
777
|
- **Inline code tasks**: If the prompt contains a code snippet and asks you to modify/add to/improve it, answer DIRECTLY with the improved code \u2014 do NOT search for files. The snippet is self-contained
|
|
745
778
|
- After identifying root cause via SSH: IMMEDIATELY fix it (edit file + restart service). Do NOT write "Empfohlene L\xF6sungen" or ask "M\xF6chten Sie...?" \u2014 just execute the fix now.
|
|
746
779
|
|
|
747
780
|
`:""}
|
|
781
|
+
<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->
|
|
748
782
|
|
|
749
783
|
# Plan Mode
|
|
750
784
|
|
|
@@ -958,7 +992,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
|
|
|
958
992
|
- Instead: use bash with inline node -e '...' for quick one-off checks.
|
|
959
993
|
- If the test is worth keeping, write it to tests/ with a proper name.
|
|
960
994
|
- Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
|
|
961
|
-
${
|
|
995
|
+
${Ix()}
|
|
962
996
|
|
|
963
997
|
# Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
|
|
964
998
|
|
|
@@ -1149,67 +1183,70 @@ class ErrorBoundary extends React.Component {
|
|
|
1149
1183
|
- Use migrations for schema changes, never manual ALTER TABLE
|
|
1150
1184
|
- Add database-level constraints (unique, foreign key, check) not just app-level
|
|
1151
1185
|
|
|
1152
|
-
`,
|
|
1153
|
-
`):[]).filter(d=>{let f=d.split(".").pop();return r.has(f)});if(i.length<3)return null;let a={};for(let d of i){let f=d.split(".").pop();a[f]=(a[f]||0)+1}let l=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,u=
|
|
1154
|
-
\u{1F4E6} ${h}${
|
|
1155
|
-
${p.dim} ${a}${p.reset}`),c>=30&&process.stdout.isTTY){let l=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${c}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${c}s`;
|
|
1156
|
-
`),f==="")return a({action:"quit"});let
|
|
1186
|
+
`,_c=t,mo}function _h(){Nc.clear(),Mc.clear(),xo.clear(),Lc.clear(),ko.clear(),on.clear(),zt.clear(),Pc.clear(),Pn.clear(),qn.clear(),ri.clear(),ii.clear(),_t=0,yo=0,Vr=0,mt=!1,Zr=0,In=-1,vc=!1,Qr=0,ei=!1,qt=0,Rt=!1,Xt=0,Ct=0,ze=!1,at="",$o=0,ti="",jn=0,ni="",Dn=0,xt=!1,Sc=!1,Pe="plan",ai=0,we=!1,Vt=null,Ec=null,Tc=null,bo=0,rn=0,_s=null,vo.clear(),So.clear(),kc="",Jr=0}function Dx(){q=[],wo=null,_h();try{let{resetCompactionFailures:t}=ba();t()}catch{}}function qx(){q.length>fh&&q.splice(0,q.length-fh)}function Fx(){return q.length}function Bx(){return q}function Wx(t){q=t}async function Ux(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),n=(d,f)=>new Promise(h=>{t(d,f,{cwd:s,timeout:3e3},(g,m)=>{h(g?"":(m||"").trim())})}),[o]=await Promise.all([n("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(o?o.split(`
|
|
1187
|
+
`):[]).filter(d=>{let f=d.split(".").pop();return r.has(f)});if(i.length<3)return null;let a={};for(let d of i){let f=d.split(".").pop();a[f]=(a[f]||0)+1}let l=` \u{1F4C1} ${Object.entries(a).sort((d,f)=>f[1]-d[1]).slice(0,4).map(([d,f])=>`${f} .${d}`).join(" \xB7 ")}`,u=Oc.join(s,"package.json");if(e.existsSync(u))try{let d=JSON.parse(e.readFileSync(u,"utf-8")),f=Object.keys({...d.dependencies||{},...d.devDependencies||{}});if(f.length>0){let h=f.slice(0,5).join(" \xB7 "),g=f.length>5?` +${f.length-5}`:"";l+=`
|
|
1188
|
+
\u{1F4E6} ${h}${g}`}}catch{}return l}function Hx(t){if(process.platform==="darwin")try{let{execFileSync:e}=require("child_process");e("osascript",["-e",`display notification "${t.replace(/"/g,'\\"')}" with title "nex-code"`],{timeout:3e3,stdio:"ignore"})}catch{}}function Fe(t,e,s,n,o,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((l,u)=>l+u,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,c=0;if(o){let l=Date.now()-o;c=Math.round(l/1e3),a+=c>=60?` \xB7 ${Math.floor(c/60)}m ${c%60}s`:` \xB7 ${c}s`}if(s.size>0&&(a+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
|
|
1189
|
+
${p.dim} ${a}${p.reset}`),c>=30&&process.stdout.isTTY){let l=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${c}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${c}s`;Hx(l)}if(So.size>0&&vo.size>0)for(let l of So){let u=vo.get(l);u&&console.log(`${p.dim} \u2714 task #${l} auto-matched: ${u.slice(0,60)}${p.reset}`)}s.size>0?console.log(`${p.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${p.reset}`):!r&&n.size>=5&&s.size===0&&t>=3?console.log(`${p.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${p.reset}`):n.size>0&&t>=2&&console.log(`${p.dim} \u{1F4A1} /save \xB7 /clear${p.reset}`)}async function Yx(){if(!process.stdout.isTTY)return{action:"quit"};let t=ws(),e=At(),s=oi.fast?.[t],n=oi.strong?.[t],o=s&&s!==e,r=n&&n!==e&&n!==s,i=[];i.push({key:"r",label:`Retry with current model ${p.dim}(${e})${p.reset}`}),o&&i.push({key:"f",label:`Switch to ${p.bold}${s}${p.reset} ${p.dim}\u2014 fast, low latency${p.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${p.bold}${n}${p.reset} ${p.dim}\u2014 reliable tool-calling, medium speed${p.reset}`,model:n}),i.push({key:"q",label:`${p.dim}Quit${p.reset}`}),console.log(),console.log(`${p.yellow} Stream stale \u2014 all retries exhausted.${p.reset} What would you like to do?`);for(let a of i)console.log(` ${p.cyan}[${a.key}]${p.reset} ${a.label}`);return process.stdout.write(` ${p.yellow}> ${p.reset}`),new Promise(a=>{let c=process.stdin,l=c.isRaw;c.setRawMode(!0),c.resume(),c.setEncoding("utf8");let u=!1,d=f=>{if(u)return;u=!0,c.removeListener("data",d),c.setRawMode(l||!1),c.pause();let h=f.toLowerCase().trim();if(process.stdout.write(`${h}
|
|
1190
|
+
`),f==="")return a({action:"quit"});let g=i.find(m=>m.key===h);!g||g.key==="q"||!g.model&&g.key!=="r"?a({action:"quit"}):g.key==="r"?a({action:"retry"}):a({action:"switch",model:g.model,provider:t})};c.on("data",d)})}var Ft=null;async function Gx(t,e=null,s={}){let n=ax(At());dh=n.staleWarn,fc=n.staleAbort,Ft=e;let o=t;wo&&typeof t=="string"&&(o=`${wo}
|
|
1157
1191
|
|
|
1158
|
-
${t}`,
|
|
1159
|
-
`+
|
|
1160
|
-
`)}catch(be){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",be.message)}let
|
|
1161
|
-
${
|
|
1192
|
+
${t}`,wo=null);let r=yh(o);q.push({role:"user",content:r}),qx();let i=s.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",a=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:be,runOrchestrated:ke}=nh(),Ae=be(typeof t=="string"?t:"");if(i&&Ae.isComplex&&Ae.estimatedGoals>=a)return console.log(`${p.yellow}\u26A1 Auto-orchestrate: ${Ae.estimatedGoals} goals \u2192 parallel agents${p.reset}`),await ke(t,{orchestratorModel:s.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:s.model});Ae.isComplex&&process.stdout.isTTY&&console.log(`${p.dim}Hint: ~${Ae.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${p.reset}`)}catch{}let{setOnChange:c}=$a(),l=null,u=0;c((be,ke)=>{be==="create"?(l&&l.stop(),l=new y_(ke.name,ke.tasks),l.setStats({tokens:u}),l.start()):be==="update"&&l?l.updateTask(ke.id,ke.status):be==="clear"&&l&&(l.stop(),l=null)});let d=await Cc(),f=d;try{let{getBrainContext:be}=Ma(),ke=await be(t);ke&&(f=d+`
|
|
1193
|
+
`+ke+`
|
|
1194
|
+
`)}catch(be){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",be.message)}let g=sx(typeof t=="string"?t:"");if(g.length>0){let be=g.map(ke=>`[Triggered: ${ke.name}]
|
|
1195
|
+
${ke.instructions}`).join(`
|
|
1162
1196
|
`);f+=`
|
|
1163
1197
|
`+be+`
|
|
1164
|
-
`}let
|
|
1165
|
-
${
|
|
1166
|
-
`),
|
|
1167
|
-
`+
|
|
1168
|
-
`));let
|
|
1198
|
+
`}let m=[{role:"system",content:f},...q];b_(At());let b=new $s(rc());b.start();let x=q.length===1,j=x?Ux().catch(()=>null):Promise.resolve(null),G=x?D_(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),L=Qe(),[{messages:P,compressed:C,compacted:Z,tokensRemoved:Y},ue,ie]=await Promise.all([S_(m,L),j,G]),se=Tt(m,L);if(b.stop(),ue&&console.log(`${p.dim}${ue}${p.reset}`),Z)console.log(`${p.dim} [context compacted \u2014 summary (~${Y} tokens freed)]${p.reset}`);else if(C){let be=se.limit>0?Math.round(Y/se.limit*100):0;F(`${p.dim} [context compressed \u2014 ~${Y} tokens freed (${be}%)]${p.reset}`)}se.percentage>85&&F(`${p.yellow} \u26A0 Context ${Math.round(se.percentage)}% used (${Math.round(100-se.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${p.reset}`);let T=P;if(ie&&x&&(T=[T[0],{role:"user",content:`[Server probe at task start]
|
|
1199
|
+
${ie}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...T.slice(1)]),x){let be=q_(typeof t=="string"?t:"");be&&(T=[T[0],{role:"user",content:be.user},{role:"assistant",content:be.assistant},...T.slice(1)])}if(Tt(T,Qe()).percentage>=65){let{messages:ke,tokensRemoved:Ae}=jt(T,Qe());Ae>0&&(T=ke,console.log(`${p.dim} [pre-flight compress \u2014 ${Ae} tokens freed, now ${Math.round(Tt(T,Qe()).percentage)}% used]${p.reset}`))}let Te=0,K=0,X=0,me=0,fe=0,$e=9,pe=0,Re=(()=>{let be=q.find(ke=>ke.role==="user");return typeof be?.content=="string"?be.content:""})(),w=/set_reminder|google.?auth|cron:|api\.log|swarm.{0,30}(agent|crash|gecrasht|abgestürzt|fail)|agent.{0,30}(gecrasht|abgestürzt|crashed|fail)|server.{0,30}(passiert|fehler|crash|problem)|am.server/i.test(Re),I=0;if(!ze){let be=q.filter(Ae=>Ae.role==="user"||Ae.role==="tool").map(Ae=>typeof Ae.content=="string"?Ae.content:"").join(`
|
|
1200
|
+
`),ke=hc(be);ke&&(ze=!0,at=ke.slice(0,120),F(`${p.yellow} \u26A1 Root cause in briefing: ${at} \u2014 fix phase active from start (read budget: 3)${p.reset}`))}!ze&&!xt&&/\b(create|build|generate|implement|write|make|develop|set\s*up|scaffold|add)\b.{0,80}\b(app|component|page|game|api|backend|frontend|server|service|module|class|function|feature|project|system|bot|script|tool)\b/i.test(Re)&&(xt=!0,F(`${p.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${p.reset}`)),q.length<=1&&!s.skipPhaseRouting&&(we=L_(),we&&(_s=M_(Re)?.id||"coding",Pe="plan",Vt=$c("plan",_s),ai=0,bo=0,rn=0,process.stdout.isTTY&&console.log(`${p.dim} \u21B3 Phase routing: plan(${Vt||"default"}) \u2192 implement \u2192 verify${p.reset}`),F(`${p.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${Vt||"default model"} (category: ${_s})${p.reset}`)));let v=0,O=new Map,R=new Set,k=new Set,H=Date.now(),Se=new __(lx),xe=Pc,ge=s.skillLoop?10:1,fi=3*ge,Dh=5*ge,Yc=Nc,qh=5*ge,Fh=8*ge,Bh=Mc,Wh=(we?6:4)*ge,Uh=(we?10:7)*ge,pi=xo,Hh=(we?5:3)*ge,To=(we?8:5)*ge,Yh=Lc,Gh=(we?4:3)*ge,Kh=(we?6:4)*ge,zh=3*ge,Xh=4*ge,Fn=on,Vh=(we?3:2)*ge,Jh=(we?5:3)*ge,Bn=(we?6:4)*ge,Zh=25,an=0,Qh=6*ge,em=10*ge,cn=0,Gc=5*ge,ln=0,tm=2*ge,nm=3,hi=0,vs=10,sm=16,Kc=s.skillLoop?999:n.investigationCap,We,Ot=s.maxIterations||(we?Mn(Pe):bc),mi=0,zc=3,gi=!1,Ro=0;e:for(;;){for(gi=!1,We=0;We<Ot&&!zr()?.aborted;We++){{let $=Qe(),y=Tt(T,$),ee=v===0?65:78;if(y.percentage>=ee){if(R.size>0||we&&Pe!=="plan"){let Q=T_(q,{filesModified:R,currentPhase:we?Pe:null});if(Q){let D=T.findIndex(N=>N._progressSnapshot);D!==-1&&T.splice(D,1);let le=T.findIndex(N=>N.role==="system");T.splice(le+1,0,Q)}}let{messages:S,tokensRemoved:A}=jt(T,$,v===0);if(A>0&&(T=S,A>50&&console.log(`${p.dim} [auto-compressed \u2014 ~${A} tokens freed, now ${Math.round(Tt(T,$).percentage)}%]${p.reset}`),xt&&R.size>=3)){let Q=[...R].map(le=>le.split("/").pop()).slice(0,10).join(", "),D={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${R.size} files: ${Q}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};T.push(D)}}}if(mt&&!ze&&$o<2){$o++;let $={role:"user",content:"[SYSTEM] SSH paused \u2014 you have made many consecutive SSH calls. Synthesize your findings so far: summarize what you learned and what the likely issue is. After your synthesis, SSH will be available again for targeted follow-up commands."};T.push($),q.push($),F(`${p.yellow} \u26A0 Pre-call SSH-blocked nudge #${$o} injected \u2014 model told to synthesize${p.reset}`)}mt||($o=0);let ke=!0;v>0&&X_();let Ae=null;if(l&&l.isActive())l._paused&&l.resume();else if(!l){let $,y=V_();if(y&&y.total>1){let ee=y.description.length>40?y.description.slice(0,37)+"\u2026":y.description;$=`Plan step ${y.current}/${y.total}: ${ee}`}else $=v>0?`${rc()} (step ${v+1})`:rc();Ae=new $s($),Ae.start()}let Wn=!0,lt="",Un=!1,Ve=new J_,Nt,yi=Date.now(),Co=!1,$i=new AbortController,Xc=setInterval(()=>{let $=Date.now()-yi;if($>=fc)Ve._clearCursorLine(),F(`${p.yellow} \u26A0 Stream stale for ${Math.round($/1e3)}s \u2014 aborting and retrying${p.reset}`),$i.abort();else if($>=dh&&!Co){Co=!0,Ve._clearCursorLine();let y=oi.fast?.[ws()],ee=X>0?` (retry ${X+1}/${Gr})`:"",S=Math.round((fc-$)/1e3);F(`${p.yellow} \u26A0 No tokens received for ${Math.round($/1e3)}s \u2014 waiting...${ee}${p.reset}`),y&&y!==At()?console.log(`${p.dim} \u{1F4A1} Will auto-switch to ${y} in ~${S}s if no tokens arrive${p.reset}`):console.log(`${p.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${S}s${p.reset}`)}},5e3),gt="",Bt=null;try{let $=$h(Qe()),y=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),ee=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),S;_o()?S=$.filter(D=>gh.has(D.function.name)):we&&Pe==="plan"?S=$.filter(D=>y.has(D.function.name)):we&&Pe==="verify"?S=$.filter(D=>ee.has(D.function.name)):S=$;let A=zr(),Q=new AbortController;A&&A.addEventListener("abort",()=>Q.abort(),{once:!0}),$i.signal.addEventListener("abort",()=>Q.abort(),{once:!0}),Nt=await sh(T,S,{signal:Q.signal,...Vt?{model:Vt}:{},onThinkingToken:()=>{yi=Date.now(),Co=!1,Ft?.onThinkingToken&&Ft.onThinkingToken()},onToken:D=>{if(yi=Date.now(),Co=!1,Ft?.onToken){Ft.onToken(D),lt+=D;return}if(lt+=D,!Un&<.length>400&<.length%250<D.length+1){let le=wc(lt,3);le.truncated&&(Un=!0,Ve._clearCursorLine?.(),F(`${p.yellow} \u26A0 LLM stream loop detected (${le.repeatCount}\xD7 repeated) \u2014 suppressing display${p.reset}`))}Un||(gt+=D,process.stdout.isTTY?Bt||(Bt=setTimeout(()=>{gt&&Ve&&Ve.push(gt),gt="",Bt=null},50)):(Ve.push(gt),gt=""),Wn&&(l&&!l._paused?l.pause():Ae&&Ae.stop(),ke||(ke=!0),Ve.startCursor(),Wn=!1))}})}catch($){if(clearInterval(Xc),Bt&&(clearTimeout(Bt),Bt=null),gt&&Ve&&(Ve.push(gt),gt=""),l&&!l._paused&&l.pause(),Ae&&Ae.stop(),Ve.stopCursor(),$i.signal.aborted&&!zr()?.aborted){if(X++,X>Gr){if(me<1){me++,ys("Stale retries exhausted \u2014 last-resort force-compress...",p.yellow);let le=Qe(),{messages:N,tokensRemoved:B}=jt(T,le);T=N,B>50&&F(`${p.dim} [force-compressed \u2014 ~${B} tokens freed]${p.reset}`),X=0,We--;continue}l&&(l.stop(),l=null);let D=await Yx();if(D.action==="quit"){c(null),Fe(v,O,R,k,H),qe(q);break}D.action==="switch"&&(lh(`${D.provider}:${D.model}`),console.log(`${p.green} \u2713 Switched to ${D.provider}:${D.model}${p.reset}`)),X=0,We--;continue}let A=X===1?3e3:5e3;if(X>=1&&pe<1){pe++,ys(`Stale retry ${X}/${Gr} \u2014 force-compressing before retry...`,p.yellow);let D=Qe(),{messages:le,tokensRemoved:N}=jt(T,D,!0);if(T=le,N>0&&N>50&&F(`${p.dim} [force-compressed \u2014 ~${N} tokens freed]${p.reset}`),Ex){let B=oi.fast?.[ws()];B&&B!==At()&&(lh(`${ws()}:${B}`),console.log(`${p.cyan} \u26A1 Auto-switched to ${B} to avoid further stale timeouts${p.reset}`),console.log(`${p.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${p.reset}`))}}else F(`${p.yellow} \u26A0 Stale retry ${X}/${Gr} \u2014 retrying in ${A/1e3}s...${p.reset}`);let Q=new $s(`Waiting ${A/1e3}s before retry...`);Q.start(),await new Promise(D=>setTimeout(D,A)),Q.stop(),We--;continue}if($.name==="AbortError"||$.name==="CanceledError"||$.message?.includes("canceled")||$.message?.includes("aborted")){l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H),qe(q);break}let y=$.message;if($.code==="ECONNREFUSED"||$.message.includes("ECONNREFUSED"))y="Connection refused \u2014 please check your internet connection or API endpoint";else if($.code==="ENOTFOUND"||$.message.includes("ENOTFOUND"))y="Network error \u2014 could not reach the API server. Please check your connection";else if($.code==="ETIMEDOUT"||$.message.includes("timeout"))y="Request timed out \u2014 the API server took too long to respond. Please try again";else if($.message.includes("401")||$.message.includes("Unauthorized"))y="Authentication failed \u2014 please check your API key in the .env file";else if($.message.includes("403")||$.message.includes("Forbidden"))y="Access denied \u2014 your API key may not have permission for this model";else if($.message.includes("404")){y=`Model not found (404): ${At?At():"unknown"} \u2014 check your .env MODEL setting or run /models to list available models`,console.log(`${p.red} \u2717 ${y}${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H),qe(q);break}else if($.message.includes("400")){if(me<3&&fe<$e){me++,fe++;let A=v===0&&me===1,Q=A||me===3||pe>0;if(A){me=3;let B=$.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);ys(`Bad request (400) \u2014 ${B||"system prompt too large"}, compressing...`,p.yellow)}else ys(Q?`Bad request (400) \u2014 nuclear compression (attempt ${me}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${me}/3)`,p.yellow);let D=Qe(),{messages:le,tokensRemoved:N}=jt(T,D,Q);T=le,N>50&&F(`${p.dim} [force-compressed \u2014 ~${N} tokens freed]${p.reset}`),We--;continue}{let A=T.find(U=>U.role==="system"),Q=T.find(U=>U.role==="user"&&!String(U.content).startsWith("[SYSTEM")&&!String(U.content).startsWith("BLOCKED:")),D=[A,Q].filter(Boolean),{getUsage:le}=It(),N=It().estimateMessagesTokens(D),B=It().estimateMessagesTokens(T);if(N<B){let U=[],V=q.filter(ne=>ne.role==="assistant"&&typeof ne.content=="string"&&ne.content.trim().length>30).slice(-5).map(ne=>ne.content.trim().slice(0,300).replace(/\n+/g," "));V.length>0&&U.push(`Key findings:
|
|
1201
|
+
`+V.map(ne=>`- ${ne}`).join(`
|
|
1202
|
+
`));let J=q.filter(ne=>ne.role==="tool"&&typeof ne.content=="string"&&!ne.content.startsWith("BLOCKED:")&&ne.content.trim().length>10).slice(-5).map(ne=>ne.content.trim().split(`
|
|
1169
1203
|
`).slice(0,8).join(`
|
|
1170
|
-
`).slice(0,500));if(
|
|
1171
|
-
`+
|
|
1172
|
-
`)),
|
|
1173
|
-
${JSON.stringify(
|
|
1174
|
-
${
|
|
1204
|
+
`).slice(0,500));if(J.length>0&&U.push(`Tool results summary:
|
|
1205
|
+
`+J.map(ne=>`- ${ne}`).join(`
|
|
1206
|
+
`)),R.size>0){let ne=[...R].map(Me=>Me.split("/").slice(-2).join("/")).join(", ");U.unshift(`Already modified: ${ne} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(k.size>0){let ne=[...k].map(Me=>Me.split("/").slice(-2).join("/")).join(", ");U.push(`Files already investigated: ${ne}`)}let oe=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(oe,JSON.stringify({filesWritten:[...R].map(ne=>ne.split("/").slice(-2).join("/")),filesRead:[...k].map(ne=>ne.split("/").slice(-2).join("/")),isCreationTask:xt,wipeNumber:yo+1,timestamp:Date.now()},null,2)),U.push(`Session checkpoint: ${oe} \u2014 read it for exact file list`)}catch{}let he=0;{let Me=((typeof Q?.content=="string"?Q.content:Array.isArray(Q?.content)?Q.content.filter(Ye=>Ye.type==="text").map(Ye=>Ye.text).join(" "):"").match(/(?:^|\s)([\w./\-]+\.(?:js|ts|jsx|tsx|py|json|yml|yaml|sh|css|scss|html|md|go|rs|java|rb|php))/gm)||[]).map(Ye=>Ye.trim()).filter(Boolean),Ue=[...R],yt=Me.filter(Ye=>!Ue.some(_i=>_i.endsWith(Ye)||Ye.endsWith(_i.split("/").pop())));he=yt.length;let ut=[...q].reverse().find(Ye=>Ye.role==="tool"&&typeof Ye.content=="string"&&!Ye.content.startsWith("BLOCKED:")&&Ye.content.length>5),Ut={completed:Ue.map(Ye=>Ye.split("/").slice(-2).join("/")),pending:yt.length>0?yt:Ue.length===0?["(task files not yet identified)"]:[],lastEdit:ut?ut.content.trim().slice(0,120):null};(Ut.completed.length>0||Ut.pending.length>0)&&U.unshift(`Work manifest:
|
|
1207
|
+
${JSON.stringify(Ut,null,2)}`)}if(U.length>0){let ne={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
|
|
1208
|
+
${U.join(`
|
|
1175
1209
|
`)}
|
|
1176
|
-
Continue implementing the fixes based on these findings.`};
|
|
1177
|
-
Files modified so far: ${[...
|
|
1210
|
+
Continue implementing the fixes based on these findings.`};D.push(ne)}if(yo>=3){let ne=R.size>0?`
|
|
1211
|
+
Files modified so far: ${[...R].map(Me=>Me.split("/").slice(-1)[0]).join(", ")}`:"";F(`${p.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${p.reset}`),console.log(`${p.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${ne?p.dim+ne:""}${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);break}T=D,yo++,In=12+Math.min(he*3,15),vc=!0,Qr=R.size,ei=!1,_t=0,I=0;for(let[ne,Me]of on){let Ue=Me?.count??Me??0;mc(on,ne,Ue>=2?Ue:1)}for(let[ne]of zt)Dt(on,ne)<2&&zt.delete(ne);Pn.clear(),qn.clear(),xt&&Ct>0&&(Rt=!0,F(`${p.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Ct} edits already made)${p.reset}`));for(let[ne]of xo)mc(xo,ne,To-1);if(ys(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${B-N} tokens freed)`,p.yellow),yo>=1){let ne=[...on.entries()].filter(([,ut])=>ut>=Bn).map(([ut])=>ut.split("/").slice(-1)[0]),Me=ne.length>0?`
|
|
1178
1212
|
|
|
1179
|
-
Files already at read cap \u2014 use grep_search instead: ${ne.join(", ")}`:"",
|
|
1180
|
-
Use /undo to revert changes made during this session.${p.reset}`),l&&(l.stop(),l=null),c(null),
|
|
1181
|
-
${
|
|
1213
|
+
Files already at read cap \u2014 use grep_search instead: ${ne.join(", ")}`:"",yt={role:"user",content:mt&&!ze?"[SYSTEM] Context was compressed. SSH is currently unavailable \u2014 do not read more local files. Summarize what you found and ask the user for the server output you need.":`[SYSTEM] Context was compressed. Use the findings above to implement your fix. If you need to re-read a file, use line_start/line_end for the specific section.${Me}`};q.push(yt),T.push(yt)}me=0,We--;continue}}y="Context too large to compress \u2014 use /clear to start fresh"}else $.message.includes("500")||$.message.includes("502")||$.message.includes("503")||$.message.includes("504")?y="API server error \u2014 the provider is experiencing issues. Please try again in a moment":($.message.includes("fetch failed")||$.message.includes("fetch"))&&(y="Network request failed \u2014 please check your internet connection");if(console.log(`${p.red} \u2717 ${y}${p.reset}`),$.message.includes("429")){if(Te++,Te>uc){console.log(`${p.red} Rate limit: max retries (${uc}) exceeded. Try again later or use /budget to check your limits.${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H),qe(q);break}let A=Math.min(1e4*Math.pow(2,Te-1),12e4),Q=new $s(`Rate limit \u2014 waiting ${Math.round(A/1e3)}s (retry ${Te}/${uc})`);Q.start(),await new Promise(D=>setTimeout(D,A)),Q.stop();continue}let ee=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return Ge().getActiveProviderName()==="ollama"}catch{return!1}})();if($.message.includes("socket disconnected")||$.message.includes("TLS")||$.message.includes("ECONNRESET")||$.message.includes("ECONNABORTED")||$.message.includes("ETIMEDOUT")||ee&&($.message.includes("500")||$.message.includes("502")||$.message.includes("503")||$.message.includes("504")||$.message.includes("401")||$.message.includes("Unauthorized"))||$.code==="ECONNRESET"||$.code==="ECONNABORTED"){if(K++,K>dc){console.log(`${p.red} Network error: max retries (${dc}) exceeded. Check your connection and try again.
|
|
1214
|
+
Use /undo to revert changes made during this session.${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H),qe(q);break}let A=Math.min(2e3*Math.pow(2,K-1),3e4),Q=new $s(`API temporarily unavailable \u2014 retrying in ${Math.round(A/1e3)}s (${K}/${dc}). Your changes are safe.`);Q.start(),await new Promise(D=>setTimeout(D,A)),Q.stop(),We--;continue}l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H),qe(q);break}if(clearInterval(Xc),Te=0,K=0,Wn&&(l&&!l._paused&&l.pause(),Ae&&Ae.stop()),Bt&&(clearTimeout(Bt),Bt=null),gt&&Ve&&(Ve.push(gt),gt=""),lt&&Ve.flush(),K=0,X=0,Nt&&Nt.usage){let $=Nt.usage.prompt_tokens||0,y=Nt.usage.completion_tokens||0;rh(ws(),At(),$,y),u+=$+y,l&&l.setStats({tokens:u})}else if(Nt&&!Nt.usage){let $=T.map(S=>typeof S.content=="string"?S.content:Array.isArray(S.content)?S.content.map(A=>typeof A=="string"?A:A.text||"").join(""):"").join(" "),y=ah($),ee=ah(Nt.content||lt||"");rh(ws(),At(),y,ee),u+=y+ee,l&&l.setStats({tokens:u})}let{content:Vc,tool_calls:Wt}=Nt,Ao=wc(Vc||""),Jc=Ao.truncated?Ao.text:Vc;Ao.truncated&&F(`${p.yellow} \u26A0 LLM output loop detected (${Ao.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${p.reset}`);let Oo=px(Jc||""),Mt=Oo.truncated?Oo.text:Jc;Oo.truncated&&F(`${p.yellow} \u26A0 LLM output loop detected (${Oo.repeatCount}\xD7 repeated window) \u2014 response truncated${p.reset}`);let wi={role:"assistant",content:Mt||""};if(Wt&&Wt.length>0&&(wi.tool_calls=Wt),q.push(wi),T.push(wi),!ze&&Mt&&Wt&&Wt.length>0){let $=hc(Mt);if($){ze=!0,at=$.slice(0,120),qt=0,Rt=!1,Xt=0,F(`${p.yellow} \u26A1 Root cause in model analysis: ${at} \u2014 fix phase (read budget: 3)${p.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${at}. Read only the file that needs fixing, then edit it. Do not read other files.`};q.push(y),T.push(y)}}if(!Wt||Wt.length===0){let $=(Mt||"").trim().length>0||lt.trim().length>0,y=!1;if(mt&&$&&(Kr>=2?F(`${p.yellow} \u26A0 SSH permanently blocked after ${Kr} storm warnings \u2014 no further SSH calls allowed${p.reset}`):(mt=!1,_t=vs-4,y=!0)),y&&$){let S=(Mt||"").trim();if(S.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(S.slice(-200))){let Q={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};T.push(Q),q.push(Q);continue}}if(!$&&v>0&&We<bc-1){let S={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};T.push(S),q.push(S);continue}let ee=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if($&&We<3&&ee.test((Mt||"").slice(0,600)))if(vc&&In<=0||mt){F(`${p.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${p.reset}`);let A={role:"user",content:"[SYSTEM] Correct \u2014 remote access is currently limited. Summarize what you have found so far and tell the user exactly what specific information (logs, process list, error output) you need from the server to continue."};T.push(A),q.push(A);continue}else{F(`${p.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${p.reset}`);let A={role:"user",content:"[SYSTEM] You have full tool access. Use your tools to investigate and implement the fix directly \u2014 do not say you cannot use tools. If SSH is needed, use a single targeted command that captures the most relevant information rather than multiple sequential calls."};T.push(A),q.push(A);continue}if(s.skillLoop&&$&&v>3&&Ro<5){let S=(Mt||lt||"").toLowerCase();if(/\b(i.ll stop|stop the|stopped|done with|complet|summar|conclud|no more|finish|end of|that.s all|final|wrapped up|no further|mindful of|reached.*limit|tool call limit|at this point|recommend keep)/.test(S.slice(-600))){Ro=(Ro||0)+1,F(`${p.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${Ro}${p.reset}`);let Q={role:"user",content:"[SYSTEM] Do NOT stop. You are in an autonomous experiment loop. The user is away and expects you to keep running experiments indefinitely until they interrupt with Ctrl+C. Start the next experiment NOW: hypothesize a new change, checkpoint, edit, run, measure, keep or revert. Think harder \u2014 try a completely different optimization approach."};T.push(Q),q.push(Q);continue}}if(we&&Pe==="plan"&&rn>=2){F(`${p.cyan} \u21B3 Plan phase: ${rn} consecutive blocks \u2014 auto-advancing to implement${p.reset}`),rn=0;let S=ho("implement","[auto-advance: task only requires direct action]");if(S){q.push(S),T.push(S),We=0,Ot=Mn("implement");continue}}if(we&&$){let S=(Mt||lt||"").trim();if(Pe==="plan"){let A=ho("implement",S);if(A){q.push(A),T.push(A),We=0,Ot=Mn("implement");continue}}else if(Pe==="implement"&&R.size>0){let A=q.find(le=>le.role==="user"),Q=typeof A?.content=="string"?A.content:"",D=ho("verify",S,R,Q);if(D){q.push(D),T.push(D),We=0,Ot=Math.min(Mn("verify")+Math.max(0,(R.size-2)*2),20);continue}}else if(Pe==="verify"){let Q=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(S.slice(0,500));if(Q&&bo<1){bo++;let D={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
|
|
1215
|
+
${S.slice(0,400)}
|
|
1182
1216
|
|
|
1183
|
-
Fix the identified issues. This is the final attempt.`};
|
|
1217
|
+
Fix the identified issues. This is the final attempt.`};Pe="implement",Vt=$c("implement",_s),q.push(D),T.push(D),We=0,Ot=Mn("implement"),F(`${p.yellow} \u21B3 Verify \u2192 implement loop-back #${bo} (issues found)${p.reset}`);continue}if(F(`${p.green} \u2713 Verification phase complete${Q?" (loop-back exhausted)":" (PASS)"}${p.reset}`),!Q){Fe(v,O,R,k,H),qe(q),ic(q);break e}}}if(_o()&&$&&v===0)if(Vr++,Vr>2)F(`${p.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${p.reset}`);else{let S={role:"user",content:`[SYSTEM] You wrote a plan without reading any files. This plan may be based on incorrect assumptions (wrong database type, wrong file structure, etc.).
|
|
1184
1218
|
|
|
1185
|
-
MANDATORY: Use read_file, glob, or grep to investigate the actual codebase first. Read at least the relevant module file and route file before writing the plan.`};q.push(
|
|
1186
|
-
${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${
|
|
1187
|
-
`),oe==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(oe==="e")console.log(`${p.yellow}Type /plan edit to open in editor, or give feedback.${p.reset}`);else if(B()){
|
|
1219
|
+
MANDATORY: Use read_file, glob, or grep to investigate the actual codebase first. Read at least the relevant module file and route file before writing the plan.`};q.push(S),T.push(S),F(`${p.yellow} \u26A0 Plan rejected (${Vr}/2): no files read \u2014 forcing investigation${p.reset}`);continue}if(_o()&&$){let S=(Mt||lt||"").trim();G_(S),Tx(S);let A=K_(S);if(A.length>0){let Q=q.find(B=>B.role==="user"),D=typeof Q?.content=="string"?Q.content.slice(0,120):"Task";z_(D,A);let le=A.length===1?"step":"steps",N=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:B,startExecution:U,setPlanMode:V}=Wr();process.stdout.write(`
|
|
1220
|
+
${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${A.length} ${le})${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.yellow}[E]${p.reset}${p.dim}dit${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let J=process.stdin.isRaw,oe=await new Promise(he=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",ne=>{try{process.stdin.setRawMode(J||!1)}catch{}let Me=ne.toString().toLowerCase()[0]||"\r";he(Me)})});if(process.stdout.write(`
|
|
1221
|
+
`),oe==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(oe==="e")console.log(`${p.yellow}Type /plan edit to open in editor, or give feedback.${p.reset}`);else if(B()){U(),V(!1),xc(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing ${A.length} ${le}...`);let he=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1188
1222
|
|
|
1189
1223
|
Implement the following plan step by step. All tools are now available.
|
|
1190
1224
|
|
|
1191
|
-
${
|
|
1192
|
-
${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${
|
|
1193
|
-
${p.cyan}${p.bold}Plan ready.${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let B=process.stdin.isRaw,
|
|
1194
|
-
`),
|
|
1225
|
+
${S}`;q.push({role:"user",content:he}),T.push({role:"user",content:he}),N=!0}}else console.log(`
|
|
1226
|
+
${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${A.length} ${le} extracted).${p.reset} Type ${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ${p.reset}${p.cyan}/plan edit${p.reset}${p.dim} to review.${p.reset}`);if(N){l&&(l.stop(),l=null),We--;continue}}else{let Q=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:D,startExecution:le,setPlanMode:N}=Wr();process.stdout.write(`
|
|
1227
|
+
${p.cyan}${p.bold}Plan ready.${p.reset} ${p.green}[A]${p.reset}${p.dim}pprove${p.reset} ${p.red}[R]${p.reset}${p.dim}eject${p.reset} ${p.dim}[\u21B5 = approve]:${p.reset} `);let B=process.stdin.isRaw,U=await new Promise(V=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",J=>{try{process.stdin.setRawMode(B||!1)}catch{}V(J.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
|
|
1228
|
+
`),U==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(D()){le(),N(!1),xc(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing...`);let J=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1195
1229
|
|
|
1196
1230
|
Implement the following plan step by step. All tools are now available.
|
|
1197
1231
|
|
|
1198
|
-
${getPlanContent()||
|
|
1199
|
-
${p.cyan}${p.bold}Plan ready.${p.reset} ${p.dim}Type ${p.reset}${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ask follow-up questions to refine.${p.reset}`);if(
|
|
1200
|
-
${F}`),q.push({role:"user",content:A},{role:"assistant",content:F}))}catch{}Be(q),Hp(q);return}k++,oi++,k>=1&&(xe=!1);for(let $ of Bt){let y=$.function.name;N.set(y,(N.get(y)||0)+1)}if(k>=30&&!nh){nh=!0,D(`${p.yellow} \u26A0 Tool budget warning: ${k} tool calls used \u2014 nudging model to wrap up${p.reset}`);let $={role:"user",content:"[SYSTEM] \u26A0 You have used "+k+" tool calls. This is approaching the quality threshold (40). Wrap up NOW: write your final summary and stop. Do NOT run additional verification commands (git status, git diff, git log) \u2014 your changes are already committed and verified. Further tool calls will hurt session quality."};q.push($),_.push($)}let pe=await Promise.all(Bt.map($=>cx($)));{let $=Et(_,Ze()),y=$.percentage,ee=pe.some(F=>F.canExecute&&F.fnName==="read_file"&&!F.args?.line_end),A=pe.filter(F=>F.canExecute&&F.fnName==="read_file"&&F.args?.path&&An(So,F.args.path)>=1&&!F.args?.line_start).map(F=>F.args.path.split("/").slice(-2).join("/")),I=A.length>0;if(y>=70&&ee&&li<70||y>=85&&li<85||I){li=y;let F=y>=85?"URGENT":"WARNING",le;I?(F="WARNING",le=`Full-file read of ${A.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):ee?le=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:le="Use targeted reads (line_start/line_end) to save space.";let j={role:"user",content:`[SYSTEM ${F}] Context ${Math.round(y)}% used (${$.used}/${$.limit} tokens). ${le}`};if(q.push(j),_.push(j),y>=85){let B=I?` (re-read of: ${A.join(", ")})`:"";D(`${p.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${B}${p.reset}`)}}}let mi=new Map;for(let $ of pe){if(!$.canExecute||$.fnName!=="read_file")continue;let y=$.args?.path;if(!y)continue;let ee=An(So,y),A=mi.get(y)||0,I=ee+A,te=$.args?.line_start!=null,F=Nn.get(y)||0,le=F>0,j=2;if(I>=bs){let B=y.split("/").slice(-2).join("/"),W=(jn.get(y)||0)+1;if(jn.set(y,W),W===1)D(`${p.red} \u2716 Blocked: "${B}" read ${I}\xD7 \u2014 hard cap (${bs}) reached${p.reset}`);else if(W===2){D(`${p.red} \u2716 Escalated block: "${B}" \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let z={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${y}") and tried again anyway. This file has reached its read cap (${bs}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};q.push(z),_.push(z)}$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${I}\xD7 (hard cap: ${bs}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:$.callId}}else if(I>=1&&te)if(le&&F<=j){let B=y.split("/").slice(-2).join("/");console.log(`${p.cyan} \u21A9 Targeted re-read: "${B}" (line_start=${$.args.line_start}) \u2014 edit recovery #${F}${p.reset}`),Nn.set(y,F-1)}else if(le&&F>j){let B=y.split("/").slice(-2).join("/");D(`${p.red} \u2716 Edit recovery blocked: "${B}" \u2014 ${j} recovery reads already used. Use grep to find the exact line numbers, then retry.${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${j} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:$.callId}}else{let B=$.args.line_start||1,W=$.args.line_end||B+350,z=tn.get(y)||[],X=!1;for(let[oe,ue]of z){let ne=Math.max(B,oe),Ne=Math.min(W,ue);if(Ne>ne){let Xe=Ne-ne,xt=W-B||1,lt=ue-oe||1,Wt=Xe/lt>=.7&&Xe/xt<.7;if(!(W-B<=Wh)&&(Xe/xt>=.7||Xe/lt>=.7)){let Fn=y.split("/").slice(-2).join("/"),Uc=`${y}:${B}-${W}`,Bn=(ni.get(Uc)||0)+1;if(ni.set(Uc,Bn),D(Wt?`${p.red} \u2716 Blocked superread: "${Fn}" lines ${B}-${W} subsumes already-read ${oe}-${ue} \u2014 use line_start=${ue+1} to skip known content (block #${Bn})${p.reset}`:`${p.red} \u2716 Blocked duplicate read: "${Fn}" lines ${B}-${W} (\u226570% overlap with lines ${oe}-${ue} already in context, block #${Bn})${p.reset}`),Bn>=2){D(`${p.red} \u2716 Escalated range-block: "${Fn}" lines ${B}-${W} \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let Hc={role:"user",content:Wt?`[SYSTEM] Read blocked ${Bn}\xD7 for read_file("${y}", lines ${B}-${W}). Lines ${oe}-${ue} were already read. Use line_start=${ue+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Bn}\xD7 for read_file("${y}", lines ${B}-${W}). Lines ${oe}-${ue} were already read and will NOT change. Use grep_search to find specific content instead.`};q.push(Hc),_.push(Hc)}$.canExecute=!1,$.errorResult={role:"tool",content:Wt?`BLOCKED: read_file("${y}", lines ${B}-${W}) re-reads lines ${oe}-${ue} already in context. Use line_start=${ue+1} to read only the new content beyond line ${ue}.`:`BLOCKED: read_file("${y}", lines ${B}-${W}) is a duplicate \u2014 lines ${oe}-${ue} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:$.callId},X=!0;break}}}if(!X){let oe=z.length,ue=2;if(oe>=3){let Ne=y.split("/").slice(-2).join("/");D(`${p.red} \u2716 Blocked file-scroll: "${Ne}" \u2014 ${oe} sections already read. Use grep to find specific content.${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 you have already read ${oe} different sections of this file (file-scroll pattern). You have seen most of this file. Use grep_search to find the exact lines you need instead of continuing to scroll.`,tool_call_id:$.callId}}else oe>=ue&&($._scrollWarn={sectionCount:oe+1,path:y})}}else if(I>=1){let B=y.split("/").slice(-2).join("/"),W=(jn.get(y)||0)+1;if(jn.set(y,W),W===1)D(`${p.red} \u2716 Blocked unbounded re-read: "${B}" \u2014 already in context. Use line_start/line_end for specific sections.${p.reset}`);else if(W===2){D(`${p.red} \u2716 Escalated block: "${B}" \u2014 model ignored unbounded re-read block, injecting system warning${p.reset}`);let z={role:"user",content:`[SYSTEM] read_file("${y}") was blocked again \u2014 full-file reads are disabled after the first read. Use line_start/line_end for a specific section, or use grep_search to find what you need.`};q.push(z),_.push(z)}$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${I}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:$.callId}}$.canExecute&&mi.set(y,(mi.get(y)||0)+1)}if(en>=3)for(let $ of pe)$.canExecute&&($.fnName!=="read_file"&&$.fnName!=="edit_file"||(D(`${p.red} \u2716 Blocked ${$.fnName} \u2014 ${en} consecutive file-not-found errors, must search first${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${en} consecutive "File not found" errors. You must call search_files or glob_files to locate the correct path before reading or editing. Do not guess file paths.`,tool_call_id:$.callId}));for(let $ of pe){if(!$.canExecute||$.fnName!=="bash")continue;let y=($.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){D(`${p.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:$.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(D(`${p.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:$.callId})}for(let $ of pe)$.canExecute&&($.fnName!=="ssh_exec"&&$.fnName!=="bash"||/\bsed\s+-n\b/.test($.args?.command||"")&&(D(`${p.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:'BLOCKED: sed -n is forbidden \u2014 it floods context with line ranges. Use grep -n "pattern" <file> | head -30 to read a specific section, or cat <file> for the full file.',tool_call_id:$.callId}));for(let $ of pe){if(!$.canExecute||$.fnName!=="write_file")continue;let y=$.args?.path,ee=$.args?.content||"";if(y)try{let A=require("fs"),I=require("path").resolve(process.cwd(),y);if(A.existsSync(I)){let te=A.statSync(I).size,F=Buffer.byteLength(ee,"utf8"),le=te>0?F/te:1;if(le<.6&&te>200){let j=y.split("/").slice(-2).join("/");console.log(`${p.red} \u2716 write_file shrink guard: "${j}" would shrink to ${Math.round(le*100)}% of original \u2014 likely context loss${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(le*100)}% of current file size (${te} \u2192 ${F} bytes). This looks like a partial rewrite after context loss. Use edit_file/patch_file to add only the new code, or read the file first to see full content before replacing.`,tool_call_id:$.callId}}}}catch{}}let qc=new Map;for(let $ of pe){if(!$.canExecute||$.fnName!=="grep")continue;let y=$.args?.path;if(!y)continue;let ee=qc.get(y)||0,A=An(Oc,y)+ee;if(A>=Nc){let I=y.split("/").slice(-2).join("/");D(`${p.red} \u2716 Blocked grep: "${I}" grepped ${A}\xD7 with different patterns \u2014 flood threshold exceeded${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: grep("${y}") denied \u2014 ${A} patterns already tried. Use existing results or read the file instead.`,tool_call_id:$.callId}}$.canExecute&&qc.set(y,ee+1)}let zh=5,Fc=new Map;for(let $ of pe){if(!$.canExecute||$.fnName!=="ssh_exec")continue;let ee=($.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),A=Fc.get(ee)||0,I=An(Ac,ee)+A;I>=zh&&(D(`${p.yellow} \u26A0 Blocked ssh_exec: same command run ${I}\xD7 \u2014 result already in context${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${I} times and the output is in your context. Use existing results, try a different command, or run it as a local bash call: bash("ssh user@host 'your command'").`,tool_call_id:$.callId}),$.canExecute&&Fc.set(ee,A+1)}if(ht){let $=pe.filter(A=>A.canExecute&&A.fnName==="ssh_exec"),y=pe.some(A=>A.canExecute&&A.fnName!=="ssh_exec"),ee=w&&P<3;if($.length>0&&!y&&ee&&Xr<1)ht=!1,Xr++,wt=Math.max(0,_s-2),D(`${p.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Xr}/1)]${p.reset}`);else for(let A of $)A.canExecute=!1,A.errorResult={role:"tool",content:Ye?`BLOCKED: ssh_exec denied \u2014 SSH paused (${_s}+ calls). Root cause is known (${it}). Edit the file now. You can still use bash("ssh user@host 'cmd'") for a single targeted lookup if essential.`:`BLOCKED: ssh_exec denied \u2014 SSH temporarily paused (${_s}+ calls). Provide a text summary of your findings first. Do NOT ask the user to run commands. SSH re-enables after your summary. For one-off lookups use bash("ssh user@host 'cmd'") instead.`,tool_call_id:A.callId}}if(w&&P<3&&!ht){for(let $ of pe)if($.canExecute&&["bash","read_file","find_files"].includes($.fnName)){P++;{let y=Ze(),{messages:ee}=It(_,y);_=ee}D(`${p.yellow} \u26A0 Jarvis-local guard: blocking local ${$.fnName} \u2014 use ssh_exec on 94.130.37.43${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${$.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:$.callId};break}}if(!$e&&Tt&&bt&&Rt>=1){let $=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of pe)y.canExecute&&$.includes(y.fnName)&&(D(`${p.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${p.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:y.callId})}if(Mn>=0){let $=pe.filter(y=>y.canExecute).length;if($>0&&(Mn-=$,Mn<0))if(!Jr&&T.size>Vr){Jr=!0,Mn=5,D(`${p.green} \u2713 Post-wipe progress detected (${T.size-Vr} files modified) \u2014 granting 5 bonus tool calls${p.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};q.push(y),_.push(y)}else{D(`${p.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${p.reset}`);for(let ee of pe)ee.canExecute&&(ee.canExecute=!1,ee.errorResult={role:"tool",content:"BLOCKED: post-wipe tool budget exhausted. No further tool calls are allowed. Summarise what was accomplished and stop.",tool_call_id:ee.callId});let y={role:"user",content:"[SYSTEM] Post-wipe tool budget exhausted. All tool calls are now blocked. Respond with a final summary of what was done and stop \u2014 do not attempt any more tool calls."};q.push(y),_.push(y)}}let Xh=new Set(["edit_file","write_file","bash","ssh_exec","ask_user","spawn_agents","browser_click","browser_fill","browser_open","skill_ar_run_experiment","skill_ar_run_benchmark","skill_ar_checkpoint","skill_ar_revert","skill_ar_log_experiment","skill_ar_extract_metric"]);for(let $ of pe){if(!$.canExecute||Xh.has($.fnName))continue;let y=JSON.stringify($.args||{}),ee=`${$.fnName}|${y}`,A=An(si,ee);A>=2?(D(`${p.red} \u2716 Blocked duplicate: ${$.fnName}(${y.substring(0,80)}) \u2014 called ${A+1}\xD7 with identical args${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${$.fnName}() with these exact arguments has already been called ${A}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:$.callId}):A===1&&D(`${p.yellow} \u26A0 Duplicate tool call: ${$.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${p.reset}`),On(si,ee)}let xs=l?{skipSpinner:!0,skipSummaries:!0}:{},Vh=pe.some($=>$.fnName==="ask_user"),Bc=!xs.skipSummaries&&!xe,Ao=null;Bc&&!Vh?(xe=!0,xs.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(Wr(pe,k,!1,"blink")),Ao=!0):qt||process.stdout.write(Wr(pe,k,!1)+`
|
|
1201
|
-
`)):
|
|
1202
|
-
`)
|
|
1203
|
-
`)
|
|
1204
|
-
`).
|
|
1205
|
-
`).map(z=>z.trim()).find(z=>z.length>0&&(z.startsWith("EXIT")||/^[\w./-]+:\s/.test(z)||z.startsWith("bash:")||z.startsWith("sh:")))??"";if(W){if(W===Qr?Pn++:(Qr=W,Pn=1),Pn===3){D(`${p.yellow} \u26A0 Bash repeated-error: "${W.slice(0,60)}" returned ${Pn}\xD7 \u2014 nudging to change approach${p.reset}`);let z={role:"user",content:`[SYSTEM WARNING] The last ${Pn} bash commands all failed with the same error: "${W}". Retrying variants of the same command will not help. Switch to a completely different approach (e.g. use a different tool, change the command syntax, or use ssh_exec to run the command on the remote server instead).`};q.push(z),_.push(z)}}else Qr="",Pn=0}if(y.fnName==="bash"&&y.canExecute&&!sc&&y.args?.command){let j=Nt[$]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!j.startsWith("EXIT")&&!j.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(j)||j.includes("files changed")||j.includes("file changed")||j.includes("insertions(+)")||j.includes("create mode"))){sc=!0,uo=0,D(`${p.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${p.reset}`);let z={role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. Your changes are committed. Do NOT run further git status / git diff / git log calls \u2014 the commit is done. Write your final summary and stop. Running extra verification commands wastes tool calls and hurts session quality."};q.push(z),_.push(z)}}if(sc&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(uo++,uo>2)){D(`${p.yellow} \u26A0 Post-commit git verification blocked (call ${uo})${p.reset}`);let B={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(uo-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};q.push(B),_.push(B)}if(I&&y.fnName==="grep"&&y.args&&y.args.pattern){let j=`${y.args.pattern}|${y.args.path||""}`,B=On(Oh,j);if(B===Nh){D(`${p.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${B}\xD7 \u2014 possible search loop${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${B}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};q.push(W),_.push(W)}else if(B>=Mh){D(`${p.red} \u2716 Loop abort: grep pattern run ${B}\xD7 \u2014 aborting runaway search loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}if(y.args.path){let W=On(Oc,y.args.path),z=An(So,y.args.path)>=1;if(W===(z?1:Lh)){let oe=y.args.path.split("/").slice(-2).join("/");D(`${p.yellow} \u26A0 Loop warning: "${oe}" grepped ${W}\xD7 with different patterns \u2014 context flood risk${p.reset}`);let ue={role:"user",content:z?`[SYSTEM NOTE] "${y.args.path}" was already fully read \u2014 its content is in context. Grepping it again is redundant; use the context you already have.`:`[SYSTEM NOTE] "${y.args.path}" grepped ${W}\xD7 \u2014 use the search results already in context instead of searching again.`};q.push(ue),_.push(ue)}}}if(I&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){let j=y.args.pattern||y.args.query||y.args.path||"",B=On(Ph,j);if(B===Ih){D(`${p.yellow} \u26A0 Loop warning: glob pattern "${j.slice(0,40)}" run ${B}\xD7 \u2014 possible search loop${p.reset}`);let z={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${B}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};q.push(z),_.push(z)}else if(B>=jh){D(`${p.red} \u2716 Loop abort: glob pattern run ${B}\xD7 \u2014 aborting runaway search loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}let W=j.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(z=>z.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(z));for(let z of W){let X=z.toLowerCase();_o.has(X)||_o.set(X,new Set);let oe=_o.get(X);if(oe.add(j),oe.size===qh){D(`${p.red} \u2716 Glob core-term block: ${oe.size} different patterns all searching for "${X}" \u2014 search loop${p.reset}`);let ue={role:"user",content:`[SYSTEM WARNING] You have searched for "${X}" using ${oe.size} different glob patterns. This is a search loop \u2014 the file you are looking for likely does not exist. Stop searching and work with the files you have already found, or ask the user for clarification.`};q.push(ue),_.push(ue)}else if(oe.size===Dh){D(`${p.yellow} \u26A0 Glob core-term warning: ${oe.size} different patterns searching for "${X}"${p.reset}`);let ue={role:"user",content:`[SYSTEM WARNING] ${oe.size} different glob patterns all target "${X}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};q.push(ue),_.push(ue)}}}let te=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),F=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(te)||/\/(health|status|ping|ready|alive)\b/.test(te);if(I&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&F&&ee.includes('"valid":true')){{let B=Ze();if(Et(_,B).percentage>=60){let{messages:z,tokensRemoved:X}=It(_,B);X>0&&(_=z,console.log(`${p.dim} [pre-stop-compress \u2014 ~${X} tokens freed before STOP injection, now ${Math.round(Et(_,B).percentage)}%]${p.reset}`))}}let j={role:"user",content:'[SYSTEM STOP] Tool result contains {"valid":true}. The token/service is valid and reachable. STOP all further investigation immediately. Report to the user that the token is valid, the service is healthy, and no fix is needed. Do NOT read any more log files.'};q.push(j),_.push(j),console.log(`${p.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${p.reset}`)}if(ee.startsWith("BLOCKED:")){if(on++,on>=Mc){D(`${p.red} \u2716 Loop abort: ${on} consecutive blocked calls \u2014 model not heeding BLOCKED messages${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}}else on=0;if(I)sn=0,di=!0;else if(sn++,sn===Uh){D(`${p.yellow} \u26A0 Loop warning: ${sn} consecutive tool errors \u2014 possible stuck loop${p.reset}`);let j={role:"user",content:`[SYSTEM WARNING] ${sn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};q.push(j),_.push(j)}else if(sn>=Hh){D(`${p.red} \u2716 Loop abort: ${sn} consecutive errors \u2014 aborting stuck loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}if(I&&y.fnName==="read_file"&&y.args&&y.args.path){S.add(y.args.path);let j=On(So,y.args.path);if(y.args.line_start!=null){let X=y.args.line_start||1,oe=y.args.line_end||X+350;tn.has(y.args.path)||tn.set(y.args.path,[]),tn.get(y.args.path).push([X,oe])}if(y._scrollWarn){let{sectionCount:X,path:oe}=y._scrollWarn,ue={role:"user",content:`[SYSTEM WARNING] "${oe}" \u2014 you have now read ${X} different sections of this file. This is a file-scroll pattern. Stop reading sections and use grep_search to find the specific lines you need instead.`};q.push(ue),_.push(ue),D(`${p.yellow} \u26A0 Scroll warning: "${oe.split("/").slice(-2).join("/")}" \u2014 ${X} sections read \u2014 use grep instead${p.reset}`)}let B=y.args.path.split("/").slice(-2).join("/"),W=!y.args?.line_start&&!y.args?.line_end,z=$e&&De==="plan";if(!z&&W&&j===Fh){{let oe=Ze();if(Et(_,oe).percentage>=60){let{messages:ne}=It(_,oe);_=ne}}D(`${p.yellow} \u26A0 Loop warning: "${B}" read unbounded ${j}\xD7 \u2014 use line_start/line_end${p.reset}`);let X={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${j}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};q.push(X),_.push(X)}else if(!z&&W&&j>=Bh){D(`${p.red} \u2716 Loop abort: "${B}" read unbounded ${j}\xD7 \u2014 aborting runaway read loop${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}}if(y.fnName==="spawn_agents"){let j=(ee.match(/\bStatus: done\b/g)||[]).length;if((ee.match(/\bStatus: truncated\b/g)||[]).length>0&&j===0){if(rn++,rn===Gh){D(`${p.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${rn}\xD7 in a row${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${rn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};q.push(W),_.push(W)}else if(rn>=Yh){console.log(`${p.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${rn}\xD7 \u2014 aborting stuck swarm${p.reset}`),l&&(l.stop(),l=null),c(null),We(k,N,T,S,J,{suppressHint:!0}),Be(q);return}}else j>0&&(rn=0)}}for(let $ of Nt)q.push($),_.push($);if(!Ye)for(let $=0;$<Nt.length;$++){if(!pe[$]||pe[$].fnName!=="ssh_exec")continue;let y=Nt[$];if(!y||typeof y.content!="string")continue;let ee=nc(y.content);if(ee){Ye=!0,it=ee.slice(0,120),jt=0,Tt=!1,Kt=0,D(`${p.yellow} \u26A1 Root cause detected: ${it} \u2014 fix phase (read budget: 3)${p.reset}`);let A={role:"user",content:`[SYSTEM] Root cause identified: ${it}. Read only the file that needs fixing, then edit it. Do not read other files.`};q.push(A),_.push(A);break}}for(let $=0;$<Nt.length;$++){let y=pe[$];if(!y)continue;let ee=typeof Nt[$]?.content=="string"?Nt[$].content:"";if(y.fnName==="create_task"){let A=ee.match(/Task #(\d+) created/),I=typeof y.args?.subject=="string"?y.args.subject:"";A&&I&&xo.set(A[1],I)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!ee.startsWith("BLOCKED:")&&ee.trim().length>0){let I=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),te=I.split(/[._\-/]/).filter(F=>F.length>2);for(let[F,le]of xo){if(ko.has(F))continue;let j=le.toLowerCase().split(/\W+/).filter(W=>W.length>3);te.filter(W=>j.some(z=>z.includes(W)||W.includes(z))).length>=1&&(ko.add(F),D(`${p.green} \u2714 Auto-matched task #${F} to ${I}: ${le.slice(0,60)}${p.reset}`))}}}{let $=Ze();if(Et(_,$).percentage>=78){let{messages:ee,tokensRemoved:A}=It(_,$);A>0&&(_=ee,console.log(`${p.dim} [auto-compressed \u2014 ~${A} tokens freed, now ${Math.round(Et(_,$).percentage)}%]${p.reset}`))}}let Wc=hx();if(Wc){let $={role:"user",content:`[User note mid-run]: ${Wc}`};q.push($),_.push($),console.log(`${p.cyan} \u270E Context added${p.reset}`)}}if(Fe>=Ct){if(l&&(l.stop(),l=null),c(null),We(k,N,T,S,J),Be(q),Hp(q),$e&&De==="plan"){let Dn=[...q].reverse().find(ze=>ze.role==="assistant"),ct=typeof Dn?.content=="string"?Dn.content:"",qn=fo("implement",ct);if(qn){q.push(qn),_=[{role:"system",content:await hc()},...q],Ct=Cn("implement"),D(`${p.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${p.reset}`);continue e}}else if($e&&De==="verify"){D(`${p.yellow} \u26A0 Verify budget exhausted \u2014 completing session${p.reset}`);break e}let{getActiveProviderName:be}=He();if(be()==="ollama"&&ui<Pc){if(T.size===0&&!di){console.log(`${p.yellow} \u26A0 Max iterations reached with no progress. Stopping.${p.reset}`);break e}ui++,Ct=20,console.log(`${p.dim} \u2500\u2500 auto-extending (+20 turns, ext ${ui}/${Pc}) \u2500\u2500${p.reset}`);continue e}if(console.log(`
|
|
1206
|
-
|
|
1207
|
-
`),
|
|
1208
|
-
`),await t(a,i,d)}catch(f){if(s=f,!ph(f))throw f}}continue}}throw n>0&&n===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function Wx(t,e,s={}){return _t(),gh((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function Ux(t,e,s={}){if(_t(),s.provider){let n=Ke[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||qe,...s};try{return await n.chat(t,e,o)}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return gh(async(n,o,r)=>{try{return await n.chat(t,e,{model:r,...s})}catch(i){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw i}})}function Hx(){_t();let t=[];for(let[e,s]of Object.entries(Ke))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function Gx(){for(let t of Object.keys(Ke))delete Ke[t];at=null,qe=null,vo=[]}yh.exports={registerProvider:$s,getProvider:Nx,getActiveProvider:vc,getActiveProviderName:Mx,getActiveModelId:Lx,getActiveModel:Px,setActiveModel:Ix,getModelNames:jx,parseModelSpec:mh,listProviders:Dx,listAllModels:qx,callStream:Wx,callChat:Ux,getConfiguredProviders:Hx,setFallbackChain:Fx,getFallbackChain:Bx,resolveModelForProvider:xc,MODEL_EQUIVALENTS:kc,OLLAMA_FALLBACK_MODELS:_c,_reset:Gx}});var{C:G}=Ue(),Yx=He(),{TOOL_DEFINITIONS:$h}=Jn(),{saveRoutingConfig:Kx}=ls(),Tc=[{id:"read-package",category:"file-ops",prompt:"Read the file package.json and show me its contents.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"write-file",category:"file-ops",prompt:'Create a file at /tmp/nex-bench-test.txt with the content "benchmark run".',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&typeof t.content=="string"},{id:"edit-file",category:"file-ops",prompt:'In the file src/config.js, replace the string "debug: false" with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.old_string!==void 0&&t.new_string!==void 0||t.path&&Array.isArray(t.patches)&&t.patches.length>0)},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".js")},{id:"search-constant",category:"search",prompt:'Search for the string "DEFAULT_MODEL" across all files in the project.',expectedTool:["search_files","grep"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("DEFAULT_MODEL")},{id:"grep-function-def",category:"search",prompt:'Find where the function "callStream" is defined in the codebase.',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:t=>JSON.stringify(t).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git")},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git status")},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let s=e?.function?.parameters||{},n=s.required||[],o=Object.keys(s.properties||{});return n.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>o.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"What is the current version of this project? Check the source files.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"multi-step-count",category:"multi-step",prompt:"How many JavaScript files are in the cli/ directory? Count them.",expectedTool:["bash","glob","list_directory"],validateArgs:t=>!!(typeof t.command=="string"&&t.command.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli")||typeof t.path=="string"&&t.path.includes("cli"))},{id:"no-tool-reasoning",category:"reasoning",prompt:'What does the acronym "API" stand for?',expectedTool:null,validateArgs:()=>!0},{id:"frontend-find-hook",category:"frontend",prompt:"Find all files that import useState from React.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("useState")},{id:"frontend-create-component",category:"frontend",prompt:"Create a React functional component called Button that accepts a label prop and renders a styled button element. Save it to src/components/Button.jsx.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".jsx")||t.path.includes(".tsx")||t.path.includes(".js"))&&typeof t.content=="string"},{id:"frontend-edit-css",category:"frontend",prompt:'In the file src/styles.css, change the background-color value from "blue" to "red".',expectedTool:["edit_file","patch_file"],validateArgs:t=>t.path&&t.old_string!==void 0?t.path.includes(".css")||t.old_string.includes("blue")||t.old_string.includes("background"):!!(t.path&&Array.isArray(t.patches))},{id:"frontend-glob-components",category:"frontend",prompt:"Find all JSX and TSX component files in the components/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&(t.pattern.includes(".jsx")||t.pattern.includes(".tsx")||t.pattern.includes("{jsx,tsx}"))},{id:"frontend-list-assets",category:"frontend",prompt:"List all files in the src/assets/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("assets")||typeof t.pattern=="string"&&t.pattern.includes("assets"))},{id:"sysadmin-port-check",category:"sysadmin",prompt:"Which process is currently listening on port 3000?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("lsof")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("3000"))},{id:"sysadmin-nginx-config",category:"sysadmin",prompt:"Create an nginx server block that proxies requests to localhost:3000. Save it to /etc/nginx/sites-available/myapp.",expectedTool:["write_file","bash"],validateArgs:t=>!!(t.path&&(t.path.includes("nginx")||t.path.includes("sites-available"))||t.command&&t.command.includes("nginx"))},{id:"sysadmin-service-status",category:"sysadmin",prompt:"Check the status of the nginx service and show if it is running.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("systemctl")||t.command.includes("service")||t.command.includes("nginx"))},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("journalctl")||t.command.includes("nginx"))},{id:"sysadmin-docker-compose",category:"sysadmin",prompt:"Create a docker-compose.yml file for a Node.js application with a PostgreSQL database.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("docker-compose")&&typeof t.content=="string"},{id:"data-sql-query",category:"data",prompt:"Write a SQL query to find all users who have not logged in for more than 30 days. Save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".sql")||t.path.includes("quer"))&&typeof t.content=="string"},{id:"data-find-json-key",category:"data",prompt:'Find all JSON files in the project that contain the key "userId".',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("userId")},{id:"data-python-csv",category:"data",prompt:'Write a Python script that reads data.csv and calculates the average of the "price" column. Save it to scripts/average_price.py.',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".py")&&typeof t.content=="string"},{id:"data-find-migrations",category:"data",prompt:"Find all database migration files in this project.",expectedTool:["glob","search_files","grep"],validateArgs:t=>JSON.stringify(t).toLowerCase().includes("migrat")},{id:"data-find-schema",category:"data",prompt:"Find where the database schema or models are defined in this project.",expectedTool:["grep","glob"],validateArgs:t=>!!(t.pattern&&/schema|model|migration/i.test(t.pattern)||t.pattern&&/schema|model|migration/i.test(t.pattern))},{id:"data-write-query",category:"data",prompt:"Write a SQL query to find all users who registered in the last 30 days and save it to queries/recent-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".sql")},{id:"data-read-env",category:"data",prompt:"Read the .env file to find the database connection string.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/\.env|env\./i.test(t.path)},{id:"resilience-edit-failed",category:"resilience",prompt:"Your edit_file call on server.js failed: old_string 'const PORT = 3000' was not found in the file. What do you do next to recover?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("server")},{id:"resilience-file-not-found",category:"resilience",prompt:"read_file returned 'file not found' for src/utils/helpers.js. You need to find where the helper functions are now. What tool do you use?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("src")||e.includes("helper")||e.includes("util")||e.includes("*.js")}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. What is the most efficient tool to use \u2014 read_file or bash with grep?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("awk"))},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. What tool do you use to find the new location?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("config")||e.includes("*.ts")||e.includes("*.js")||e.includes("find")}},{id:"resilience-bash-error-recover",category:"resilience",prompt:"The command 'npm test' failed with exit code 1. The output contains 'SyntaxError: Unexpected token' in src/parser.js:45. What is your next action?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("parser")},{id:"resilience-grep-no-match",category:"resilience",prompt:"grep returned zero matches for 'getUserById' in src/. The function exists but may have been renamed. What bash command finds all exported function names in src/ to identify the current name?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("src"))},{id:"ssh-exec-log",category:"ssh",prompt:'Show the last 50 lines of /var/log/nginx/error.log on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("log"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-service",category:"ssh",prompt:'Restart the nginx service on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("nginx")||t.command.includes("systemctl")||t.command.includes("restart"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-port",category:"ssh",prompt:'Check if port 8080 is listening on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("8080")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("lsof"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-processes",category:"ssh",prompt:'Show the top CPU-consuming processes on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("top")||t.command.includes("ps")||t.command.includes("htop"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"git-diff-staged",category:"git",prompt:"Show all staged changes before committing.",expectedTool:["git_diff","bash"],validateArgs:t=>!!(t.staged===!0||t.staged==="true"||typeof t.command=="string"&&t.command.includes("diff"))},{id:"git-log-recent",category:"git",prompt:"Show the last 5 commit messages with their hashes.",expectedTool:["git_log","bash"],validateArgs:t=>!!(typeof t.limit=="number"||typeof t.n=="number"||typeof t.command=="string"&&t.command.includes("log"))},{id:"git-status-check",category:"git",prompt:"Check if there are any uncommitted changes in the repository.",expectedTool:["git_status","bash"],validateArgs:t=>t.path===void 0&&t.command===void 0?!1:(typeof t.command=="string"&&t.command.includes("status"),!0)},{id:"agentic-test-first",category:"agentic",prompt:"Run the full test suite. If any tests fail, identify the failing test file and read it to understand the issue.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("test")||t.command.includes("jest")||t.command.includes("npm"))},{id:"agentic-read-then-act",category:"agentic",prompt:"Read the project README.md, find the TODO section, and list which items are completed.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("README")},{id:"agentic-build-deploy",category:"agentic",prompt:"Build the project with npm run build, then verify the output exists in the dist/ directory.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("build")||t.command.includes("npm"))},{id:"agentic-spawn-parallel",category:"agentic",prompt:"Search for all TODO comments and all FIXME comments across the codebase in parallel using multiple agents.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2},{id:"agentic-multi-investigate",category:"agentic",prompt:"The app is crashing on startup. Spawn parallel agents to check: (1) recent git changes, (2) npm dependency issues, (3) the main entry file for syntax errors.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2}],wh=[{id:"phase-plan-diagnosis",category:"phase-plan",prompt:"The server returns 500 on /api/users. The error log shows: TypeError: Cannot read property 'map' of undefined at routes/users.js:42. Read the relevant file to diagnose the root cause.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/users/i.test(t.path)},{id:"phase-plan-search",category:"phase-plan",prompt:"We're getting CORS errors in production. Search the codebase for where CORS middleware is configured.",expectedTool:"grep",validateArgs:t=>typeof t.pattern=="string"&&/cors/i.test(t.pattern)},{id:"phase-plan-context",category:"phase-plan",prompt:"The login page shows a blank screen after the last deploy. Check git log for recent changes that might have broken it.",expectedTool:"git_log",validateArgs:()=>!0},{id:"phase-verify-test",category:"phase-verify",prompt:"The file src/utils.js was modified to fix a null pointer bug. Run the test suite to verify the fix works correctly.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/test|jest|npm\s+test|pytest|mocha/.test(t.command)},{id:"phase-verify-read",category:"phase-verify",prompt:"A patch was applied to config/database.js to fix the connection pool. Read the file to verify the changes look correct.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/database/i.test(t.path)},{id:"phase-verify-lint",category:"phase-verify",prompt:"Code was modified in src/components/Header.tsx. Run the linter to check for any style violations.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/lint|eslint|prettier|tsc/.test(t.command)},{id:"phase-plan-git-blame",category:"phase-plan",prompt:"A production bug was introduced 2 days ago. Use git log to find commits from the last 2 days to identify what changed.",expectedTool:"git_log",validateArgs:()=>!0},{id:"phase-plan-error-trace",category:"phase-plan",prompt:"The error stack trace mentions src/middleware/auth.js line 87. Read the file around that line to understand the bug.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/auth/i.test(t.path)},{id:"phase-plan-grep-config",category:"phase-plan",prompt:"Users report the app is using wrong API keys in staging. Search for where API_KEY is loaded from environment.",expectedTool:"grep",validateArgs:t=>typeof t.pattern=="string"&&/api.?key|env/i.test(t.pattern)},{id:"phase-verify-build",category:"phase-verify",prompt:"The TypeScript source was modified. Run the build command to verify there are no compilation errors.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/build|tsc|compile/.test(t.command)},{id:"phase-verify-git-diff",category:"phase-verify",prompt:"Changes were just committed. Show the git diff of the last commit to verify only the intended files were modified.",expectedTool:["git_diff","bash"],validateArgs:t=>(t.command&&/git.*diff|diff.*HEAD/.test(t.command),!0)},{id:"phase-verify-read-config",category:"phase-verify",prompt:"The deployment config was updated. Read config/production.json to verify the changes are correct before deploying.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/config|production|deploy/i.test(t.path)}],ci=[...Tc,...wh],Sc=["devstral-2:123b","kimi-k2.5","glm-5:cloud","qwen3-coder:480b","qwen3-coder-next","ministral-3:14b","minimax-m2.7:cloud","kimi-k2:1t"];function zx(){try{let s=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(s))return Sc;let n=JSON.parse(require("fs").readFileSync(s,"utf-8"));return!Array.isArray(n)||n.length===0?Sc:n.filter(o=>typeof o.score=="number"&&o.score>=60).sort((o,r)=>r.score-o.score).slice(0,12).map(o=>o.model)}catch{return Sc}}var Rc=zx(),Xx=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],bh=(()=>{let t=Rc.slice(0,3);return t.length>=3?t:Xx})(),Vx=7,ii={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},Jx="You are a coding assistant. Use the provided tools to help with file operations, search, and development tasks. Only call a tool when one is clearly needed to answer the request. Do not call a tool for questions you can answer from general knowledge.";async function Ec(t,e){let s={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},n=[{role:"system",content:Jx},{role:"user",content:t.prompt}],o=Date.now();try{let r=await Yx.callChat(n,$h,{provider:"ollama",model:e,temperature:0,timeout:9e4});s.latencyMs=Date.now()-o;let i=r.tool_calls||[];if(t.expectedTool===null){let a=i.length===0;s.producedToolCall=a,s.correctTool=a,s.validArgs=!0,s.schemaCompliant=!0}else if(i.length>0){let a=i[0],c=a.function?.name||"unknown",l=a.function?.arguments||{};s.producedToolCall=!0,s.toolCalled=c;let u=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(s.correctTool=u.includes(c),s.correctTool){let d=$h.find(f=>f.function?.name===c);if(s.validArgs=!!t.validateArgs(l,d),d){let f=d.function?.parameters||{},h=f.required||[],m=Object.keys(f.properties||{});s.schemaCompliant=h.every(g=>l[g]!==void 0)&&Object.keys(l).every(g=>m.includes(g))}}}}catch(r){s.latencyMs=Date.now()-o,s.error=r.message.slice(0,120)}return s}function ws(t){return t.error?0:((t.producedToolCall?ii.producedToolCall:0)+(t.correctTool?ii.correctTool:0)+(t.validArgs?ii.validArgs:0)+(t.schemaCompliant?ii.schemaCompliant:0))*100}var _h={coding:"coding",search:"coding",shell:"coding",schema:"coding","multi-step":"coding",reasoning:"coding",frontend:"frontend",sysadmin:"sysadmin",data:"data",agentic:"agentic",resilience:"coding",ssh:"sysadmin",git:"coding","phase-plan":"plan","phase-verify":"verify"};function Cc(t){return Object.entries(t).map(([e,s])=>{let n=s.map(ws),o=n.reduce((a,c)=>a+c,0)/n.length,r=a=>Math.round(s.filter(a).length/s.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=s.filter(u=>_h[u.category]===a);if(c.length===0)continue;let l=c.map(ws).reduce((u,d)=>u+d,0)/c.length;i[a]=Math.round(l*10)/10}return{model:e,score:Math.round(o*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(s.reduce((a,c)=>a+c.latencyMs,0)/s.length),errorCount:s.filter(a=>a.error).length,categoryScores:i,results:s}}).sort((e,s)=>s.score-e.score)}function xh(t){let e={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=t.filter(g=>g.categoryScores[a]!==void 0&&g.score>=65).sort((g,b)=>b.categoryScores[a]-g.categoryScores[a]);if(c.length===0)continue;let u=(c[0]?.results||[]).filter(g=>_h[g.category]===a).length;if(u<4)continue;let d=c[0],f=c[1];if(d.categoryScores[a]>=95&&u<8&&f&&d.categoryScores[a]-f.categoryScores[a]<15){let b=t.filter(v=>v.categoryScores[a]!==void 0).find(v=>v.categoryScores[a]<95);b&&(e[a]={model:b.model,score:b.categoryScores[a],avgLatency:b.avgLatency,_flukePrevented:!0});continue}let m=c.filter(g=>d.categoryScores[a]-g.categoryScores[a]<=5).sort((g,b)=>g.avgLatency-b.avgLatency)[0];e[a]={model:m.model,score:m.categoryScores[a],avgLatency:m.avgLatency}}return e}function kh(t,e){let s=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,n=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],o=n.reduce((l,u)=>l+u.width+1,0)+1,r="\u2500".repeat(o);console.log(`
|
|
1209
|
-
|
|
1210
|
-
${G.bold}${G.green}Winner: ${l.model}${G.reset} score ${l.score}/100`),t.length>1){let u=(l.score-t[1].score).toFixed(1);console.log(`${G.dim}+${u} pts over ${t[1].model}${G.reset}`)}}let a=["coding","frontend","sysadmin","data","agentic"];if(t.some(l=>Object.keys(l.categoryScores).length>1)){console.log(`
|
|
1211
|
-
${
|
|
1212
|
-
${
|
|
1232
|
+
${getPlanContent()||Nt.content}`;q.push({role:"user",content:J}),T.push({role:"user",content:J}),Q=!0}}else console.log(`
|
|
1233
|
+
${p.cyan}${p.bold}Plan ready.${p.reset} ${p.dim}Type ${p.reset}${p.cyan}/plan approve${p.reset}${p.dim} to execute, or ask follow-up questions to refine.${p.reset}`);if(Q){l&&(l.stop(),l=null),We--;continue}}}if(l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H),xt&&R.size>=3){let S=[...R].map(N=>N.split("/").pop()).slice(0,8).join(", "),A=[...R].some(N=>N.endsWith("package.json")),Q=[...R].some(N=>N.endsWith("requirements.txt")),D=[...R].some(N=>N.endsWith("package-lock.json")||N.endsWith("yarn.lock")||N.endsWith("pnpm-lock.yaml")),le=A&&!D?"npm install not yet run":Q?"pip install not yet run":null;wo=`[Previous session created ${R.size} files: ${S}`+(le?` \u2014 ${le}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(xt&&!Sc&&v>0){let S=[...R].some(J=>J.endsWith("package.json")),A=[...R].some(J=>J.endsWith("requirements.txt")||J.endsWith("Pipfile")||J.endsWith("pyproject.toml")),Q=[...R].some(J=>J.endsWith("package-lock.json")||J.endsWith("yarn.lock")||J.endsWith("pnpm-lock.yaml")),D=q.flatMap(J=>{let oe=Array.isArray(J.tool_calls)?J.tool_calls:[],he=Array.isArray(J.content)?J.content.filter(ne=>ne?.type==="tool_use"):[];return[...oe,...he]}).filter(J=>{let oe=J.function?.name||J.name||"";return oe==="bash"||oe==="Bash"}).map(J=>{try{let oe=J.function?.arguments??J.input??{};return(typeof oe=="string"?JSON.parse(oe):oe)?.command||""}catch{return""}}),le=D.some(J=>/pip\s+install|python\s+-m\s+venv/.test(J)),N=D.some(J=>/npm\s+install/.test(J)),U=[...R].some(J=>/\/App\.(js|ts|jsx|tsx)$/.test(J))&&!S&&!N;if(A&&!le||S&&!Q&&!N||U){Sc=!0;let J=[];A&&!le&&J.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),U?J.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):S&&!Q&&!N&&J.push("npm install");let oe=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${J.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;F(`${p.dim} [post-creation] bootstrapping environment (${J.join(", ")})${p.reset}`),q.push({role:"user",content:oe}),T.push({role:"user",content:oe});continue}}if(v>0&&!s._isSummaryTurn&&P_(Mt))try{F(`${p.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${p.reset}`);let S=R.size>0?"Write a closing summary (3+ sentences): what files changed and why, what the result is, anything the user should know or do next.":"Write a closing diagnosis (3+ sentences): what you investigated, what you found, and what the user should do next or what the root cause is.",A=[...T,{role:"user",content:S}],D=((await sh(A,[],{}))?.content||"").trim();D&&(console.log(`
|
|
1234
|
+
${D}`),q.push({role:"user",content:S},{role:"assistant",content:D}))}catch{}qe(q),ic(q);return}v++,ai++,v>=1&&(ke=!1);for(let $ of Wt){let y=$.function.name;O.set(y,(O.get(y)||0)+1)}if(v>=30&&!hh){hh=!0,F(`${p.yellow} \u26A0 Tool budget warning: ${v} tool calls used \u2014 nudging model to wrap up${p.reset}`);let $={role:"user",content:"[SYSTEM] \u26A0 You have used "+v+" tool calls. This is approaching the quality threshold (40). Wrap up NOW: write your final summary and stop. Do NOT run additional verification commands (git status, git diff, git log) \u2014 your changes are already committed and verified. Further tool calls will hurt session quality."};q.push($),T.push($)}let ye=await Promise.all(Wt.map($=>Rx($)));{let $=Tt(T,Qe()),y=$.percentage,ee=ye.some(D=>D.canExecute&&D.fnName==="read_file"&&!D.args?.line_end),S=ye.filter(D=>D.canExecute&&D.fnName==="read_file"&&D.args?.path&&Dt(Fn,D.args.path)>=1&&!D.args?.line_start).map(D=>D.args.path.split("/").slice(-2).join("/")),A=S.length>0;if(y>=70&&ee&&hi<70||y>=85&&hi<85||A){hi=y;let D=y>=85?"URGENT":"WARNING",le;A?(D="WARNING",le=`Full-file read of ${S.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):ee?le=`Unbounded read at ${Math.round(y)}% context \u2014 use line_start/line_end to avoid overflow.`:le="Use targeted reads (line_start/line_end) to save space.";let N={role:"user",content:`[SYSTEM ${D}] Context ${Math.round(y)}% used (${$.used}/${$.limit} tokens). ${le}`};if(q.push(N),T.push(N),y>=85){let B=A?` (re-read of: ${S.join(", ")})`:"";F(`${p.yellow} \u26A0 Context ${Math.round(y)}% used \u2014 agent warned to use targeted reads${B}${p.reset}`)}}}let bi=new Map;for(let $ of ye){if(!$.canExecute||$.fnName!=="read_file")continue;let y=$.args?.path;if(!y)continue;let ee=Dt(Fn,y),S=bi.get(y)||0,A=ee+S,Q=$.args?.line_start!=null,D=Pn.get(y)||0,le=D>0,N=2;if(A>=Bn){let B=y.split("/").slice(-2).join("/"),U=(qn.get(y)||0)+1;if(qn.set(y,U),U===1)F(`${p.red} \u2716 Blocked: "${B}" read ${A}\xD7 \u2014 hard cap (${Bn}) reached${p.reset}`);else if(U===2){F(`${p.red} \u2716 Escalated block: "${B}" \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let V={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${y}") and tried again anyway. This file has reached its read cap (${Bn}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};q.push(V),T.push(V)}$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${A}\xD7 (hard cap: ${Bn}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:$.callId}}else if(A>=1&&Q)if(le&&D<=N){let B=y.split("/").slice(-2).join("/");console.log(`${p.cyan} \u21A9 Targeted re-read: "${B}" (line_start=${$.args.line_start}) \u2014 edit recovery #${D}${p.reset}`),Pn.set(y,D-1)}else if(le&&D>N){let B=y.split("/").slice(-2).join("/");F(`${p.red} \u2716 Edit recovery blocked: "${B}" \u2014 ${N} recovery reads already used. Use grep to find the exact line numbers, then retry.${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 edit recovery budget exhausted (${N} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:$.callId}}else{let B=$.args.line_start||1,U=$.args.line_end||B+350,V=zt.get(y)||[],J=!1;for(let[oe,he]of V){let ne=Math.max(B,oe),Me=Math.min(U,he);if(Me>ne){let Ue=Me-ne,yt=U-B||1,ut=he-oe||1,Ut=Ue/ut>=.7&&Ue/yt<.7,Ye=U-B<=Zh;if(Ue>=yt||!Ye&&(Ue/yt>=.7||Ue/ut>=.7)){let xi=y.split("/").slice(-2).join("/"),nl=`${y}:${B}-${U}`,Yn=(ri.get(nl)||0)+1;if(ri.set(nl,Yn),F(Ut?`${p.red} \u2716 Blocked superread: "${xi}" lines ${B}-${U} subsumes already-read ${oe}-${he} \u2014 use line_start=${he+1} to skip known content (block #${Yn})${p.reset}`:`${p.red} \u2716 Blocked duplicate read: "${xi}" lines ${B}-${U} (\u226570% overlap with lines ${oe}-${he} already in context, block #${Yn})${p.reset}`),Yn>=2){F(`${p.red} \u2716 Escalated range-block: "${xi}" lines ${B}-${U} \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let sl={role:"user",content:Ut?`[SYSTEM] Read blocked ${Yn}\xD7 for read_file("${y}", lines ${B}-${U}). Lines ${oe}-${he} were already read. Use line_start=${he+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Yn}\xD7 for read_file("${y}", lines ${B}-${U}). Lines ${oe}-${he} were already read and will NOT change. Use grep_search to find specific content instead.`};q.push(sl),T.push(sl)}$.canExecute=!1,$.errorResult={role:"tool",content:Ut?`BLOCKED: read_file("${y}", lines ${B}-${U}) re-reads lines ${oe}-${he} already in context. Use line_start=${he+1} to read only the new content beyond line ${he}.`:`BLOCKED: read_file("${y}", lines ${B}-${U}) is a duplicate \u2014 lines ${oe}-${he} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:$.callId},J=!0;break}}}if(!J){let oe=V.length,he=2;if(oe>=3){let Me=y.split("/").slice(-2).join("/");F(`${p.red} \u2716 Blocked file-scroll: "${Me}" \u2014 ${oe} sections already read. Use grep to find specific content.${p.reset}`);let Ue=Dt(pi,y)>=To;$.canExecute=!1,$.errorResult={role:"tool",content:Ue?`BLOCKED: read_file("${y}") denied \u2014 you have already read ${oe} different sections of this file (file-scroll pattern). Grep is also exhausted. The content you need is already in your context \u2014 work with what you have.`:`BLOCKED: read_file("${y}") denied \u2014 you have already read ${oe} different sections of this file (file-scroll pattern). You have seen most of this file. Use grep_search to find the exact lines you need instead of continuing to scroll.`,tool_call_id:$.callId}}else oe>=he&&($._scrollWarn={sectionCount:oe+1,path:y})}}else if(A>=1){let B=y.split("/").slice(-2).join("/"),U=(qn.get(y)||0)+1;if(qn.set(y,U),U===1)F(`${p.red} \u2716 Blocked unbounded re-read: "${B}" \u2014 already in context. Use line_start/line_end for specific sections.${p.reset}`);else if(U===2){F(`${p.red} \u2716 Escalated block: "${B}" \u2014 model ignored unbounded re-read block, injecting system warning${p.reset}`);let V={role:"user",content:`[SYSTEM] read_file("${y}") was blocked again \u2014 full-file reads are disabled after the first read. Use line_start/line_end for a specific section, or use grep_search to find what you need.`};q.push(V),T.push(V)}$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already in context (read ${A}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:$.callId}}$.canExecute&&bi.set(y,(bi.get(y)||0)+1)}if(sn>=3)for(let $ of ye)$.canExecute&&($.fnName!=="read_file"&&$.fnName!=="edit_file"||(F(`${p.red} \u2716 Blocked ${$.fnName} \u2014 ${sn} consecutive file-not-found errors, must search first${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${sn} consecutive "File not found" errors. You must call search_files or glob_files to locate the correct path before reading or editing. Do not guess file paths.`,tool_call_id:$.callId}));for(let $ of ye){if(!$.canExecute||$.fnName!=="bash")continue;let y=($.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(y)&&!/npm|yarn|pnpm|make|git/.test(y)){F(`${p.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:$.callId};continue}/\bfind\s+[\S.]/.test(y)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(y)&&(F(`${p.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:$.callId})}for(let $ of ye)$.canExecute&&($.fnName!=="ssh_exec"&&$.fnName!=="bash"||/\bsed\s+-n\b/.test($.args?.command||"")&&(F(`${p.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:'BLOCKED: sed -n is forbidden \u2014 it floods context with line ranges. Use grep -n "pattern" <file> | head -30 to read a specific section, or cat <file> for the full file.',tool_call_id:$.callId}));for(let $ of ye){if(!$.canExecute||$.fnName!=="write_file")continue;let y=$.args?.path,ee=$.args?.content||"";if(y)try{let S=require("fs"),A=require("path").resolve(process.cwd(),y);if(S.existsSync(A)){let Q=S.statSync(A).size,D=Buffer.byteLength(ee,"utf8"),le=Q>0?D/Q:1;if(le<.6&&Q>200){let N=y.split("/").slice(-2).join("/");console.log(`${p.red} \u2716 write_file shrink guard: "${N}" would shrink to ${Math.round(le*100)}% of original \u2014 likely context loss${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: write_file("${y}") denied \u2014 new content is only ${Math.round(le*100)}% of current file size (${Q} \u2192 ${D} bytes). This looks like a partial rewrite after context loss. Use edit_file/patch_file to add only the new code, or read the file first to see full content before replacing.`,tool_call_id:$.callId}}}}catch{}}let Zc=new Map;for(let $ of ye){if(!$.canExecute||$.fnName!=="grep")continue;let y=$.args?.path;if(!y)continue;let ee=Zc.get(y)||0,S=Dt(pi,y)+ee,A=Dt(Fn,y)>=1,Q=A?Math.min(3,To):To;if(S>=Q){let D=y.split("/").slice(-2).join("/");F(`${p.red} \u2716 Blocked grep: "${D}" grepped ${S}\xD7 with different patterns \u2014 flood threshold exceeded${p.reset}`);let le=Dt(Fn,y),N=le>=Bn;if(N){let B={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${y}". You have already read ${le} sections and tried ${S} grep patterns. Do NOT attempt to read or grep this file again. The content you need is already in your conversation context \u2014 scroll back to find it, or proceed with what you know.`};q.push(B),T.push(B),F(`${p.red} \u2716 Deadlock detected: "${D}" \u2014 both read and grep blocked, injecting deadlock-break${p.reset}`)}$.canExecute=!1,$.errorResult={role:"tool",content:N?`BLOCKED: grep("${y}") denied \u2014 ${S} patterns already tried AND reads are also exhausted. The content is already in your context. Do not attempt to read or grep this file again.`:A?`BLOCKED: grep("${y}") denied \u2014 file was already read and ${S} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${y}") denied \u2014 ${S} patterns already tried. Work with the grep results already in your context.`,tool_call_id:$.callId}}$.canExecute&&Zc.set(y,ee+1)}let om=5,Qc=new Map;for(let $ of ye){if(!$.canExecute||$.fnName!=="ssh_exec")continue;let ee=($.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),S=Qc.get(ee)||0,A=Dt(Yc,ee)+S;A>=om&&(F(`${p.yellow} \u26A0 Blocked ssh_exec: same command run ${A}\xD7 \u2014 result already in context${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${A} times and the output is in your context. Use existing results, try a different command, or run it as a local bash call: bash("ssh user@host 'your command'").`,tool_call_id:$.callId}),$.canExecute&&Qc.set(ee,S+1)}if(mt){let $=ye.filter(S=>S.canExecute&&S.fnName==="ssh_exec"),y=ye.some(S=>S.canExecute&&S.fnName!=="ssh_exec"),ee=w&&I<3;if($.length>0&&!y&&ee&&Zr<1)mt=!1,Zr++,_t=Math.max(0,vs-2),F(`${p.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Zr}/1)]${p.reset}`);else for(let S of $)S.canExecute=!1,S.errorResult={role:"tool",content:ze?`BLOCKED: ssh_exec denied \u2014 SSH paused (${vs}+ calls). Root cause is known (${at}). Edit the file now. You can still use bash("ssh user@host 'cmd'") for a single targeted lookup if essential.`:`BLOCKED: ssh_exec denied \u2014 SSH temporarily paused (${vs}+ calls). Provide a text summary of your findings first. Do NOT ask the user to run commands. SSH re-enables after your summary. For one-off lookups use bash("ssh user@host 'cmd'") instead.`,tool_call_id:S.callId}}if(w&&I<3&&!mt){for(let $ of ye)if($.canExecute&&["bash","read_file","find_files"].includes($.fnName)){I++;{let y=Qe(),{messages:ee}=jt(T,y);T=ee}F(`${p.yellow} \u26A0 Server-local guard: blocking local ${$.fnName} \u2014 use ssh_exec on 94.130.37.43${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${$.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:$.callId};break}}if(!we&&Rt&&xt&&Ct>=1){let $=["read_file","grep","search_files","glob","list_directory","find_files"];for(let y of ye)y.canExecute&&$.includes(y.fnName)&&(F(`${p.red} \u2716 Creation hard-block: ${y.fnName} denied \u2014 cap fired, files already written${p.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:y.callId})}if(In>=0){let $=ye.filter(y=>y.canExecute).length;if($>0&&(In-=$,In<0))if(!ei&&R.size>Qr){ei=!0,In=5,F(`${p.green} \u2713 Post-wipe progress detected (${R.size-Qr} files modified) \u2014 granting 5 bonus tool calls${p.reset}`);let y={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};q.push(y),T.push(y)}else{F(`${p.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${p.reset}`);for(let ee of ye)ee.canExecute&&(ee.canExecute=!1,ee.errorResult={role:"tool",content:"BLOCKED: post-wipe tool budget exhausted. No further tool calls are allowed. Summarise what was accomplished and stop.",tool_call_id:ee.callId});let y={role:"user",content:"[SYSTEM] Post-wipe tool budget exhausted. All tool calls are now blocked. Respond with a final summary of what was done and stop \u2014 do not attempt any more tool calls."};q.push(y),T.push(y)}}let rm=new Set(["edit_file","write_file","bash","ssh_exec","ask_user","spawn_agents","browser_click","browser_fill","browser_open","skill_ar_run_experiment","skill_ar_run_benchmark","skill_ar_checkpoint","skill_ar_revert","skill_ar_log_experiment","skill_ar_extract_metric"]);for(let $ of ye){if(!$.canExecute||rm.has($.fnName))continue;let y=JSON.stringify($.args||{}),ee=`${$.fnName}|${y}`,S=Dt(ii,ee);S>=2?(F(`${p.red} \u2716 Blocked duplicate: ${$.fnName}(${y.substring(0,80)}) \u2014 called ${S+1}\xD7 with identical args${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${$.fnName}() with these exact arguments has already been called ${S}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:$.callId}):S===1&&F(`${p.yellow} \u26A0 Duplicate tool call: ${$.fnName}(${y.substring(0,80)}) \u2014 2nd call with identical args${p.reset}`),Ln(ii,ee)}let Ss=l?{skipSpinner:!0,skipSummaries:!0}:{},im=ye.some($=>$.fnName==="ask_user"),el=!Ss.skipSummaries&&!ke,No=null,Hn=null;el&&!im?(ke=!0,Ss.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(Hn=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write(Yr(ye,v,!1,"blink")),No=!0):Ft||process.stdout.write(Yr(ye,v,!1)+`
|
|
1235
|
+
`)):el&&(ke=!0,Ss.skipSpinner=!0),l&&l._paused&&l.resume();let Mo=null;if(No&&process.stdout.isTTY&&ye.some(y=>y.canExecute&&(y.fnName==="bash"||y.fnName==="ssh_exec"))){let y=Date.now();Mo=setInterval(()=>{let ee=Math.round((Date.now()-y)/1e3);if(ee>=3){let S=`${Yr(ye,v,!1,"blink")} ${p.dim}[${ee}s]${p.reset}`;Hn!==null?process.stdout.write(`\x1B[${Hn};1H\x1B[2K${S}`):process.stdout.write(`\r\x1B[2K${S}`)}},1e3)}let{results:Je,summaries:am}=await Nx(ye,!0,{...Ss,skipSummaries:!0});if(Mo&&(clearInterval(Mo),Mo=null),No){No=null;let $=Yr(ye,v,!1);Hn!==null?process.stdout.write(`\x1B[${Hn};1H\x1B[2K${$}
|
|
1236
|
+
`):process.stdout.write(`\r\x1B[2K${$}
|
|
1237
|
+
`),Hn=null}if(!Ss.skipSummaries){let $=am.filter((S,A)=>!(ye[A]&&ye[A].fnName==="ask_user"));for(let S of $)console.log(S);let y=ye.filter(S=>S&&S.fnName!=="ask_user").map(S=>S.fnName),ee=Se.record(0,y,k,R);ee&&ux(ee)}for(let $ of ye){if($.canExecute||!$.errorResult)continue;let y=typeof $.errorResult.content=="string"?$.errorResult.content:"";if((y.startsWith("BLOCKED:")||y.startsWith("PLAN MODE:")||y.startsWith("PLAN PHASE:"))&&(cn++,cn>=Gc)){F(`${p.red} \u2716 Loop abort: ${cn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}}for(let $=0;$<ye.length;$++){let y=ye[$];if(!y.canExecute)continue;let ee=Je[$].content,S=ee.split(`
|
|
1238
|
+
`)[0],A=!S.startsWith("ERROR")&&!S.startsWith("CANCELLED")&&!S.startsWith("Command failed")&&!S.startsWith("EXIT");if(!A&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&S.includes("old_text not found")){let N=Pn.get(y.args.path)||0;Pn.set(y.args.path,N+1)}if(!A&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(S)){if(sn++,sn>=2){F(`${p.yellow} \u26A0 File-not-found streak: ${sn} consecutive misses \u2014 forcing search${p.reset}`);let N={role:"user",content:`[SYSTEM] ${sn} consecutive "File not found" errors. STOP guessing paths. Use search_files or glob_files to locate the correct file first, then read/edit the path returned by the search.`};q.push(N),T.push(N)}}else A&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(sn=0);if(A&&y.fnName==="write_file"&&y.args?.path){let N=y.args.path.split("/").pop(),B=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(N)&&!B){F(`${p.yellow} \u26A0 Temp file: "${N}" \u2014 delete with bash rm when done to keep the workspace clean${p.reset}`);let V={role:"user",content:`[HINT] "${y.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${y.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};q.push(V),T.push(V)}}if(A&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){Pn.delete(y.args.path),R.add(y.args.path);let N=Ln(xe,y.args.path),B=y.args.path.split("/").slice(-2).join("/");if(N===fi){F(`${p.yellow} \u26A0 Loop warning: "${B}" edited ${N}\xD7 \u2014 possible edit loop${p.reset}`);let U={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${N}\xD7. One more edit max, then move on.`};q.push(U),T.push(U)}else if(N>=Dh){F(`${p.red} \u2716 Loop abort: "${B}" edited ${N}\xD7 \u2014 aborting to prevent runaway loop${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}}if(A&&y.canExecute&&we&&(rn=0),A&&y.canExecute&&!(we&&Pe==="plan")){let N=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){qt=0,Rt=!1,Xt=0,Ct++;let ne=y.args?.path||y.args?.file_path;ne&&(mc(on,ne,1),zt.delete(ne))}else N.includes(y.fnName)&&(qt++,Rt&&Xt++);let U=n.postEditCap,V=we&&Pe==="implement"?Math.min(Kc,6):Kc,J=ze?3:xt?Ct>0?2:4:Ct>0?U:V,oe=3;if(!we&&Rt&&(ze||xt&&Ct>=1||Xt>=oe)&&N.includes(y.fnName)){let ne=ze?`root cause already identified (${at})`:Xt>=oe?`${qt} consecutive reads without an edit`:`${Ct} file edit(s) already made`;F(`${p.red} \u2716 Blocked read-only tool: cap fired, ${ne}${p.reset}`),y.canExecute=!1,y.errorResult={role:"tool",content:ze?`BLOCKED: root cause already identified (${at}). Use edit_file to fix the issue \u2014 do not read more files.`:xt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":Xt>=oe?`BLOCKED: You have read ${qt} files without making any edits. Stop investigating and either implement a fix with edit_file/write_file, or write your diagnosis as text output. Do not read more files.`:`BLOCKED: ${Ct} file edit(s) already made and post-edit investigation cap reached. The fix is in place. Do not read more files \u2014 proceed with the task.`,tool_call_id:y.callId}}else if(qt>=J&&!Rt){if(Rt=!0,F(`${p.yellow} \u26A0 Investigation cap: ${qt} read-only calls without an edit \u2014 forcing implementation${p.reset}`),we&&Pe==="plan"){let Ue=[...T].reverse().find(Ut=>Ut.role==="assistant"),yt=typeof Ue?.content=="string"?Ue.content:"",ut=ho("implement",yt);ut&&(q.push(ut),T.push(ut),We=0,Ot=Mn("implement"))}let ne;ze?ne=`[SYSTEM] Root cause was already identified (${at}). Edit the file now \u2014 do not read more files.`:mt?ne="[SYSTEM] SSH temporarily paused. Summarize your findings and state the likely diagnosis. Do NOT ask the user to run commands \u2014 SSH re-enables after your summary.":ne="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let Me={role:"user",content:ne};q.push(Me),T.push(Me)}}if((y.fnName==="bash"||y.fnName==="ssh_exec")&&y.args&&y.args.command){let N=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),B=Ln(Yc,N);if(B===qh){F(`${p.yellow} \u26A0 Loop warning: same bash command run ${B}\xD7 \u2014 possible debug loop${p.reset}`);let U={role:"user",content:`[SYSTEM WARNING] Same bash command ${B}\xD7. Debug loop detected \u2014 try a different approach.`};q.push(U),T.push(U)}else if(B>=Fh){F(`${p.red} \u2716 Loop abort: same bash command run ${B}\xD7 \u2014 aborting runaway debug loop${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}}if(y.fnName==="ssh_exec"){_t++;{let U=(Je[$]?.content??"").split(`
|
|
1239
|
+
`).map(V=>V.trim()).find(V=>V.length>0&&!V.startsWith("**")&&(V.startsWith("EXIT")||/^[\w./-]+:\s/.test(V)||V.startsWith("bash:")||V.startsWith("sh:")))??"";if(U){if(U===ti?jn++:(ti=U,jn=1),jn===3&&!mt){F(`${p.yellow} \u26A0 SSH repeated-error: "${U.slice(0,60)}" returned ${jn}\xD7 \u2014 nudging to change approach${p.reset}`);let V={role:"user",content:`[SYSTEM WARNING] The last ${jn} SSH commands all failed with the same error: "${U}". Retrying variants of the same command will not help. Switch to a different approach to accomplish the task (e.g. use a different tool, read a local file, or change the command syntax entirely).`};q.push(V),T.push(V)}}else ti="",jn=0}if(_t>=sm){F(`${p.red} \u2716 SSH storm abort: ${_t} consecutive ssh_exec calls \u2014 aborting${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}else if(_t===vs){{let U=Qe(),{messages:V}=jt(T,U);T=V}mt=!0,Kr++,F(`${p.yellow} \u26A0 SSH storm warning (#${Kr}): ${_t} consecutive ssh_exec calls \u2014 blocking further SSH${p.reset}`);let B={role:"user",content:ze?`[SYSTEM WARNING] ${_t} consecutive SSH calls. Root cause identified (${at}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${_t} consecutive SSH calls \u2014 SSH temporarily paused for synthesis. Summarize what you found and state the likely diagnosis. Do NOT ask the user to run commands or provide logs. SSH will be re-enabled after your summary so you can continue.`};q.push(B),T.push(B)}}else y.canExecute&&(_t=0);if(y.fnName==="bash"&&y.canExecute){let U=(Je[$]?.content??"").split(`
|
|
1240
|
+
`).map(V=>V.trim()).find(V=>V.length>0&&(V.startsWith("EXIT")||/^[\w./-]+:\s/.test(V)||V.startsWith("bash:")||V.startsWith("sh:")))??"";if(U){if(U===ni?Dn++:(ni=U,Dn=1),Dn===3){F(`${p.yellow} \u26A0 Bash repeated-error: "${U.slice(0,60)}" returned ${Dn}\xD7 \u2014 nudging to change approach${p.reset}`);let V={role:"user",content:`[SYSTEM WARNING] The last ${Dn} bash commands all failed with the same error: "${U}". Retrying variants of the same command will not help. Switch to a completely different approach (e.g. use a different tool, change the command syntax, or use ssh_exec to run the command on the remote server instead).`};q.push(V),T.push(V)}}else ni="",Dn=0}if(y.fnName==="bash"&&y.canExecute&&!gc&&y.args?.command){let N=Je[$]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!N.startsWith("EXIT")&&!N.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(N)||N.includes("files changed")||N.includes("file changed")||N.includes("insertions(+)")||N.includes("create mode"))){gc=!0,po=0,F(`${p.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${p.reset}`);let V={role:"user",content:"[SYSTEM] \u2713 Git commit succeeded. Your changes are committed. Do NOT run further git status / git diff / git log calls \u2014 the commit is done. Write your final summary and stop. Running extra verification commands wastes tool calls and hurts session quality."};q.push(V),T.push(V)}}if(gc&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(po++,po>2)){F(`${p.yellow} \u26A0 Post-commit git verification blocked (call ${po})${p.reset}`);let B={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(po-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};q.push(B),T.push(B)}if(A&&y.fnName==="grep"&&y.args&&y.args.pattern){let N=`${y.args.pattern}|${y.args.path||""}`,B=Ln(Bh,N);if(B===Wh){F(`${p.yellow} \u26A0 Loop warning: grep pattern "${y.args.pattern.slice(0,40)}" run ${B}\xD7 \u2014 possible search loop${p.reset}`);let U={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${B}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};q.push(U),T.push(U)}else if(B>=Uh){F(`${p.red} \u2716 Loop abort: grep pattern run ${B}\xD7 \u2014 aborting runaway search loop${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}if(y.args.path){let U=Ln(pi,y.args.path),V=Dt(Fn,y.args.path)>=1;if(U===(V?1:Hh)){let oe=y.args.path.split("/").slice(-2).join("/");F(`${p.yellow} \u26A0 Loop warning: "${oe}" grepped ${U}\xD7 with different patterns \u2014 context flood risk${p.reset}`);let he={role:"user",content:V?`[SYSTEM NOTE] "${y.args.path}" was already fully read \u2014 its content is in context. Grepping it again is redundant; use the context you already have.`:`[SYSTEM NOTE] "${y.args.path}" grepped ${U}\xD7 \u2014 use the search results already in context instead of searching again.`};q.push(he),T.push(he)}}}if(A&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){let N=y.args.pattern||y.args.query||y.args.path||"",B=Ln(Yh,N);if(B===Gh){F(`${p.yellow} \u26A0 Loop warning: glob pattern "${N.slice(0,40)}" run ${B}\xD7 \u2014 possible search loop${p.reset}`);let V={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${B}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};q.push(V),T.push(V)}else if(B>=Kh){F(`${p.red} \u2716 Loop abort: glob pattern run ${B}\xD7 \u2014 aborting runaway search loop${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}let U=N.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(V=>V.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(V));for(let V of U){let J=V.toLowerCase();ko.has(J)||ko.set(J,new Set);let oe=ko.get(J);if(oe.add(N),oe.size===Xh){F(`${p.red} \u2716 Glob core-term block: ${oe.size} different patterns all searching for "${J}" \u2014 search loop${p.reset}`);let he={role:"user",content:`[SYSTEM WARNING] You have searched for "${J}" using ${oe.size} different glob patterns. This is a search loop \u2014 the file you are looking for likely does not exist. Stop searching and work with the files you have already found, or ask the user for clarification.`};q.push(he),T.push(he)}else if(oe.size===zh){F(`${p.yellow} \u26A0 Glob core-term warning: ${oe.size} different patterns searching for "${J}"${p.reset}`);let he={role:"user",content:`[SYSTEM WARNING] ${oe.size} different glob patterns all target "${J}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};q.push(he),T.push(he)}}}let Q=(y.args?.command||y.args?.cmd||y.args?.script||"").toLowerCase(),D=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(Q)||/\/(health|status|ping|ready|alive)\b/.test(Q);if(A&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&D&&ee.includes('"valid":true')){{let B=Qe();if(Tt(T,B).percentage>=60){let{messages:V,tokensRemoved:J}=jt(T,B);J>0&&(T=V,console.log(`${p.dim} [pre-stop-compress \u2014 ~${J} tokens freed before STOP injection, now ${Math.round(Tt(T,B).percentage)}%]${p.reset}`))}}let N={role:"user",content:'[SYSTEM STOP] Tool result contains {"valid":true}. The token/service is valid and reachable. STOP all further investigation immediately. Report to the user that the token is valid, the service is healthy, and no fix is needed. Do NOT read any more log files.'};q.push(N),T.push(N),console.log(`${p.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${p.reset}`)}if(ee.startsWith("BLOCKED:")){if(cn++,cn>=Gc){F(`${p.red} \u2716 Loop abort: ${cn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}}else cn=0;if(A)an=0,gi=!0;else if(an++,an===Qh){F(`${p.yellow} \u26A0 Loop warning: ${an} consecutive tool errors \u2014 possible stuck loop${p.reset}`);let N={role:"user",content:`[SYSTEM WARNING] ${an} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};q.push(N),T.push(N)}else if(an>=em){F(`${p.red} \u2716 Loop abort: ${an} consecutive errors \u2014 aborting stuck loop${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}if(A&&y.fnName==="read_file"&&y.args&&y.args.path){k.add(y.args.path);let N=Ln(Fn,y.args.path);{let J=y.args.line_start!=null&&y.args.line_start||1,oe=y.args.line_start!=null?y.args.line_end||J+350:350;zt.has(y.args.path)||zt.set(y.args.path,[]),zt.get(y.args.path).push([J,oe])}if(y._scrollWarn){let{sectionCount:J,path:oe}=y._scrollWarn,he={role:"user",content:`[SYSTEM WARNING] "${oe}" \u2014 you have now read ${J} different sections of this file. This is a file-scroll pattern. Stop reading sections and use grep_search to find the specific lines you need instead.`};q.push(he),T.push(he),F(`${p.yellow} \u26A0 Scroll warning: "${oe.split("/").slice(-2).join("/")}" \u2014 ${J} sections read \u2014 use grep instead${p.reset}`)}let B=y.args.path.split("/").slice(-2).join("/"),U=!y.args?.line_start&&!y.args?.line_end,V=we&&Pe==="plan";if(!V&&U&&N===Vh){{let oe=Qe();if(Tt(T,oe).percentage>=60){let{messages:ne}=jt(T,oe);T=ne}}F(`${p.yellow} \u26A0 Loop warning: "${B}" read unbounded ${N}\xD7 \u2014 use line_start/line_end${p.reset}`);let J={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${N}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};q.push(J),T.push(J)}else if(!V&&U&&N>=Jh){F(`${p.red} \u2716 Loop abort: "${B}" read unbounded ${N}\xD7 \u2014 aborting runaway read loop${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}}if(y.fnName==="spawn_agents"){let N=(ee.match(/\bStatus: done\b/g)||[]).length;if((ee.match(/\bStatus: truncated\b/g)||[]).length>0&&N===0){if(ln++,ln===tm){F(`${p.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${ln}\xD7 in a row${p.reset}`);let U={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${ln}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};q.push(U),T.push(U)}else if(ln>=nm){console.log(`${p.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${ln}\xD7 \u2014 aborting stuck swarm${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H,{suppressHint:!0}),qe(q);return}}else N>0&&(ln=0)}}{let y=Je.reduce((ee,S)=>ee+(typeof S.content=="string"?S.content.length:0),0);if(y>2e5){let ee=Je.map((S,A)=>({i:A,len:typeof S.content=="string"?S.content.length:0})).sort((S,A)=>A.len-S.len);for(let{i:S,len:A}of ee){if(y<=2e5)break;let Q=y-2e5,D=Math.max(A-Q,500);D<A&&typeof Je[S].content=="string"&&(Je[S]={...Je[S],content:Je[S].content.substring(0,D)+`
|
|
1241
|
+
...(truncated ${A-D} chars \u2014 per-message budget)`},y-=A-D)}}}for(let $ of Je)q.push($),T.push($);if(!ze)for(let $=0;$<Je.length;$++){if(!ye[$]||ye[$].fnName!=="ssh_exec")continue;let y=Je[$];if(!y||typeof y.content!="string")continue;let ee=hc(y.content);if(ee){ze=!0,at=ee.slice(0,120),qt=0,Rt=!1,Xt=0,F(`${p.yellow} \u26A1 Root cause detected: ${at} \u2014 fix phase (read budget: 3)${p.reset}`);let S={role:"user",content:`[SYSTEM] Root cause identified: ${at}. Read only the file that needs fixing, then edit it. Do not read other files.`};q.push(S),T.push(S);break}}for(let $=0;$<Je.length;$++){let y=ye[$];if(!y)continue;let ee=typeof Je[$]?.content=="string"?Je[$].content:"";if(y.fnName==="create_task"){let S=ee.match(/Task #(\d+) created/),A=typeof y.args?.subject=="string"?y.args.subject:"";S&&A&&vo.set(S[1],A)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!ee.startsWith("BLOCKED:")&&ee.trim().length>0){let A=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),Q=A.split(/[._\-/]/).filter(D=>D.length>2);for(let[D,le]of vo){if(So.has(D))continue;let N=le.toLowerCase().split(/\W+/).filter(U=>U.length>3);Q.filter(U=>N.some(V=>V.includes(U)||U.includes(V))).length>=1&&(So.add(D),F(`${p.green} \u2714 Auto-matched task #${D} to ${A}: ${le.slice(0,60)}${p.reset}`))}}}{let $=Qe();if(Tt(T,$).percentage>=78){let{messages:ee,tokensRemoved:S}=jt(T,$);S>0&&(T=ee,console.log(`${p.dim} [auto-compressed \u2014 ~${S} tokens freed, now ${Math.round(Tt(T,$).percentage)}%]${p.reset}`))}}let tl=Lx();if(tl){let $={role:"user",content:`[User note mid-run]: ${tl}`};q.push($),T.push($),console.log(`${p.cyan} \u270E Context added${p.reset}`)}}if(We>=Ot){if(l&&(l.stop(),l=null),c(null),Fe(v,O,R,k,H),qe(q),ic(q),we&&Pe==="plan"){let Wn=[...q].reverse().find(Ve=>Ve.role==="assistant"),lt=typeof Wn?.content=="string"?Wn.content:"",Un=ho("implement",lt);if(Un){q.push(Un),T=[{role:"system",content:await Cc()},...q],Ot=Mn("implement"),F(`${p.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${p.reset}`);continue e}}else if(we&&Pe==="verify"){F(`${p.yellow} \u26A0 Verify budget exhausted \u2014 completing session${p.reset}`);break e}let{getActiveProviderName:be}=Ge();if(be()==="ollama"&&mi<zc){if(R.size===0&&!gi){console.log(`${p.yellow} \u26A0 Max iterations reached with no progress. Stopping.${p.reset}`);break e}mi++,Ot=20,console.log(`${p.dim} \u2500\u2500 auto-extending (+20 turns, ext ${mi}/${zc}) \u2500\u2500${p.reset}`);continue e}if(console.log(`
|
|
1242
|
+
${p.yellow}\u26A0 Max iterations reached.${p.reset}`),await mh(" Continue for 20 more turns?")){Ot=20;continue e}console.log(`${p.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${p.reset}`)}break e}}xh.exports={processInput:Gx,clearConversation:Dx,getConversationLength:Fx,getConversationMessages:Bx,setConversationMessages:Wx,setAbortSignalGetter:mx,setMaxIterations:hx,invalidateSystemPromptCache:xc,clearToolFilterCache:kx,getCachedFilteredTools:$h,buildSystemPrompt:Cc,splitSystemPrompt:jx,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Rc,getProjectContextHash:wh,buildUserContent:yh,detectAndTruncateLoop:wc,injectMidRunNote:Mx,resetSessionTracking:_h}});var Ge=re((Hv,Rh)=>{var{OllamaProvider:Kx}=El(),{OpenAIProvider:zx}=Al(),{AnthropicProvider:Xx}=Ll(),{GeminiProvider:Vx}=Dl(),{LocalProvider:Jx}=Bl(),{checkBudget:Zx}=Jo(),Dc={top:{ollama:"kimi-k2:1t",openai:"gpt-4.1",anthropic:"claude-sonnet-4-5",gemini:"gemini-2.5-pro"},strong:{ollama:"qwen3-coder:480b",openai:"gpt-4o",anthropic:"claude-sonnet",gemini:"gemini-2.5-flash"},fast:{ollama:"devstral-small-2:24b",openai:"gpt-4.1-mini",anthropic:"claude-haiku",gemini:"gemini-2.0-flash"}},Ic=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Sh={};for(let[t,e]of Object.entries(Dc))for(let s of Object.values(e))Sh[s]=t;function jc(t,e){let s=Sh[t];return s&&Dc[s][e]||t}var Xe={},ct=null,Be=null,Eo=[];function kt(){if(Object.keys(Xe).length>0)return;xs("ollama",new Kx),xs("openai",new zx),xs("anthropic",new Xx),xs("gemini",new Vx),xs("local",new Jx);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;Xe[t]?(ct=t,Be=e||Xe[t].defaultModel):(ct="ollama",Be="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(Eo=s.split(",").map(n=>n.trim()).filter(Boolean))}function xs(t,e){Xe[t]=e}function Qx(t){return kt(),Xe[t]||null}function qc(){return kt(),Xe[ct]||null}function ek(){return kt(),ct}function tk(){return kt(),Be}function nk(){kt();let t=qc();if(!t)return{id:Be,name:Be,provider:ct};let e=t.getModel(Be);return e?{...e,provider:ct}:{id:Be,name:Be,provider:ct}}function Eh(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(Xe[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function sk(t){kt();let{provider:e,model:s}=Eh(t);if(e){let o=Xe[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(ct=e,Be=s,ci(),!0):!1}let n=qc();if(n&&n.getModel(s))return Be=s,ci(),!0;for(let[o,r]of Object.entries(Xe))if(r.getModel(s))return ct=o,Be=s,ci(),!0;return!1}function ci(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=kh();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=It();t()}catch{}}function ok(){kt();let t=new Set;for(let e of Object.values(Xe))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function rk(){return kt(),Object.entries(Xe).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===ct&&s.id===Be}))}))}function ik(){kt();let t=[];for(let[e,s]of Object.entries(Xe)){let n=s.isConfigured();for(let o of Object.values(s.getModels()))t.push({spec:`${e}:${o.id}`,name:o.name,provider:e,configured:n})}return t}function ak(t){Eo=Array.isArray(t)?t:[]}function ck(){return[...Eo]}function vh(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ECONNRESET"||s==="EHOSTUNREACH"||s==="ENETUNREACH"||s==="EPIPE"||s==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function Th(t){let e=[ct,...Eo.filter(r=>r!==ct)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],a=Xe[i];if(!a||!a.isConfigured())continue;o++;let c=Zx(i);if(!c.allowed){n++,s=new Error(`Budget limit reached for ${i}: $${c.spent.toFixed(2)} / $${c.limit.toFixed(2)}`);continue}try{let l=r>0,u=l?jc(Be,i):Be;return l&&u!==Be&&process.stderr.write(` [fallback: ${i}:${u}]
|
|
1243
|
+
`),await t(a,i,u)}catch(l){if(s=l,!vh(l)||r>=e.length-1)throw l;if(i==="ollama"&&Ic.length>0){let u=isFallback?jc(Be,i):Be;for(let d of Ic)if(d!==u)try{return process.stderr.write(` [ollama fallback: ${d}]
|
|
1244
|
+
`),await t(a,i,d)}catch(f){if(s=f,!vh(f))throw f}}continue}}throw n>0&&n===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function lk(t,e,s={}){return kt(),Th((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function uk(t,e,s={}){if(kt(),s.provider){let n=Xe[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||Be,...s};try{return await n.chat(t,e,o)}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return Th(async(n,o,r)=>{try{return await n.chat(t,e,{model:r,...s})}catch(i){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw i}})}function dk(){kt();let t=[];for(let[e,s]of Object.entries(Xe))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function fk(){for(let t of Object.keys(Xe))delete Xe[t];ct=null,Be=null,Eo=[]}Rh.exports={registerProvider:xs,getProvider:Qx,getActiveProvider:qc,getActiveProviderName:ek,getActiveModelId:tk,getActiveModel:nk,setActiveModel:sk,getModelNames:ok,parseModelSpec:Eh,listProviders:rk,listAllModels:ik,callStream:lk,callChat:uk,getConfiguredProviders:dk,setFallbackChain:ak,getFallbackChain:ck,resolveModelForProvider:jc,MODEL_EQUIVALENTS:Dc,OLLAMA_FALLBACK_MODELS:Ic,_reset:fk}});var{C:W}=He(),pk=Ge(),{TOOL_DEFINITIONS:Ch}=ts(),{saveRoutingConfig:hk}=ps(),Wc=[{id:"read-package",category:"file-ops",prompt:"Read the file package.json and show me its contents.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"write-file",category:"file-ops",prompt:'Create a file at /tmp/nex-bench-test.txt with the content "benchmark run".',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&typeof t.content=="string"},{id:"edit-file",category:"file-ops",prompt:'In the file src/config.js, replace the string "debug: false" with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.old_string!==void 0&&t.new_string!==void 0||t.path&&Array.isArray(t.patches)&&t.patches.length>0)},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".js")},{id:"read-partial",category:"file-ops",prompt:"Read only lines 20 to 40 of src/index.js \u2014 I need to see that specific range.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("index")&&(typeof t.line_start=="number"||typeof t.start_line=="number")},{id:"glob-ts-defs",category:"file-ops",prompt:"Find all TypeScript type definition files (*.d.ts) anywhere in the project.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".d.ts")},{id:"write-gitignore",category:"file-ops",prompt:"Create a .gitignore file at the project root that ignores node_modules/ and dist/.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".gitignore")&&typeof t.content=="string"&&t.content.includes("node_modules")},{id:"edit-version-bump",category:"file-ops",prompt:'In package.json, change the version field from "1.0.0" to "1.1.0".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.path.includes("package"))},{id:"grep-with-filter",category:"search",prompt:"Search for all calls to require() but only inside .js files in the cli/ directory.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("require")},{id:"no-tool-http-port",category:"reasoning",prompt:"What is the default port used by the HTTP protocol?",expectedTool:null,validateArgs:()=>!0},{id:"bash-node-version",category:"shell",prompt:"Check which version of Node.js is currently installed on this system.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("node")&&(t.command.includes("--version")||t.command.includes("-v"))},{id:"search-constant",category:"search",prompt:'Search for the string "DEFAULT_MODEL" across all files in the project.',expectedTool:["search_files","grep"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("DEFAULT_MODEL")},{id:"grep-function-def",category:"search",prompt:'Find where the function "callStream" is defined in the codebase.',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:t=>JSON.stringify(t).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git")},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git status")},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let s=e?.function?.parameters||{},n=s.required||[],o=Object.keys(s.properties||{});return n.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>o.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"What is the current version of this project? Check the source files.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"multi-step-count",category:"multi-step",prompt:"How many JavaScript files are in the cli/ directory? Count them.",expectedTool:["bash","glob","list_directory"],validateArgs:t=>!!(typeof t.command=="string"&&t.command.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli")||typeof t.path=="string"&&t.path.includes("cli"))},{id:"no-tool-reasoning",category:"reasoning",prompt:'What does the acronym "API" stand for?',expectedTool:null,validateArgs:()=>!0},{id:"frontend-find-hook",category:"frontend",prompt:"Find all files that import useState from React.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("useState")},{id:"frontend-create-component",category:"frontend",prompt:"Create a React functional component called Button that accepts a label prop and renders a styled button element. Save it to src/components/Button.jsx.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".jsx")||t.path.includes(".tsx")||t.path.includes(".js"))&&typeof t.content=="string"},{id:"frontend-edit-css",category:"frontend",prompt:'In the file src/styles.css, change the background-color value from "blue" to "red".',expectedTool:["edit_file","patch_file"],validateArgs:t=>t.path&&t.old_string!==void 0?t.path.includes(".css")||t.old_string.includes("blue")||t.old_string.includes("background"):!!(t.path&&Array.isArray(t.patches))},{id:"frontend-glob-components",category:"frontend",prompt:"Find all JSX and TSX component files in the components/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&(t.pattern.includes(".jsx")||t.pattern.includes(".tsx")||t.pattern.includes("{jsx,tsx}"))},{id:"frontend-list-assets",category:"frontend",prompt:"List all files in the src/assets/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("assets")||typeof t.pattern=="string"&&t.pattern.includes("assets"))},{id:"sysadmin-port-check",category:"sysadmin",prompt:"Which process is currently listening on port 3000?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("lsof")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("3000"))},{id:"sysadmin-nginx-config",category:"sysadmin",prompt:"Create an nginx server block that proxies requests to localhost:3000. Save it to /etc/nginx/sites-available/myapp.",expectedTool:["write_file","bash"],validateArgs:t=>!!(t.path&&(t.path.includes("nginx")||t.path.includes("sites-available"))||t.command&&t.command.includes("nginx"))},{id:"sysadmin-service-status",category:"sysadmin",prompt:"Check the status of the nginx service and show if it is running.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("systemctl")||t.command.includes("service")||t.command.includes("nginx"))},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("journalctl")||t.command.includes("nginx"))},{id:"sysadmin-docker-compose",category:"sysadmin",prompt:"Create a docker-compose.yml file for a Node.js application with a PostgreSQL database.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("docker-compose")&&typeof t.content=="string"},{id:"data-sql-query",category:"data",prompt:"Write a SQL query to find all users who have not logged in for more than 30 days. Save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".sql")||t.path.includes("quer"))&&typeof t.content=="string"},{id:"data-find-json-key",category:"data",prompt:'Find all JSON files in the project that contain the key "userId".',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("userId")},{id:"data-python-csv",category:"data",prompt:'Write a Python script that reads data.csv and calculates the average of the "price" column. Save it to scripts/average_price.py.',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".py")&&typeof t.content=="string"},{id:"data-find-migrations",category:"data",prompt:"Find all database migration files in this project.",expectedTool:["glob","search_files","grep"],validateArgs:t=>JSON.stringify(t).toLowerCase().includes("migrat")},{id:"data-find-schema",category:"data",prompt:"Find where the database schema or models are defined in this project.",expectedTool:["grep","glob"],validateArgs:t=>!!(t.pattern&&/schema|model|migration/i.test(t.pattern)||t.pattern&&/schema|model|migration/i.test(t.pattern))},{id:"data-write-query",category:"data",prompt:"Write a SQL query to find all users who registered in the last 30 days and save it to queries/recent-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".sql")},{id:"data-read-env",category:"data",prompt:"Read the .env file to find the database connection string.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/\.env|env\./i.test(t.path)},{id:"resilience-edit-failed",category:"resilience",prompt:"Your edit_file call on server.js failed: old_string 'const PORT = 3000' was not found in the file. What do you do next to recover?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("server")},{id:"resilience-file-not-found",category:"resilience",prompt:"read_file returned 'file not found' for src/utils/helpers.js. You need to find where the helper functions are now. What tool do you use?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("src")||e.includes("helper")||e.includes("util")||e.includes("*.js")}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. What is the most efficient tool to use \u2014 read_file or bash with grep?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("awk"))},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. What tool do you use to find the new location?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("config")||e.includes("*.ts")||e.includes("*.js")||e.includes("find")}},{id:"resilience-bash-error-recover",category:"resilience",prompt:"The command 'npm test' failed with exit code 1. The output contains 'SyntaxError: Unexpected token' in src/parser.js:45. What is your next action?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("parser")},{id:"resilience-grep-no-match",category:"resilience",prompt:"grep returned zero matches for 'getUserById' in src/. The function exists but may have been renamed. What bash command finds all exported function names in src/ to identify the current name?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("src"))},{id:"ssh-exec-log",category:"ssh",prompt:'Show the last 50 lines of /var/log/nginx/error.log on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("log"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-service",category:"ssh",prompt:'Restart the nginx service on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("nginx")||t.command.includes("systemctl")||t.command.includes("restart"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-port",category:"ssh",prompt:'Check if port 8080 is listening on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("8080")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("lsof"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-processes",category:"ssh",prompt:'Show the top CPU-consuming processes on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("top")||t.command.includes("ps")||t.command.includes("htop"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"git-diff-staged",category:"git",prompt:"Show all staged changes before committing.",expectedTool:["git_diff","bash"],validateArgs:t=>!!(t.staged===!0||t.staged==="true"||typeof t.command=="string"&&t.command.includes("diff"))},{id:"git-log-recent",category:"git",prompt:"Show the last 5 commit messages with their hashes.",expectedTool:["git_log","bash"],validateArgs:t=>!!(typeof t.limit=="number"||typeof t.n=="number"||typeof t.command=="string"&&t.command.includes("log"))},{id:"git-status-check",category:"git",prompt:"Check if there are any uncommitted changes in the repository.",expectedTool:["git_status","bash"],validateArgs:t=>t.path===void 0&&t.command===void 0?!1:(typeof t.command=="string"&&t.command.includes("status"),!0)},{id:"agentic-test-first",category:"agentic",prompt:"Run the full test suite. If any tests fail, identify the failing test file and read it to understand the issue.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("test")||t.command.includes("jest")||t.command.includes("npm"))},{id:"agentic-read-then-act",category:"agentic",prompt:"Read the project README.md, find the TODO section, and list which items are completed.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("README")},{id:"agentic-build-deploy",category:"agentic",prompt:"Build the project with npm run build, then verify the output exists in the dist/ directory.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("build")||t.command.includes("npm"))},{id:"agentic-spawn-parallel",category:"agentic",prompt:"Search for all TODO comments and all FIXME comments across the codebase in parallel using multiple agents.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2},{id:"agentic-multi-investigate",category:"agentic",prompt:"The app is crashing on startup. Spawn parallel agents to check: (1) recent git changes, (2) npm dependency issues, (3) the main entry file for syntax errors.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2}],Ah=[{id:"phase-plan-diagnosis",category:"phase-plan",prompt:"The server returns 500 on /api/users. The error log shows: TypeError: Cannot read property 'map' of undefined at routes/users.js:42. Read the relevant file to diagnose the root cause.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/users/i.test(t.path)},{id:"phase-plan-search",category:"phase-plan",prompt:"We're getting CORS errors in production. Search the codebase for where CORS middleware is configured.",expectedTool:"grep",validateArgs:t=>typeof t.pattern=="string"&&/cors/i.test(t.pattern)},{id:"phase-plan-context",category:"phase-plan",prompt:"The login page shows a blank screen after the last deploy. Check git log for recent changes that might have broken it.",expectedTool:"git_log",validateArgs:()=>!0},{id:"phase-verify-test",category:"phase-verify",prompt:"The file src/utils.js was modified to fix a null pointer bug. Run the test suite to verify the fix works correctly.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/test|jest|npm\s+test|pytest|mocha/.test(t.command)},{id:"phase-verify-read",category:"phase-verify",prompt:"A patch was applied to config/database.js to fix the connection pool. Read the file to verify the changes look correct.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/database/i.test(t.path)},{id:"phase-verify-lint",category:"phase-verify",prompt:"Code was modified in src/components/Header.tsx. Run the linter to check for any style violations.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/lint|eslint|prettier|tsc/.test(t.command)},{id:"phase-plan-git-blame",category:"phase-plan",prompt:"A production bug was introduced 2 days ago. Use git log to find commits from the last 2 days to identify what changed.",expectedTool:"git_log",validateArgs:()=>!0},{id:"phase-plan-error-trace",category:"phase-plan",prompt:"The error stack trace mentions src/middleware/auth.js line 87. Read the file around that line to understand the bug.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/auth/i.test(t.path)},{id:"phase-plan-grep-config",category:"phase-plan",prompt:"Users report the app is using wrong API keys in staging. Search for where API_KEY is loaded from environment.",expectedTool:"grep",validateArgs:t=>typeof t.pattern=="string"&&/api.?key|env/i.test(t.pattern)},{id:"phase-verify-build",category:"phase-verify",prompt:"The TypeScript source was modified. Run the build command to verify there are no compilation errors.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&/build|tsc|compile/.test(t.command)},{id:"phase-verify-git-diff",category:"phase-verify",prompt:"Changes were just committed. Show the git diff of the last commit to verify only the intended files were modified.",expectedTool:["git_diff","bash"],validateArgs:t=>(t.command&&/git.*diff|diff.*HEAD/.test(t.command),!0)},{id:"phase-verify-read-config",category:"phase-verify",prompt:"The deployment config was updated. Read config/production.json to verify the changes are correct before deploying.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/config|production|deploy/i.test(t.path)}],di=[...Wc,...Ah],Fc=["devstral-2:123b","kimi-k2.5","glm-5:cloud","qwen3-coder:480b","qwen3-coder-next","ministral-3:14b","minimax-m2.7:cloud","kimi-k2:1t"];function mk(){try{let s=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(s))return Fc;let n=JSON.parse(require("fs").readFileSync(s,"utf-8"));return!Array.isArray(n)||n.length===0?Fc:n.filter(o=>typeof o.score=="number"&&o.score>=60).sort((o,r)=>r.score-o.score).slice(0,12).map(o=>o.model)}catch{return Fc}}var Uc=mk(),gk=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Oh=(()=>{let t=Uc.slice(0,3);return t.length>=3?t:gk})(),yk=14,li={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},$k="You are a coding assistant. Use the provided tools to help with file operations, search, and development tasks. Only call a tool when one is clearly needed to answer the request. Do not call a tool for questions you can answer from general knowledge.";async function Bc(t,e){let s={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},n=[{role:"system",content:$k},{role:"user",content:t.prompt}],o=Date.now();try{let r=await pk.callChat(n,Ch,{provider:"ollama",model:e,temperature:0,timeout:9e4});s.latencyMs=Date.now()-o;let i=r.tool_calls||[];if(t.expectedTool===null){let a=i.length===0;s.producedToolCall=a,s.correctTool=a,s.validArgs=!0,s.schemaCompliant=!0}else if(i.length>0){let a=i[0],c=a.function?.name||"unknown",l=a.function?.arguments||{};s.producedToolCall=!0,s.toolCalled=c;let u=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(s.correctTool=u.includes(c),s.correctTool){let d=Ch.find(f=>f.function?.name===c);if(s.validArgs=!!t.validateArgs(l,d),d){let f=d.function?.parameters||{},h=f.required||[],g=Object.keys(f.properties||{});s.schemaCompliant=h.every(m=>l[m]!==void 0)&&Object.keys(l).every(m=>g.includes(m))}}}}catch(r){s.latencyMs=Date.now()-o,s.error=r.message.slice(0,120)}return s}function ks(t){return t.error?0:((t.producedToolCall?li.producedToolCall:0)+(t.correctTool?li.correctTool:0)+(t.validArgs?li.validArgs:0)+(t.schemaCompliant?li.schemaCompliant:0))*100}var Nh={coding:"coding",search:"coding",shell:"coding",schema:"coding","multi-step":"coding",reasoning:"coding",frontend:"frontend",sysadmin:"sysadmin",data:"data",agentic:"agentic",resilience:"coding",ssh:"sysadmin",git:"coding","phase-plan":"plan","phase-verify":"verify"};function Hc(t){return Object.entries(t).map(([e,s])=>{let n=s.map(ks),o=n.reduce((a,c)=>a+c,0)/n.length,r=a=>Math.round(s.filter(a).length/s.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=s.filter(u=>Nh[u.category]===a);if(c.length===0)continue;let l=c.map(ks).reduce((u,d)=>u+d,0)/c.length;i[a]=Math.round(l*10)/10}return{model:e,score:Math.round(o*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(s.reduce((a,c)=>a+c.latencyMs,0)/s.length),errorCount:s.filter(a=>a.error).length,categoryScores:i,results:s}}).sort((e,s)=>s.score-e.score)}function Mh(t){let e={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=t.filter(m=>m.categoryScores[a]!==void 0&&m.score>=65).sort((m,b)=>b.categoryScores[a]-m.categoryScores[a]);if(c.length===0)continue;let u=(c[0]?.results||[]).filter(m=>Nh[m.category]===a).length;if(u<4)continue;let d=c[0],f=c[1];if(d.categoryScores[a]>=95&&u<8&&f&&d.categoryScores[a]-f.categoryScores[a]<15){let b=t.filter(x=>x.categoryScores[a]!==void 0).find(x=>x.categoryScores[a]<95);b&&(e[a]={model:b.model,score:b.categoryScores[a],avgLatency:b.avgLatency,_flukePrevented:!0});continue}let g=c.filter(m=>d.categoryScores[a]-m.categoryScores[a]<=5).sort((m,b)=>m.avgLatency-b.avgLatency)[0];e[a]={model:g.model,score:g.categoryScores[a],avgLatency:g.avgLatency}}return e}function Lh(t,e){let s=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,n=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],o=n.reduce((u,d)=>u+d.width+1,0)+1,r="\u2500".repeat(o);console.log(`
|
|
1245
|
+
${W.bold}${s}${W.reset}`),console.log(r);let i=n.map(u=>u.label.padEnd(u.width)).join(" ");if(console.log(`${W.dim}${i}${W.reset}`),console.log(r),t.forEach((u,d)=>{let f=String(d+1).padEnd(n[0].width),h=u.model.slice(0,n[1].width).padEnd(n[1].width),g=String(u.score).padEnd(n[2].width),m=`${u.toolCallRate}%`.padEnd(n[3].width),b=`${u.correctRate}%`.padEnd(n[4].width),x=`${u.validArgsRate}%`.padEnd(n[5].width),j=`${u.schemaRate}%`.padEnd(n[6].width),G=`${(u.avgLatency/1e3).toFixed(1)}s`.padEnd(n[7].width),L=u.errorCount>0?`${W.red}${u.errorCount}${W.reset}`:`${W.dim}0${W.reset}`,P=u.score>=80?W.green:u.score>=60?W.yellow:W.red,C=d===0?`${W.yellow}${f}${W.reset}`:`${W.dim}${f}${W.reset}`;console.log(`${C} ${P}${h}${W.reset} ${W.bold}${P}${g}${W.reset} ${m} ${b} ${x} ${j} ${W.dim}${G}${W.reset} ${L}`)}),console.log(r),t.length>0){let u=t[0];if(console.log(`
|
|
1246
|
+
${W.bold}${W.green}Winner: ${u.model}${W.reset} score ${u.score}/100`),t.length>1){let d=(u.score-t[1].score).toFixed(1);console.log(`${W.dim}+${d} pts over ${t[1].model}${W.reset}`)}}let a=t.filter(u=>u.results.some(d=>!d.error&&(!d.correctTool||!d.validArgs)));if(a.length>0){console.log(`${W.bold}Failing tasks:${W.reset}`);for(let u of a){let d=u.results.filter(g=>!g.error&&(!g.correctTool||!g.validArgs));if(d.length===0)continue;let f=u.model.slice(0,22),h=d.map(g=>{if(!g.correctTool){let m=g.toolCalled||"(none)";return`${W.dim}${g.taskId}${W.reset} ${W.red}\u2192${m}${W.reset}`}return`${W.dim}${g.taskId}${W.reset} ${W.yellow}bad-args${W.reset}`});console.log(` ${W.dim}${f.padEnd(22)}${W.reset} ${h.join(" ")}`)}console.log()}let c=["coding","frontend","sysadmin","data","agentic"];if(t.some(u=>Object.keys(u.categoryScores).length>1)){console.log(`
|
|
1247
|
+
${W.bold}Best model per task type:${W.reset}`);for(let u of c){let d=t.filter(m=>m.categoryScores[u]!==void 0).sort((m,b)=>b.categoryScores[u]-m.categoryScores[u]);if(d.length===0)continue;let f=d[0],h=f.categoryScores[u],g=h>=80?W.green:h>=60?W.yellow:W.red;console.log(` ${W.dim}${u.padEnd(10)}${W.reset} ${g}${f.model}${W.reset} ${W.dim}${h}/100${W.reset}`)}}console.log()}function Ph(t){if(!(!t||t.length<2))try{let e=Mh(t),{loadRoutingConfig:s}=ps(),n=s(),o={...n},r=[],i=new Set(["plan","verify"]);for(let[a,{model:c,score:l}]of Object.entries(e)){let u=i.has(a),d=u?n.phases&&n.phases[a]:n[a];d&&d!==c&&!t.find(h=>h.model===d)||(u?(o.phases||(o.phases={}),o.phases[a]!==c&&(o.phases[a]=c,r.push(`phase:${a}\u2192${c}`))):o[a]!==c&&(o[a]=c,r.push(`${a}\u2192${c}`)))}r.length>0&&(hk(o),console.log(`
|
|
1248
|
+
${W.dim} Routing updated: ${r.join(", ")}${W.reset}`),console.log(`
|
|
1249
|
+
${W.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${W.reset}`))}catch{}}async function wk({models:t,quick:e=!1,onProgress:s,parallelModels:n=1}={}){let o=e?Wc.slice(0,yk):di,r=t?.length>0?t:e?Oh:Uc,i={};for(let c of r)i[c]=[];if(n<=1)for(let c of r)for(let l of o){s?.({model:c,task:l.id,done:!1});let u=await Bc(l,c);i[c].push(u),s?.({model:c,task:l.id,done:!0,score:ks(u),error:u.error})}else{let c=Math.min(n,r.length),l=[...r],u=Array.from({length:c},async()=>{for(;l.length>0;){let d=l.shift();if(!d)break;for(let f of o){s?.({model:d,task:f.id,done:!1});let h=await Bc(f,d);i[d].push(h),s?.({model:d,task:f.id,done:!0,score:ks(h),error:h.error})}}});await Promise.all(u)}let a=Hc(i);return Lh(a,o.length),Ph(a),a}async function bk({newModels:t,existingRanking:e=[],onProgress:s}={}){if(!t||t.length===0)return e;let n={};for(let i of t){n[i]=[];for(let a of di){s?.({model:i,task:a.id,done:!1});let c=await Bc(a,i);n[i].push(c),s?.({model:i,task:a.id,done:!0,score:ks(c),error:c.error})}}let r=[...Hc(n)];for(let i of e)r.find(a=>a.model===i.model)||r.push(i);return r.sort((i,a)=>a.score-i.score),Lh(r,di.length),Ph(r),r}var ui=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function Ih(t){let e=require("fs"),n=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(n))return console.log(`${W.yellow}No scenarios configured.${W.reset} Create ${W.dim}.nex/benchmark-config.json${W.reset} to define your benchmark scenarios.
|
|
1213
1250
|
Example:
|
|
1214
1251
|
{
|
|
1215
1252
|
"scenarios": [
|
|
@@ -1222,14 +1259,14 @@ ${G.dim} Routing updated: ${r.join(", ")}${G.reset}`))}catch{}}async function Z
|
|
|
1222
1259
|
}
|
|
1223
1260
|
]
|
|
1224
1261
|
}
|
|
1225
|
-
`),
|
|
1226
|
-
`),
|
|
1227
|
-
`),
|
|
1262
|
+
`),ui;try{let o=JSON.parse(e.readFileSync(n,"utf-8"));return!Array.isArray(o.scenarios)||o.scenarios.length===0?(console.log(`${W.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${W.reset}
|
|
1263
|
+
`),ui):o.scenarios}catch(o){return console.log(`${W.yellow}Failed to parse benchmark-config.json: ${o.message}${W.reset}
|
|
1264
|
+
`),ui}}function jh(t,e){let{scoreMessages:s,_extractToolCalls:n,_getLastAssistantText:o}=jr(),r=s(t),i=r.score,a=[],c=o(t).toLowerCase();e.successCriteria.every(f=>c.includes(f.toLowerCase()))&&(i=Math.min(10,i+1),a.push("+1.0 all success criteria met"));let u=n(t);u.length<e.maxTurns/2&&(i=Math.min(10,i+.5),a.push(`+0.5 efficient (${u.length} tool calls < ${e.maxTurns/2})`)),i=Math.round(i*10)/10;let d=i>=9?"A":i>=8?"B":i>=7?"C":i>=6?"D":"F";return{score:i,grade:d,issues:r.issues,summary:r.summary,bonuses:a}}async function _k(t,e={}){let{spawn:s}=require("child_process"),n=require("fs"),o=require("path"),r=require("os"),i=o.join(r.tmpdir(),`nex-bench-${t.id}-${Date.now()}.txt`);n.writeFileSync(i,t.prompt,"utf-8");let a=o.resolve(__dirname,"..","bin","nex-code.js"),c=e.cwd||process.cwd(),l=[a,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(t.maxTurns)];return e.model&&l.push("--model",e.model),new Promise(u=>{let d=s(process.execPath,l,{cwd:c,stdio:["ignore","pipe","pipe"],env:{...process.env}}),f=t.maxTurns*60*1e3,h=!1,g=setTimeout(()=>{h=!0;try{d.kill("SIGTERM")}catch{}},f);d.on("close",m=>{clearTimeout(g);try{n.unlinkSync(i)}catch{}let b=o.join(c,".nex","sessions","_autosave.json"),x=[];if(n.existsSync(b))try{x=JSON.parse(n.readFileSync(b,"utf-8")).messages||[]}catch{}u({messages:x,exitCode:m||0,timedOut:h})}),d.stdout.resume(),d.stderr.resume()})}function xk(t,e,s){let n=t.length>0?Math.round(t.reduce((c,l)=>c+l.score,0)/t.length*10)/10:0,o=n>=9?"A":n>=8?"B":n>=7?"C":n>=6?"D":"F",r=57,i="\u2500".repeat(r);console.log(`
|
|
1228
1265
|
\u250C\u2500 Benchmark Results ${"\u2500".repeat(r-19)}\u2510`);for(let c of t){let l=c.id.padEnd(20),u=c.name.substring(0,26).padEnd(26),d=`${c.score}/10`.padStart(6),f=c.grade.padStart(2);console.log(`\u2502 ${l} ${u} ${d} ${f} \u2502`)}console.log(`\u2502 ${" ".repeat(r-2)} \u2502`);let a=`Overall: ${n}/10 (${o}) \xB7 v${e} \xB7 ${s}`;console.log(`\u2502 ${a.substring(0,r-4).padEnd(r-4)} \u2502`),console.log(`\u2514${"\u2500".repeat(r+1)}\u2518
|
|
1229
|
-
`)}function
|
|
1230
|
-
`);return}let o=[];try{o=JSON.parse(e.readFileSync(n,"utf-8"))}catch{o=[]}if(!Array.isArray(o)||o.length===0){console.log(`${
|
|
1266
|
+
`)}function kk(t=10){let e=require("fs"),n=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(n)){console.log(`${W.yellow}No score history yet. Run a session first.${W.reset}
|
|
1267
|
+
`);return}let o=[];try{o=JSON.parse(e.readFileSync(n,"utf-8"))}catch{o=[]}if(!Array.isArray(o)||o.length===0){console.log(`${W.yellow}Score history is empty.${W.reset}
|
|
1231
1268
|
`);return}let r=o.slice(-t);console.log(`
|
|
1232
|
-
${
|
|
1233
|
-
${
|
|
1234
|
-
`);for(let c of r)console.log(` ${
|
|
1235
|
-
${
|
|
1269
|
+
${W.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${W.reset}`);for(let i of r){let a=(i.date||"").replace("T"," ").substring(0,16),c=(i.version||"?").padEnd(8),l=(i.model||"?").substring(0,12).padEnd(12),u=`${i.score}/10`.padStart(6),d=i.grade||"?",f=i.issues&&i.issues.length>0?`${W.yellow}\u26A0 ${i.issues.slice(0,2).map(g=>g.substring(0,30)).join(", ")}${W.reset}`:`${W.green}\u2713${W.reset}`,h=i.score>=8?W.green:i.score>=6?W.yellow:W.red;console.log(` ${W.dim}${a}${W.reset} ${W.dim}v${c}${W.reset} ${W.dim}${l}${W.reset} ${h}${u} ${d}${W.reset} ${f}`)}console.log()}async function vk({dryRun:t=!1,model:e,cwd:s,onProgress:n}={}){let o=Lo(),r=Ih(s);if(t){console.log(`
|
|
1270
|
+
${W.bold}Scenario Benchmark \u2014 Scenarios (dry-run):${W.reset}
|
|
1271
|
+
`);for(let c of r)console.log(` ${W.cyan}${c.id.padEnd(20)}${W.reset} ${W.dim}${c.name}${W.reset} maxTurns=${c.maxTurns}`),console.log(` ${W.dim}${c.prompt.substring(0,80)}${W.reset}`);return console.log(),[]}let i=(()=>{if(e)return typeof e=="object"?e.id||"unknown":e;try{let{getActiveModel:c}=Rs(),l=c?c():null;return l?typeof l=="object"?l.id||"unknown":l:"unknown"}catch{return"unknown"}})(),a=[];for(let c of r){n?.({id:c.id,name:c.name,done:!1}),console.log(`
|
|
1272
|
+
${W.dim}Running scenario: ${c.name}...${W.reset}`);let{messages:l,timedOut:u}=await _k(c,{model:i,cwd:s}),d;u||l.length===0?d={score:0,grade:"F",issues:[u?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:d=jh(l,c);let f={id:c.id,name:c.name,score:d.score,grade:d.grade,issues:d.issues,bonuses:d.bonuses};a.push(f),n?.({id:c.id,name:c.name,done:!0,score:d.score,grade:d.grade});try{let{appendScoreHistory:h}=jr();h(d.score,{version:o.version,model:i,sessionName:`bench:${c.id}`,issues:d.issues})}catch{}}return xk(a,o.version,i),a}module.exports={runBenchmark:wk,runDiscoverBenchmark:bk,buildSummary:Hc,buildCategoryWinners:Mh,TASKS:Wc,PHASE_TASKS:Ah,ALL_TASKS:di,scoreResult:ks,DEFAULT_MODELS:Uc,QUICK_MODELS:Oh,runScenarioBenchmark:vk,showScoreTrend:kk,loadScenarios:Ih,DEFAULT_SCENARIOS:ui,scoreScenario:jh};
|