nex-code 0.4.38 → 0.4.40
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 +419 -378
- package/dist/nex-code.js +698 -632
- package/dist/skills/autoresearch.js +249 -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((Mk,fl)=>{"use strict";var il="\x1B[0m",al="\x1B[1m",Gn="\x1B[2m";function X(t,e,s){return`\x1B[38;2;${t};${e};${s}m`}function fm(){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 cl(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function pm(t){try{let s=require("fs").readFileSync(cl(),"utf8"),n=JSON.parse(s);if(n&&typeof n[t]=="boolean")return n[t]}catch{}return null}function hm(t,e){try{let s=require("fs"),n=require("path"),o=cl(),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 mm(){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=pm(s);if(n!==null)return n;let o=fm(),r=o!==null?o:!0;return hm(s,r),r}var ll=mm(),ul={reset:il,bold:al,dim:Gn,primary:X(80,190,255),secondary:X(60,170,190),success:X(80,210,120),warning:X(245,175,50),error:X(230,80,80),muted:Gn,subtle:X(130,130,145),tool_read:X(80,190,255),tool_write:X(245,165,55),tool_exec:X(185,100,235),tool_search:X(70,185,190),tool_git:X(90,210,100),tool_web:X(100,215,250),tool_sysadmin:X(225,150,75),tool_default:X(100,205,115),syn_keyword:X(185,100,235),syn_string:X(90,210,120),syn_number:X(245,175,50),syn_comment:Gn,syn_key:X(80,190,255),diff_add:X(80,210,120),diff_rem:X(230,80,80),banner_logo:X(80,200,255),banner_name:X(80,200,255),banner_version:Gn,banner_model:Gn,banner_yolo:X(245,175,50),footer_sep:Gn,footer_model:X(80,175,235),footer_branch:X(80,210,100),footer_project:X(130,130,145),footer_divider:X(80,80,95),footer_mode:X(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"},dl={reset:il,bold:al,dim:X(110,110,120),primary:X(0,110,190),secondary:X(0,125,148),success:X(0,148,62),warning:X(168,92,0),error:X(188,32,32),muted:X(110,110,120),subtle:X(155,155,165),tool_read:X(0,110,190),tool_write:X(168,92,0),tool_exec:X(128,42,188),tool_search:X(0,122,148),tool_git:X(0,138,62),tool_web:X(0,112,178),tool_sysadmin:X(168,82,0),tool_default:X(0,138,62),syn_keyword:X(128,42,188),syn_string:X(0,138,62),syn_number:X(168,92,0),syn_comment:X(135,135,148),syn_key:X(0,110,190),diff_add:X(0,148,62),diff_rem:X(188,32,32),banner_logo:X(0,122,205),banner_name:X(0,122,205),banner_version:X(100,100,118),banner_model:X(100,100,118),banner_yolo:X(168,62,0),footer_sep:X(168,168,178),footer_model:X(0,102,175),footer_branch:X(0,138,62),footer_project:X(135,135,148),footer_divider:X(168,168,178),footer_mode:X(148,88,0),white:X(40,40,52),red:X(188,32,32),green:X(0,148,62),yellow:X(168,92,0),blue:X(0,110,190),magenta:X(128,42,188),cyan:X(0,125,148),gray:X(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:X(0,158,182),brightMagenta:X(158,52,208),brightBlue:X(0,112,208)},gm=ll?ul:dl;fl.exports={T:gm,isDark:ll,DARK:ul,LIGHT:dl}});var Io=re((Lk,ym)=>{ym.exports={name:"nex-code",version:"0.4.40",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((Pk,hl)=>{var{T:te}=Es(),qo=5,Kn=(()=>{let t=[];for(let e=0;e<qo;e++)t.push(e);for(let e=qo-2;e>=1;e--)t.push(e);return t})(),pl=["\u273D","\u2726","\u2727","\u2726"],Si=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<qo;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}},Ei=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)}},jo={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Do={done:te.green,in_progress:te.cyan,pending:te.dim,failed:te.red},Qt=null,Ti=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=pl[this.frame%pl.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=jo[c.status]||jo.pending,d=Do[c.status]||Do.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),Qt=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,Qt===this&&(Qt=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=jo[c.status]||jo.pending,d=Do[c.status]||Do.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)}},Ri=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<qo;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 $m(t){Qt=t}function wm(){return Qt}function bm(){Qt&&(Qt.stop(),Qt=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}hl.exports={C:te,Spinner:Si,MultiProgress:Ei,TaskProgress:Ti,ToolProgress:Ri,setActiveTaskProgress:$m,getActiveTaskProgress:wm,cleanupTerminal:bm}});var Ci=re((Ik,$l)=>{"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"},ml={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"])},_m={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 gl(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return _m[e]||null}function xm(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 km(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 vm(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 yl(t,e,s){if(e==="json")return xm(t);if(e==="html"||e==="xml")return km(t);if(e==="css")return vm(t);if(e==="md")return t;let n=ml[e]||ml.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 Sm(t,e){let s=gl(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=>yl(r,s,o))}function Em(t,e){return e?yl(t,e,{inString:null,inBlockComment:!1}):t}$l.exports={detectLang:gl,highlightLine:Em,highlightLines:Sm}});var _l=re((jk,bl)=>{var{T:E}=Es(),Qe=E,Tm={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},Ai={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 Fo(t,e=!1,s=null){if(e)return`${E.error}\u23FA${E.reset}`;let n=Tm[t]||E.tool_default;return s==="blink"?`${n}\x1B[5m\u23FA\x1B[25m${E.reset}`:`${n}${s!==null?s:"\u23FA"}${E.reset}`}function Rm(t,e,s=!1,n=null){let o=(t||[]).filter(c=>c&&c.canExecute!==!1);if(o.length===0)return`${Fo("",s,n)} Step ${e}`;if(o.length===1){let c=o[0],l=c.args||{},u=Ai[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?`(${Qe.dim}${d}${Qe.reset})`:"";return`${Fo(c.fnName,s,n)} ${Qe.bold}${u}${Qe.reset}${f}`}let r=o[0].fnName,i=[...new Set(o.map(c=>Ai[c.fnName]||c.fnName.replace(/_/g," ")))],a=i.length<=3?i.join(", "):`${o.length} tools`;return`${Fo(r,s,n)} ${Qe.bold}${a}${Qe.reset}`}function Cm(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=Ai[t]||t.replace(/_/g," "),o=s?`(${Qe.dim}${s}${Qe.reset})`:"";return`${Fo(t)} ${Qe.bold}${n}${Qe.reset}${o}`}function Am(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 Bo=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],wl=Math.floor(Math.random()*Bo.length),Oi=null;function Om(t){Oi=t}function Nm(){let t=Bo[wl%Bo.length];wl++;let e=Oi?` \xB7 ${Oi}`:"";return`${t}${e}`}function Mm(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 Lm(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(h=>!/^File:\s/.test(h)&&!/^\[LARGE FILE:/.test(h)),l=c.length,u=c[c.length-1],d=u?parseInt(u.match(/^(\d+):/)?.[1]||"0"):0,f=e.line_start||e.line_end,m=e.path?require("path").basename(e.path):null,g=m?` ${E.muted}from ${m}${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}=Ci(),f=d(e.content||"",e.path||null),m=40,g=8;if(c<=m){let h=f.map(b=>` ${b}`).join(`
|
|
23
23
|
`);r=`${u}
|
|
24
|
-
${
|
|
24
|
+
${h}`}else{let h=f.slice(0,g).map(b=>` ${b}`).join(`
|
|
25
25
|
`);r=`${u}
|
|
26
|
-
${
|
|
27
|
-
${E.subtle}\u2026 +${c-
|
|
26
|
+
${h}
|
|
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}`:"",
|
|
30
|
-
`+
|
|
29
|
+
`),l=a.length,u=c.length,d=e.path?require("path").basename(e.path):null,f=d?` ${E.muted}${d}${E.reset}`:"",m=a.find(Y=>Y.trim()),g=c.find(Y=>Y.trim()),{highlightLine:h,detectLang:b}=Ci(),x=b(e.path||null),j=[];m&&j.push(` ${E.diff_rem}- ${E.reset}${h(m.trimEnd().substring(0,72),x)}${E.reset}`),g&&j.push(` ${E.diff_add}+ ${E.reset}${h(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",
|
|
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",m=f?l.slice(-3):l.slice(0,3),g=l.length-3,h=m.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?h.unshift(b):h.push(b)}r=h.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 Y=x.substring(0,j),A=x.substring(j+1),O=A.match(/^(\d+)[:-](.*)/s),C=O?`:${O[1]}`:"",Z=(O?O[2]:A).trim(),G=`${E.subtle}${a.basename(Y)}${C}${E.reset}`,ue=`${E.muted}${Z.substring(0,80)}${Z.length>80?"\u2026":""}${E.reset}`;return`${G} ${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}`:"",m=d>1?`${l} match${l!==1?"es":""} in ${d} files${f}`:`${l} match${l!==1?"es":""}${f}`,h=c.slice(0,3).map((x,j)=>j===0?`${m}
|
|
37
|
+
${g(x)}`:` ${g(x)}`),b=c.length-3;b>0&&h.push(` ${E.subtle}\u2026 +${b} lines${E.reset}`),r=h.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,m=d.join(", ")+(f>0?`, +${f} more`:"");r=`${u} file${u!==1?"s":""}${a} \u2014 ${E.muted}${m}${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((
|
|
43
|
+
`).find((m,g)=>g>0&&m.trim()&&!m.startsWith("Author:")&&!m.startsWith("Date:")&&!m.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(h=>/^\[/.test(h.trim()))){r=`${u} ${l.length} log lines`;break}let f=c?l.slice(-3):l.slice(0,3),m=l.length-3,g=f.map((h,b)=>b===0?`${u} ${E.muted}${h.substring(0,120)}${E.reset}`:` ${E.muted}${h.substring(0,120)}${E.reset}`);if(m>0){let h=c?` ${E.subtle}${m} lines above\u2026${E.reset}`:` ${E.subtle}\u2026 +${m} lines${E.reset}`;c?g.unshift(h):g.push(h)}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${
|
|
51
|
-
`+
|
|
49
|
+
`).filter(c=>c.trim()&&!c.startsWith("EXIT ")&&!c.startsWith("HINT:"));if(a.length>0){let c=a[0].trim().substring(0,90),l=a.length>1?` ${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 Pm(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${Qe.reset} ${Qe.bold}${t}${Qe.reset}`;return c+=`${Qe.dim} \xB7 ${a}`,r.size>0&&(c+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),c+=Qe.reset,c}bl.exports={C:Qe,formatToolCall:Cm,formatResult:Am,getToolSpinnerText:Mm,formatToolSummary:Lm,formatSectionHeader:Rm,formatMilestone:Pm,getThinkingVerb:Nm,setActiveModelForSpinner:Om,THINKING_VERBS:Bo}});var Ye=re((Dk,kl)=>{var{T:dn}=Es(),Ni=dn,xl=["01100110","01111110","01111110","01011010","01111110","00111100"];function Im(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 jm(t,e,s={}){let n=Ni.bold,o=Ni.reset,r=Im(xl,dn.banner_logo),i=s.yolo?` ${n}${dn.banner_yolo}\u26A1 YOLO${o}`:"",a=Io().version,c=[` ${dn.banner_name}${n}nex-code${o} ${dn.banner_version}v${a}${o}`,` ${dn.banner_model}${t}${o} ${dn.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=xl[0].length,m=[];for(let g=0;g<l;g++){let h=r[g-u]??" ".repeat(f),b=c[g-d]??"";m.push(h+b)}console.log(`
|
|
51
|
+
`+m.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
|
|
53
|
+
`)}var{Spinner:Dm,MultiProgress:qm,TaskProgress:Fm,ToolProgress:Bm,setActiveTaskProgress:Wm,getActiveTaskProgress:Um,cleanupTerminal:Hm}=zn(),{formatToolCall:Ym,formatResult:Gm,getToolSpinnerText:Km,formatToolSummary:zm,formatSectionHeader:Xm,formatMilestone:Vm,getThinkingVerb:Jm,setActiveModelForSpinner:Zm}=_l();kl.exports={C:Ni,banner:jm,Spinner:Dm,MultiProgress:qm,TaskProgress:Fm,ToolProgress:Bm,setActiveTaskProgress:Wm,getActiveTaskProgress:Um,cleanupTerminal:Hm,formatToolCall:Ym,formatResult:Gm,getToolSpinnerText:Km,formatToolSummary:zm,formatSectionHeader:Xm,formatMilestone:Vm,getThinkingVerb:Jm,setActiveModelForSpinner:Zm}});var Xn=re((qk,vl)=>{async function Qm(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 Mi=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`)}};vl.exports={BaseProvider:Mi,readStreamErrorBody:Qm}});var Zn=re((Fk,El)=>{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")}},Wo=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}}))}}},Uo=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 Wo(e,s)}},Ho=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}}})}}},Li="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",Yo=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};if(i&&(c.stream=!0),a?.system){let l=a.system,u=l.indexOf(Li);if(u!==-1){let d=l.slice(0,u).trimEnd(),f=l.slice(u+Li.length).trimStart();c.system=[{type:"text",text:d},{type:"text",text:f,cache_control:{type:"ephemeral"}}]}else c.system=l}return n&&n.length>0&&(c.tools=n),c}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}createStreamParser(e,s={}){return new Ho(e,s)}};function Sl(t){if(t!==null&&typeof t=="object")return t;if(typeof t!="string")return t||{};try{return JSON.parse(t)}catch{}let e=t.replace(/,\s*([}\]])/g,"$1");e=e.replace(/([^\\])\n/g,"$1\\n");try{return JSON.parse(e)}catch{}return{}}var Go=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:Sl(e.function?.arguments??e.arguments)}}))}}},Ko=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:Sl(n.function?.arguments??n.arguments)}}))}}createStreamParser(e,s={}){return new Go(e,s)}},eg=new Uo,tg=new Yo,ng=new Ko;El.exports={ANTHROPIC_CACHE_BOUNDARY:Li,WireProtocol:Vn,StreamParser:Jn,OpenAICompatibleProtocol:Uo,AnthropicProtocol:Yo,OllamaChatProtocol:Ko,OpenAIStreamParser:Wo,AnthropicStreamParser:Ho,OllamaStreamParser:Go,openaiProtocol:eg,anthropicProtocol:tg,ollamaProtocol:ng}});var Cl=re((Bk,Rl)=>{var zo=require("axios"),sg=require("http"),og=require("https"),{BaseProvider:rg,readStreamErrorBody:ig}=Xn(),{ollamaProtocol:fn}=Zn(),Xo=new sg.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Vo=new og.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Tl={"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}},Pi=class extends rg{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Tl,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){zo.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Xo,httpsAgent:Vo}).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 zo.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Xo,httpsAgent:Vo})).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=fn.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 zo.post(`${this.baseUrl}${fn.getEndpoint()}`,a,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Xo,httpsAgent:Vo})}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 fn.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=fn.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 zo.post(`${this.baseUrl}${fn.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:Xo,httpsAgent:Vo})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.status?` [HTTP ${f.response.status}]`:"",g=await ig(f,b=>b?.error),h=new Error(`API Error${m}: ${g}`);throw h.code=f.code||(f.response?.status?`HTTP_${f.response.status}`:void 0),h}let d=fn.createStreamParser(a,{onThinkingToken:c});return new Promise((f,m)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{let{done:h,result:b}=d.feed(g.toString());h&&f(b)}),u.data.on("error",g=>{if(n.signal?.aborted)return;let h=new Error(`Stream error: ${g.message}`);h.code=g.code||g.name,m(h)}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return fn.normalizeResponse(e)}};Rl.exports={OllamaProvider:Pi,OLLAMA_MODELS:Tl}});var Ml=re((Wk,Nl)=>{var Al=require("axios"),{BaseProvider:ag,readStreamErrorBody:cg}=Xn(),{openaiProtocol:pn}=Zn(),Ol={"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}},Ii=class extends ag{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Ol,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=pn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),l;try{l=await Al.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||16384,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 Al.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 m=f.response?.status?` [HTTP ${f.response.status}]`:"",g=await cg(f,h=>h?.error?.message||h?.error);throw new Error(`API Error${m}: ${g}`)}let d=pn.createStreamParser(a);return new Promise((f,m)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{let{done:h,result:b}=d.feed(g.toString());h&&f(b)}),u.data.on("error",g=>{n.signal?.aborted||m(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return pn.normalizeResponse(e)}};Nl.exports={OpenAIProvider:Ii,OPENAI_MODELS:Ol}});var jl=re((Uk,Il)=>{var Ll=require("axios"),{BaseProvider:lg,readStreamErrorBody:ug}=Xn(),{anthropicProtocol:en}=Zn(),Pl={"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}},dg="2023-06-01",ji=class extends lg{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Pl,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||dg}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 en.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=en.buildRequestBody({model:r,messages:c,tools:u,maxTokens:a,temperature:n.temperature??this.temperature,stream:!1,extra:{system:l}}),f;try{f=await Ll.post(`${this.baseUrl}${en.getEndpoint()}`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(m){if(m.name==="CanceledError"||m.name==="AbortError"||m.code==="ERR_CANCELED")throw m;let g=m.response?.status?` [HTTP ${m.response.status}]`:"",h=m.response?.data?.error?.message||m.response?.data?.error||m.message;throw new Error(`API Error${g}: ${h}`)}return en.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=en.buildRequestBody({model:r,messages:l,tools:d,maxTokens:a,temperature:n.temperature??this.temperature,stream:!0,extra:{system:u}}),m;try{m=await Ll.post(`${this.baseUrl}${en.getEndpoint()}`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let b=h.response?.status?` [HTTP ${h.response.status}]`:"",x=await ug(h,j=>j?.error?.message||j?.error);throw new Error(`API Error${b}: ${x}`)}let g=en.createStreamParser(c);return new Promise((h,b)=>{n.signal&&n.signal.addEventListener("abort",()=>{m.data.destroy(),b(new DOMException("The operation was aborted","AbortError"))},{once:!0}),m.data.on("data",x=>{let{done:j,result:Y}=g.feed(x.toString());j&&h(Y)}),m.data.on("error",x=>{n.signal?.aborted||b(new Error(`Stream error: ${x.message}`))}),m.data.on("end",()=>{h(g.flush())})})}normalizeResponse(e){return en.normalizeResponse(e)}};Il.exports={AnthropicProvider:ji,ANTHROPIC_MODELS:Pl}});var Bl=re((Hk,Fl)=>{var Dl=require("axios"),{BaseProvider:fg,readStreamErrorBody:pg}=Xn(),{openaiProtocol:hn}=Zn(),ql={"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}},Di=class extends fg{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||ql,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,{messages:a}=this.formatMessages(e),c=hn.buildRequestBody({model:o,messages:a,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!1}),l;try{l=await Dl.post(`${this.baseUrl}${hn.getEndpoint()}`,c,{timeout:n.timeout||this.timeout,headers:this._getHeaders()})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error?.message||u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return hn.normalizeResponse(l.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,a=n.onToken||(()=>{}),{messages:c}=this.formatMessages(e),l=hn.buildRequestBody({model:o,messages:c,tools:s,maxTokens:i,temperature:n.temperature??this.temperature,stream:!0}),u;try{u=await Dl.post(`${this.baseUrl}${hn.getEndpoint()}`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.status?` [HTTP ${f.response.status}]`:"",g=await pg(f,h=>h?.error?.message||h?.error);throw new Error(`API Error${m}: ${g}`)}let d=hn.createStreamParser(a);return new Promise((f,m)=>{n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{let{done:h,result:b}=d.feed(g.toString());h&&f(b)}),u.data.on("error",g=>{n.signal?.aborted||m(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{f(d.flush())})})}normalizeResponse(e){return hn.normalizeResponse(e)}};Fl.exports={GeminiProvider:Di,GEMINI_MODELS:ql}});var Hl=re((Yk,Ul)=>{var Jo=require("axios"),{BaseProvider:hg,readStreamErrorBody:mg}=Xn(),{ollamaProtocol:mn}=Zn(),Wl="http://localhost:11434",qi=class extends hg{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||Wl,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 Jo.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 Jo.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=mn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!1}),i;try{i=await Jo.post(`${this.baseUrl}${mn.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 mn.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=mn.buildRequestBody({model:o,messages:this._formatMessages(e),tools:s,maxTokens:n.maxTokens||8192,temperature:n.temperature??this.temperature,stream:!0}),a;try{a=await Jo.post(`${this.baseUrl}${mn.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 mg(l,f=>f?.error);throw new Error(`API Error${u}: ${d}`)}let c=mn.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:m}=c.feed(d.toString());f&&l(m)}),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 mn.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}};Ul.exports={LocalProvider:qi,DEFAULT_LOCAL_URL:Wl}});var gn=re((Gk,Gl)=>{"use strict";var ft=require("fs"),Yl=require("path");function gg(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function yg(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function $g(t,e){let s=Yl.dirname(t),n=Yl.join(s,`.nex-tmp.${process.pid}.${Date.now()}`);try{ft.existsSync(s)||ft.mkdirSync(s,{recursive:!0}),ft.writeFileSync(n,e,"utf-8"),ft.renameSync(n,t)}catch(o){try{ft.unlinkSync(n)}catch{}throw o}}function wg(t,e,{timeout:s=5e3,retryMs:n=50}={}){let o=t+".lock",r=Date.now()+s;for(;;){let i=-1;try{i=ft.openSync(o,"wx"),ft.writeSync(i,Buffer.from(String(process.pid))),ft.closeSync(i),i=-1;try{return e()}finally{try{ft.unlinkSync(o)}catch{}}}catch(a){if(i!==-1)try{ft.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let c=ft.readFileSync(o,"utf-8").trim(),l=parseInt(c,10);if(!gg(l)){try{ft.unlinkSync(o)}catch{}continue}}catch(c){if(c.code&&c.code!=="ENOENT")throw c;continue}if(Date.now()>=r){try{ft.unlinkSync(o)}catch{}return e()}yg(n)}}}Gl.exports={atomicWrite:$g,withFileLockSync:wg}});var Qo=re((Kk,Ql)=>{var Qn=require("fs"),Fi=require("path"),{atomicWrite:bg,withFileLockSync:_g}=gn(),Kl={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:{}},Zo=[],tn={};function xg(t,e,s,n){if(Zo.push({provider:t,model:e,input:s,output:n}),tn[t]!==void 0){let o=Jl(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 Bi(t,e){let s=Kl[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function zl(t){let e=Bi(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Xl(){let t={};for(let r of Zo){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:zl(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 kg(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=Xl();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 vg(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function Sg(t,e,s,n){let o=Bi(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Eg(){Zo=[]}function Tg(t,e){tn[t]=e}function Rg(t){delete tn[t]}function Cg(){return{...tn}}function Vl(t){let e=0;for(let s of Zo)s.provider===t&&(e+=zl(s));return e}function Jl(t){let e=Vl(t),s=tn[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 Zl(){let t=Fi.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"&&(tn={...e.costLimits})}catch{}}function Ag(){let t=Fi.join(process.cwd(),".nex"),e=Fi.join(t,"config.json");Qn.existsSync(t)||Qn.mkdirSync(t,{recursive:!0}),_g(e,()=>{let s={};if(Qn.existsSync(e))try{s=JSON.parse(Qn.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=tn,bg(e,JSON.stringify(s,null,2))})}function Og(){tn={}}Zl();Ql.exports={PRICING:Kl,trackUsage:xg,getSessionCosts:Xl,formatCosts:kg,formatCostHint:Sg,resetCosts:Eg,getPricing:Bi,setCostLimit:Tg,removeCostLimit:Rg,getCostLimits:Cg,getProviderSpend:Vl,checkBudget:Jl,loadCostLimits:Zl,saveCostLimits:Ag,resetCostLimits:Og,estimateTokens:vg}});var er=re((zk,eu)=>{function Wi(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var Ng=Wi();function Mg(...t){Wi()&&console.log(...t)}function Lg(...t){Wi()&&console.warn(...t)}eu.exports={DEBUG:Ng,debugLog:Mg,warnLog:Lg}});var su=re((Xk,nu)=>{"use strict";var Pg=new Set(["read_file","grep","glob","search_files","list_directory"]),Ig=new Set(["write_file","edit_file","patch_file"]),jg=new Set(["bash"]),Dg=new Set(["web_search","web_fetch","perplexity_search"]);function tu(t,e){let s=0,n=0,o=0,r=0,i=0;for(let[a,c]of t)i+=c,Pg.has(a)&&(s+=c),Ig.has(a)&&(n+=c),jg.has(a)&&(o+=c),Dg.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 Ui=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:tu(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}};nu.exports={MilestoneTracker:Ui,_phaseName:tu}});var Rs=re((Vk,ou)=>{var Ts=Ke(),qg={"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 Fg(){return Ts.getActiveModel()}function Bg(t){return Ts.setActiveModel(t)}function Wg(){return Ts.getModelNames()}function Ug(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 Hg(t,e){let{C:s}=Ye(),{Spinner:n}=Ye(),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 Yg(t,e){return Ts.callChat(t,e)}ou.exports={MODELS:qg,getActiveModel:Fg,setActiveModel:Bg,getModelNames:Wg,callOllamaStream:Hg,callOllama:Yg,parseToolArgs:Ug}});var As=re((Jk,uu)=>{var Gg=require("readline"),{C:Pt}=Ye(),Kg=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,zg=/^=([\w-]+)/;function Cs(t){return typeof t!="string"?t:t.replace(Kg,"").replace(zg,"$1")}var Gi=[/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/],ru=[...Gi,/\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 Xg(t){for(let e of ru)if(e.test(t))return e;return null}var iu=[/\.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)/],Vg=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,Hi=[/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 au(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)):Hi.some(c=>c.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Hi.some(a=>a.test(i))};return n.every(o)}var Ki=[/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)/],cu=[/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/],lu=[...Ki,...cu],zi=!1,yn=null,Yi=null;function Jg(t){zi=t}function Zg(t){Yi=t}function Qg(){return zi}function ey(t){yn=t}function ty(t){let e=Cs(t);for(let s of Gi)if(s.test(e))return s;return null}function ny(t){let e=Cs(t);if(/ssh\s/.test(e)&&au(e))return!1;for(let s of lu)if(s.test(e))return!0;return!1}function sy(t){let e=Cs(t);for(let s of Ki)if(s.test(e))return!0;return!1}function oy(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=Cs(t);if(!Vg.test(e))return null;for(let s of iu)if(s.test(e))return s;return null}function ry(t,e={}){if(zi)return Promise.resolve(!0);if(Yi)return Yi(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return iy(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0;yn&&yn.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${Pt.yellow}${t}${Pt.reset}`;for(let m=0;m<s.length;m++){let g=m===o,h=g?`${Pt.yellow}\u276F${Pt.reset}`:" ",b=g?`${Pt.yellow}${s[m]}${Pt.reset}`:s[m];f+=`\x1B[${d+1+m};1H\x1B[2K ${h} ${b}`}r(f)},c=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u);let f=global._nexRawWrite||(h=>process.stdout.write(h)),m=i(),g="";for(let h=0;h<s.length+1;h++)g+=`\x1B[${m+h};1H\x1B[2K`;f(g),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),yn&&yn.resume(),n(d)},l=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&tr(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 m=f.toLowerCase().trim();if(m==="y"){c(!0);return}if(m==="n"){c(!1);return}if(m==="a"&&e.toolName){tr(e.toolName),c(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function iy(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?(tr(e.toolName),n(!0)):n(i!=="n")};if(yn)yn.question(`${Pt.yellow}${t} ${s}${Pt.reset}`,o);else{let r=Gg.createInterface({input:process.stdin,output:process.stdout});r.question(`${Pt.yellow}${t} ${s}${Pt.reset}`,i=>{r.close(),o(i)})}})}var tr=()=>{};function ay(t){tr=t}uu.exports={sanitizeBashCommand:Cs,FORBIDDEN_PATTERNS:Gi,SSH_FORBIDDEN_PATTERNS:ru,BASH_PROTECTED_PATHS:iu,SSH_SAFE_PATTERNS:Hi,isSSHReadOnly:au,DANGEROUS_BASH:lu,CRITICAL_BASH:Ki,NOTABLE_BASH:cu,isForbidden:ty,isSSHForbidden:Xg,isDangerous:ny,isCritical:sy,isBashPathForbidden:oy,confirm:ry,setAutoConfirm:Jg,getAutoConfirm:Qg,setConfirmHook:Zg,setReadlineInterface:ey,setAllowAlwaysHandler:ay}});var pu=re((Qk,fu)=>{var nr=require("path"),{C:P}=Ye(),{T:Xi,isDark:Zk}=Es(),{confirm:cy,getAutoConfirm:ly}=As(),du=2e3;function Os(t,e){let s=t.split(`
|
|
63
63
|
`),n=e.split(`
|
|
64
|
-
`),o=[],r=s.length,i=n.length;if(r>
|
|
65
|
-
${
|
|
66
|
-
${
|
|
67
|
-
${
|
|
68
|
-
`),n=s.slice(0,20);for(let o of n)console.log(`${
|
|
69
|
-
${
|
|
70
|
-
`)}function
|
|
71
|
-
${
|
|
72
|
-
`);return}let
|
|
64
|
+
`),o=[],r=s.length,i=n.length;if(r>du||i>du){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 uy(t,e,s,n=3){console.log(`
|
|
65
|
+
${P.bold}${P.cyan} Diff: ${t}${P.reset}`);let o=Os(e,s),r=[];if(o.forEach((c,l)=>{c.type!=="same"&&r.push(l)}),r.length===0){console.log(`${P.gray} (no changes)${P.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(`${P.gray} ...${P.reset}`);for(let c=i;c<a;c++){let l=o[c];switch(l.type){case"remove":console.log(`${P.red} - ${l.line}${P.reset}`);break;case"add":console.log(`${P.green} + ${l.line}${P.reset}`);break;default:console.log(`${P.gray} ${l.line}${P.reset}`)}}a<o.length&&console.log(`${P.gray} ...${P.reset}`),console.log()}function dy(t,e,s){console.log(`
|
|
66
|
+
${P.bold}${P.cyan} File exists \u2014 showing changes: ${t}${P.reset}`);let n=Os(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${P.gray} (identical content)${P.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${P.gray} ...(${o-r} more changes)${P.reset}`);break}switch(i.type){case"remove":console.log(`${P.red} - ${i.line}${P.reset}`),r++;break;case"add":console.log(`${P.green} + ${i.line}${P.reset}`),r++;break;default:r>0&&console.log(`${P.gray} ${i.line}${P.reset}`)}}console.log()}function fy(t,e){console.log(`
|
|
67
|
+
${P.bold}${P.cyan} New file: ${t}${P.reset}`);let s=e.split(`
|
|
68
|
+
`),n=s.slice(0,20);for(let o of n)console.log(`${P.green} + ${o}${P.reset}`);s.length>20&&console.log(`${P.gray} ...+${s.length-20} more lines${P.reset}`),console.log()}async function py(t){return ly()?!0:cy(` ${t}?`)}function hy(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
|
|
69
|
+
${P.bold}${P.cyan} Side-by-side: ${t}${P.reset}`),console.log(` ${P.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${P.reset}`);let i=Os(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 m=[];for(;c<i.length&&i[c].type==="remove";)m.push(i[c].line),c++;let g=[];for(;c<i.length&&i[c].type==="add";)g.push(i[c].line),c++;let h=Math.max(m.length,g.length);for(let b=0;b<h;b++)a.push({left:b<m.length?m[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((m,g)=>m.type!=="same"?g:-1).filter(m=>m>=0);if(l.length===0){console.log(` ${P.gray}(no changes)${P.reset}`);return}let u=Math.max(0,l[0]-2),d=Math.min(a.length,l[l.length-1]+3),f=(m,g)=>{let h=m.replace(/\x1b\[[0-9;]*m/g,"");return h.length>=g?m.substring(0,g):m+" ".repeat(g-h.length)};u>0&&console.log(` ${P.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${P.reset}`);for(let m=u;m<d;m++){let g=a[m];if(g.type==="same")console.log(` ${P.gray}${f(g.left,r)}${P.reset}\u2502${P.gray}${f(g.right,r)}${P.reset}`);else{let h=g.left?`${P.red}${f(g.left,r)}${P.reset}`:`${f("",r)}`,b=g.right?`${P.green}${f(g.right,r)}${P.reset}`:`${f("",r)}`;console.log(` ${h}\u2502${b}`)}}d<a.length&&console.log(` ${P.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${P.reset}`),console.log(` ${P.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${P.reset}
|
|
70
|
+
`)}function my(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],a=nr.isAbsolute(t)?nr.relative(process.cwd(),t):t,c=Os(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
|
+
${P.green}\u23FA${P.reset} ${P.bold}${o}(${a})${P.reset}`),d===0&&f===0){console.log(` ${P.dim}\u23BF (no changes)${P.reset}
|
|
72
|
+
`);return}let m=[];if(d>0&&m.push(`Added ${d} line${d!==1?"s":""}`),f>0&&m.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,G=i.filter(ie=>ie.severity==="info").length,ue=[];C>0&&ue.push(`${P.red}${C} error${C!==1?"s":""}${P.dim}`),Z>0&&ue.push(`${P.yellow}${Z} warning${Z!==1?"s":""}${P.dim}`),G>0&&ue.push(`${P.cyan}${G} info${G!==1?"s":""}${P.dim}`),m.push(`found ${ue.join(", ")}`)}console.log(` ${P.dim}\u23BF ${m.join(", ")}${P.reset}`);let h=[];c.forEach((C,Z)=>{C.type!=="same"&&h.push(Z)});let b=[],x=null,j=null;for(let C of h){let Z=Math.max(0,C-r),G=Math.min(c.length-1,C+r);x===null?(x=Z,j=G):(Z<=j+1||(b.push([x,j]),x=Z),j=G)}x!==null&&b.push([x,j]);let Y=" ",A=process.stdout.columns||120;function O(C,Z,G){let ue=G.replace(/\x1b\[[0-9;]*m/g,""),ie=G+" ".repeat(Math.max(0,A-ue.length));return`${C}${Z}${ie}${P.reset}`}for(let C=0;C<b.length;C++){C>0&&console.log(`${Y}${P.dim}\xB7\xB7\xB7${P.reset}`);let[Z,G]=b[C];for(let ue=Z;ue<=G;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(O(Xi.diff_rem_bg,P.red,`${Y}${T} - ${ie.line}`)):ie.type==="add"?console.log(O(Xi.diff_add_bg,P.green,`${Y}${T} + ${ie.line}`)):console.log(`${Y}${P.dim}${T} ${P.reset}${ie.line}`);for(let K of Te){let J=P.cyan,me="\u2139";K.severity==="error"?(J=P.red,me="\u2716"):K.severity==="warn"&&(J=P.yellow,me="\u26A0"),console.log(`${Y} ${J}${me} ${K.message}${P.reset}`)}}}console.log()}function gy(t,e,s={}){let n=nr.isAbsolute(t)?nr.relative(process.cwd(),t):t,o=e.split(`
|
|
73
73
|
`),r=s.annotations||[];console.log(`
|
|
74
|
-
${
|
|
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
|
+
${P.green}\u23FA${P.reset} ${P.bold}Create(${n})${P.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(h=>h.severity==="error").length,f=r.filter(h=>h.severity==="warn").length,m=r.filter(h=>h.severity==="info").length,g=[];d>0&&g.push(`${P.red}${d} error${d!==1?"s":""}${P.dim}`),f>0&&g.push(`${P.yellow}${f} warning${f!==1?"s":""}${P.dim}`),m>0&&g.push(`${P.cyan}${m} info${m!==1?"s":""}${P.dim}`),i.push(`found ${g.join(", ")}`)}console.log(` ${P.dim}\u23BF ${i.join(", ")}${P.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),m=d+1,g=r.filter(j=>j.line===m),h=`${c}${f} + ${o[d]}`,b=h.replace(/\x1b\[[0-9;]*m/g,""),x=h+" ".repeat(Math.max(0,l-b.length));console.log(`${Xi.diff_add_bg}${P.green}${x}${P.reset}`);for(let j of g){let Y=P.cyan,A="\u2139";j.severity==="error"?(Y=P.red,A="\u2716"):j.severity==="warn"&&(Y=P.yellow,A="\u26A0"),console.log(`${c} ${Y}${A} ${j.message}${P.reset}`)}}o.length>20&&console.log(`${c}${P.dim} ...+${o.length-20} more lines${P.reset}`),console.log()}fu.exports={diffLines:Os,showEditDiff:uy,showWriteDiff:dy,showNewFilePreview:fy,confirmFileChange:py,showSideBySideDiff:hy,showDiff:my,showNewFile:gy}});var rr=re((ev,gu)=>{var hu=require("util").promisify(require("child_process").exec),yy=require("util").promisify(require("child_process").execFile),{C:Ie}=Ye();async function Vi(t){try{let{stdout:e}=await hu(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function sr(...t){try{let{stdout:e}=await yy("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function $y(){return await Vi("git rev-parse --is-inside-work-tree")==="true"}async function wy(){return await Vi("git branch --show-current")}async function Ji(){try{let{stdout:t}=await hu("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 or(t=!1){return await Vi(`git diff ${t?"--cached":""}`)||""}async function Zi(){return(await Ji()).map(e=>e.file)}async function mu(){let t=await Zi();if(t.length===0)return null;let e=await or(),n=await or(!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 by(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await sr("checkout","-b",s)!==null?s:null}async function _y(t){return await sr("add","-A"),await sr("commit","-m",t)?await sr("rev-parse","--short","HEAD"):null}async function xy(){let t=await mu();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 ky(){return(await Ji()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function vy(){let t=await Zi();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 or();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
|
+
`)}gu.exports={isGitRepo:$y,getCurrentBranch:wy,getStatus:Ji,getDiff:or,getChangedFiles:Zi,analyzeDiff:mu,createBranch:by,commit:_y,formatDiffSummary:xy,getDiffContext:vy,getMergeConflicts:ky}});var ku=re((nv,xu)=>{var ze=require("fs").promises,tv=require("fs"),wt=require("path"),Sy=require("crypto"),{execSync:Ns}=require("child_process"),Ey=100*1024,wu=50,ot=[],es=[];function Ty(t,e,s,n){for(ot.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});ot.length>wu;)ot.shift();es.length=0,bu(ot[ot.length-1]).catch(()=>{})}async function Ry(){if(ot.length===0)return null;let t=ot.pop();if(t.oldContent===null)try{await ze.unlink(t.filePath)}catch{}else await ze.writeFile(t.filePath,t.oldContent,"utf-8");return es.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Cy(){if(es.length===0)return null;let t=es.pop();return await ze.writeFile(t.filePath,t.newContent,"utf-8"),ot.push(t),{tool:t.tool,filePath:t.filePath}}function Ay(t=10){return ot.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Oy(){return ot.length}function Ny(){return es.length}function My({diskToo:t=!0}={}){if(ot.length=0,es.length=0,t){let e=ar();ze.readdir(e).then(s=>{for(let n of s)n.endsWith(".json")&&ze.unlink(wt.join(e,n)).catch(()=>{})}).catch(()=>{})}}function ar(){return wt.join(process.cwd(),".nex","history")}async function yu(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=Ey)return{inline:!0,content:t};let s=Sy.createHash("sha256").update(t,"utf-8").digest("hex"),n=wt.join(e,"blobs");return await ze.mkdir(n,{recursive:!0}),await ze.writeFile(wt.join(n,s),t,"utf-8"),{inline:!1,hash:s}}async function bu(t){let e=ar();await ze.mkdir(e,{recursive:!0});let s=wt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),n=`${t.timestamp}-${s}.json`,o=await yu(t.oldContent,e),r=await yu(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 ze.writeFile(wt.join(e,n),JSON.stringify(i),"utf-8")}async function $u(t,e){if(!t)return null;if(t.inline)return t.content;let s=wt.join(e,"blobs",t.hash);return ze.readFile(s,"utf-8")}async function Ly(){let t=ar(),e;try{e=await ze.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 ze.readFile(wt.join(t,o),"utf-8"),i=JSON.parse(r),a=await $u(i.oldContent,t),c=await $u(i.newContent,t);ot.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:a,newContent:c}),n++}catch{}for(;ot.length>wu;)ot.shift();return n}async function Py(t=7){let e=ar(),s;try{s=await ze.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 ze.readFile(wt.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 ze.unlink(wt.join(e,l))}catch{}let c=wt.join(e,"blobs");try{let l=await ze.readdir(c);for(let u of l)if(!i.has(u))try{await ze.unlink(wt.join(c,u))}catch{}}catch{}return r}var ir="nex-snapshot";function Iy(t,e=process.cwd()){let s=t?`${ir}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${ir}-${Date.now()}`;try{return Ns("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Ns(`git stash push -u -m "${s}"`,{cwd:e,timeout:15e3}),Ns("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=Ns("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(ir)?{index:parseInt(n[1],10),label:o,shortName:o.replace(`${ir}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function jy(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?(Ns(`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}}}xu.exports={recordChange:Ty,undo:Ry,redo:Cy,getHistory:Ay,getUndoCount:Oy,getRedoCount:Ny,clearHistory:My,persistEntry:bu,loadPersistedHistory:Ly,pruneHistory:Py,createSnapshot:Iy,listSnapshots:_u,restoreSnapshot:jy}});var sa=re((sv,Cu)=>{var Oe=require("fs"),rt=require("path"),{atomicWrite:Dy,withFileLockSync:qy}=gn(),tt=[];function Ms(){return rt.join(process.cwd(),".nex","skills")}function vu(){return rt.join(process.cwd(),".nex","config.json")}function Su(){let t=Ms();return Oe.existsSync(t)||Oe.mkdirSync(t,{recursive:!0}),t}function ta(){let t=vu();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 Eu(t){let e=vu(),s=rt.dirname(e);Oe.existsSync(s)||Oe.mkdirSync(s,{recursive:!0}),qy(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,Dy(e,JSON.stringify(n,null,2))})}function Tu(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 Ru(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 Qi(t){try{let e=Oe.readFileSync(t,"utf-8").trim();if(!e)return null;let s=rt.basename(t,".md"),{triggers:n,body:o}=Ru(e);return{name:s,type:"prompt",filePath:t,instructions:o||e,triggers:n,commands:[],tools:[]}}catch{return null}}function ea(t){try{let e=require(t),{valid:s,errors:n}=Tu(e,t);return s?{name:e.name||rt.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 na(){tt=[];let t=ta(),e=Ms(),s=[];if(Oe.existsSync(e))try{s=Oe.readdirSync(e)}catch{s=[]}for(let o of s){let r=rt.join(e,o),i;try{i=Oe.statSync(r)}catch{continue}if(!i.isFile())continue;let a=null;o.endsWith(".md")?a=Qi(r):o.endsWith(".js")&&(a=ea(r)),a&&(a.enabled=!t.includes(a.name),tt.push(a))}let n=rt.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=rt.join(n,r),a=rt.basename(r,rt.extname(r));if(tt.some(u=>u.name===a))continue;let c;try{c=Oe.statSync(i)}catch{continue}if(!c.isFile())continue;let l=r.endsWith(".md")?Qi(i):ea(i);l&&(l._builtin=!0,l.enabled=!t.includes(l.name),tt.push(l))}}return tt}function Fy(){let t=[];for(let e of tt)!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 By(){let t=[];for(let e of tt)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function Wy(){let t=[];for(let e of tt)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 Uy(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of tt)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 Hy(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of tt)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 Yy(){return tt.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 Gy(t){let e=tt.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=ta().filter(n=>n!==t);return Eu(s),!0}function Ky(t){let e=tt.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=ta();return s.includes(t)||(s.push(t),Eu(s)),!0}function zy(){return tt}async function Xy(t,e={}){let{execSync:s}=require("child_process"),n=Su(),o=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(o=`https://github.com/${t}.git`);let r=e.name||rt.basename(o,".git").replace(/^nex-skill-/,""),i=rt.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=rt.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 na(),{ok:!0,name:r}}async function Vy(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 Jy(t){let e=rt.join(Ms(),t);if(!Oe.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${Ms()}`};try{return Oe.rmSync(e,{recursive:!0,force:!0}),na(),{ok:!0}}catch(s){return{ok:!1,error:s.message}}}function Zy(t){if(!t)return[];let e=t.toLowerCase(),s=[];for(let n of tt){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}
|
|
96
|
-
`,c="",l=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},n);function u(f){c+=f.toString();let
|
|
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=
|
|
95
|
+
`);s.push({name:n.name,instructions:r})}}return s}Cu.exports={initSkillsDir:Su,loadAllSkills:na,getSkillInstructions:Fy,getSkillCommands:By,getSkillToolDefinitions:Wy,routeSkillCall:Uy,handleSkillCommand:Hy,listSkills:Yy,enableSkill:Gy,disableSkill:Ky,getLoadedSkills:zy,installSkill:Xy,searchSkills:Vy,removeSkill:Jy,matchSkillTriggers:Zy,_getSkillsDir:Ms,_validateScriptSkill:Tu,_loadMarkdownSkill:Qi,_loadScriptSkill:ea,_parseFrontmatter:Ru}});var ra=re((ov,Pu)=>{var{spawn:Qy}=require("child_process"),e$=require("path"),Au=require("fs"),Gt=new Map;function t$(){return e$.join(process.cwd(),".nex","config.json")}function oa(){let t=t$();if(!Au.existsSync(t))return{};try{return JSON.parse(Au.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function cr(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
|
+
`,c="",l=setTimeout(()=>{d(),r(new Error(`MCP request timeout: ${e}`))},n);function u(f){c+=f.toString();let m=c.split(`
|
|
97
|
+
`);for(let g of m)if(g.trim())try{let h=JSON.parse(g);if(h.id===i){d(),h.error?r(new Error(`MCP error: ${h.error.message||JSON.stringify(h.error)}`)):o(h.result);return}}catch{}c=m[m.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 Ou(t,e){if(Gt.has(t))return Gt.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=Qy(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await cr(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await cr(o,"tools/list",{});return r.tools=i&&i.tools||[],Gt.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Nu(t){let e=Gt.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Gt.delete(t),!0}function n$(){for(let[t]of Gt)Nu(t)}async function Mu(t,e,s={}){let n=Gt.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await cr(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 Lu(){let t=[];for(let[e,s]of Gt)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 s$(){return Lu().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function o$(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 Mu(n,o,e)}function r$(){let t=oa();return Object.entries(t).map(([e,s])=>{let n=Gt.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function i$(){let t=oa(),e=[];for(let[s,n]of Object.entries(t))try{let o=await Ou(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Pu.exports={loadMCPConfig:oa,sendRequest:cr,connectServer:Ou,disconnectServer:Nu,disconnectAll:n$,callTool:Mu,getAllTools:Lu,getMCPToolDefinitions:s$,routeMCPCall:o$,listServers:r$,connectAll:i$}});var ur=re((rv,qu)=>{var Iu=require("fs"),ia=require("path"),lr=[],Ls=[],$n={},Ps=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function ju(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 Ls.some(n=>n.definition.function.name===s)?{ok:!1,error:`Tool "${s}" is already registered`}:(Ls.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function Du(t,e){return Ps.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:($n[t]||($n[t]=[]),$n[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Ps.join(", ")}`}}async function aa(t,e){let s=$n[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 a$(){let t=ia.join(process.cwd(),".nex","plugins"),e=[];if(!Iu.existsSync(t))return{loaded:0,errors:[]};let s=Iu.readdirSync(t).filter(o=>o.endsWith(".js")),n={registerTool:ju,registerHook:Du,EVENTS:Ps};for(let o of s){let r=ia.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}lr.push({name:i.name||ia.basename(o,".js"),filePath:r})}catch(i){e.push(`${o}: ${i.message}`)}}return{loaded:lr.length,errors:e}}function c$(){return Ls.map(t=>t.definition)}async function l$(t,e,s={}){let n=Ls.find(a=>a.definition.function.name===t);if(!n)return null;let o=await aa("beforeToolExec",{name:t,args:e,options:s}),r=await n.handler(o.args||e,s);return(await aa("afterToolExec",{name:t,args:e,result:r})).result||r}function u$(){return[...lr]}function d$(){let t={};for(let e of Ps)t[e]=($n[e]||[]).length;return t}function f$(){lr.length=0,Ls.length=0;for(let t of Object.keys($n))delete $n[t]}qu.exports={registerTool:ju,registerHook:Du,emit:aa,loadPlugins:a$,getPluginToolDefinitions:c$,executePluginTool:l$,getLoadedPlugins:u$,getHookCounts:d$,clearPlugins:f$,EVENTS:Ps}});var ca=re((iv,Uu)=>{var{getSkillToolDefinitions:p$}=sa(),{getMCPToolDefinitions:h$}=ra(),{getPluginToolDefinitions:m$}=ur(),dr=new Map;function Fu(){let{TOOL_DEFINITIONS:t}=ts();return[...t,...p$(),...h$(),...m$()]}function Bu(t){if(dr.has(t))return dr.get(t);let s=Fu().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return dr.set(t,n),n}function g$(){dr.clear()}function fr(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=Wu(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Wu(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 y$(t,e){let s=Bu(t);if(s===null){let d=Fu().map(m=>m.function.name),f=fr(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=fr(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=fr(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 $$(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}}Uu.exports={validateToolArgs:y$,validateToolCallFormat:$$,closestMatch:fr,levenshtein:Wu,getCachedSchema:Bu,clearSchemaCache:g$}});var Ku=re((av,Gu)=>{var{levenshtein:pr}=ca(),w$=200,b$=.3,_$=2;function la(t){return t.replace(/\r\n/g,`
|
|
104
104
|
`).replace(/\r/g,`
|
|
105
|
-
`).replace(/\t/g," ".repeat(
|
|
105
|
+
`).replace(/\t/g," ".repeat(_$)).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 x$(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=la(t),n=la(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 k$(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
|
-
`),
|
|
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(
|
|
113
|
+
`).length;return s.length===0||o===0?null:o===1?v$(s,e):E$(s,e,o)}function Hu(t){return Math.max(1,Math.floor(t/w$))}function Yu(t,e){return t<=Math.ceil(e*b$)}function v$(t,e){let s=e.trim(),n=Hu(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=pr(a.trim(),s);c<r&&(r=c,o={text:a,distance:c,line:i+1})}return o&&n>1&&(o=S$(t,s,o,n)||o,r=o.distance),Yu(r,e.length)?o:null}function S$(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=pr(u.trim(),e);d<a&&(a=d,c={text:u,distance:d,line:l+1})}return c}function E$(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Hu(n),r=null,i=1/0;for(let a=0;a<n;a+=o){let c=t.slice(a,a+s).join(`
|
|
114
|
+
`),l=pr(c,e);l<i&&(i=l,r={text:c,distance:l,line:a+1})}return r&&o>1&&(r=T$(t,e,r,o,s,n)||r,i=r.distance),Yu(i,e.length)?r:null}function T$(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
|
+
`),m=pr(f,e);m<l&&(l=m,u={text:f,distance:m,line:d+1})}return u}Gu.exports={normalizeWhitespace:la,fuzzyFindText:x$,findMostSimilar:k$}});var Xu=re((lv,zu)=>{var{C:cv}=Ye(),R$=[{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}],C$=[{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 A$(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 R$)c.regex.test(i)&&n.push({line:a,message:`Potential secret detected: ${c.name}`,severity:"error"});for(let c of C$)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 O$(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}zu.exports={runDiagnostics:A$,getMemoryUsage:O$}});var ha=re((uv,td)=>{var ns=require("fs").promises,ss=require("path"),{exec:N$}=require("util").promisify(require("child_process").exec),os=[],pa=null,hr=!1,da=0,M$=6e4;function Ju(t){return!(os.length===0||pa!==t||Date.now()-da>M$)}async function Zu(t){if(!hr&&!Ju(t)){hr=!0,pa=t;try{try{let{stdout:n}=await N$("rg --files",{cwd:t,timeout:5e3});os=n.split(`
|
|
117
|
+
`).filter(Boolean),da=Date.now(),hr=!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,da=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{hr=!1}}}function fa(){return os}function L$(){return pa}function P$(t){return os.filter(e=>ss.basename(e)===t)}function I$(t){let e=t.toLowerCase();return os.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}var ua=null,Vu=0,j$=12e4,D$=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Qu(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(m=>m.trim().split(":")[0].trim()).filter(Boolean);for(let m of f)/^\w+$/.test(m)&&s.push({type:"export",name:m,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 ed(t){t=t||process.cwd();let e=ss.join(t,".nex","index","content-index.json"),s={};if(ua&&Date.now()-Vu<j$)return ua;try{let i=await ns.readFile(e,"utf-8");s=JSON.parse(i)}catch{s={files:{}}}fa().length===0&&await Zu(t);let o={files:{}},r=!1;for(let i of fa()){let a=ss.extname(i);if(!D$.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=Qu(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 ua=o,Vu=Date.now(),o}async function q$(t,e){let s=await ed(),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)}td.exports={refreshIndex:Zu,getFileIndex:fa,getIndexedCwd:L$,findFileInIndex:P$,searchIndex:I$,isIndexValid:Ju,buildContentIndex:ed,searchContentIndex:q$,extractDefinitions:Qu}});var ga=re((dv,rd)=>{var mr=require("fs"),yr=require("path"),$r=require("os"),{execFile:F$}=require("child_process"),{promisify:B$}=require("util"),ma=B$(F$),W$=yr.join($r.homedir(),".nex","servers.json"),gr=yr.join($r.tmpdir(),"nex-ssh-sockets");function U$(){return yr.join(process.cwd(),".nex","servers.json")}function nd(){let t=n=>{if(!mr.existsSync(n))return{};try{return JSON.parse(mr.readFileSync(n,"utf-8"))}catch{return{}}},e=t(W$),s=t(U$());return{...e,...s}}function H$(t){let e=nd();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 Y$(){mr.existsSync(gr)||mr.mkdirSync(gr,{recursive:!0})}function sd(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,$r.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),Y$();let s=t.user?`${t.user}@${t.host}`:t.host,n=yr.join(gr,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function od(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,$r.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function G$(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=sd(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:a}=await ma("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:wr(c,t)}}}async function K$(t,e,s,{timeout:n=12e4}={}){let o=od(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:a}=await ma("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(wr(a,t)||a)}}async function z$(t,e,s,{timeout:n=12e4}={}){let o=od(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:a}=await ma("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(wr(a,t)||a)}}function wr(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 X$(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}`}rd.exports={loadServerProfiles:nd,resolveProfile:H$,buildSSHArgs:sd,sshExec:G$,scpUpload:K$,scpDownload:z$,enrichSSHError:wr,formatProfile:X$,SSH_SOCKET_DIR:gr}});var cd=re((fv,ad)=>{var Is=require("fs"),ya=require("path"),V$=ya.join(".nex","deploy.json");function $a(){return ya.join(process.cwd(),V$)}function id(){let t=$a();if(!Is.existsSync(t))return{};try{return JSON.parse(Is.readFileSync(t,"utf-8"))}catch{return{}}}function J$(t){let e=id();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 Z$(t){let e=ya.join(process.cwd(),".nex");Is.existsSync(e)||Is.mkdirSync(e,{recursive:!0}),Is.writeFileSync($a(),JSON.stringify(t,null,2)+`
|
|
125
|
+
`,"utf-8")}ad.exports={loadDeployConfigs:id,resolveDeployConfig:J$,saveDeployConfigs:Z$,getDeployConfigPath:$a}});var Fs=re((pv,dd)=>{var{getActiveModel:Q$,getActiveProviderName:ew}=Ke(),js={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},Ds={"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"},qs={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},It={};function ud(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(It=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{It={}}}ud();function wa(){let e=Q$()?.id,s=ew();return e&&It[e]?It[e]:s&&It[`${s}:*`]?It[`${s}:*`]:e&&Ds[e]?Ds[e]:s&&qs[s]?qs[s]:"full"}var tw=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"]),ld={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function nw(t,e){return t&&(tw.has(t)||t.startsWith("claude-"))?"strict":e&&ld[e]?ld[e]:"fuzzy"}function sw(t,e){return t&&It[t]?It[t]:e&&It[`${e}:*`]?It[`${e}:*`]:t&&Ds[t]?Ds[t]:e&&qs[e]?qs[e]:"full"}function ow(t,e){let s=e||wa();if(s==="full"||!js[s])return t;let n=new Set(js[s]);return t.filter(o=>n.has(o.function.name))}function rw(){let t=wa(),e=js[t]?js[t].length:"all";return{tier:t,toolCount:e}}dd.exports={filterToolsForModel:ow,getActiveTier:wa,getModelTier:sw,getEditMode:nw,getTierInfo:rw,TIERS:js,MODEL_TIERS:Ds,PROVIDER_DEFAULT_TIER:qs,loadConfigOverrides:ud}});var Ws=re((hv,hd)=>{var ba=null,Kt=null,Bs=null,fd=`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 pd(){if(Bs!==null)return Bs;try{require("playwright"),Bs=!0}catch{Bs=!1}return Bs}async function br(){if(!pd())throw new Error(fd);return ba||(ba=require("playwright")),(!Kt||!Kt.isConnected())&&(Kt=await ba.chromium.launch({headless:!0})),Kt}async function iw(){if(Kt){try{await Kt.close()}catch{}Kt=null}}process.on("exit",()=>{if(Kt)try{Kt.close()}catch{}});async function aw(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await br()).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 cw(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await br()).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 lw(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await br()).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 uw(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 br()).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()}}hd.exports={isPlaywrightAvailable:pd,browserNavigate:aw,browserScreenshot:cw,browserClick:lw,browserFill:uw,closeBrowser:iw,INSTALL_MSG:fd}});var _a=re((mv,md)=>{var{C:Ne}=Ye(),Hs="",nt=[],Us=0,wn=null;function dw(t){wn=t}function fw(t,e){Hs=t,nt=[],Us=0;for(let n of e){Us++;let o=`t${Us}`;nt.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${Us}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=nt.map(n=>({...n}));return wn&&wn("create",{name:t,tasks:s}),s}function pw(t,e,s){let n=nt.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),wn&&wn("update",{id:t,status:e,result:s}),{...n}):null}function hw(){return{name:Hs,tasks:nt.map(t=>({...t}))}}function mw(){Hs="",nt=[],Us=0,wn&&wn("clear",{})}function gw(){return nt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=nt.find(n=>n.id===e);return s&&s.status==="done"}))}function yw(){if(nt.length===0)return`${Ne.dim}No active tasks${Ne.reset}`;let t=[];Hs&&(t.push(` ${Ne.bold}${Ne.cyan}Tasks: ${Hs}${Ne.reset}`),t.push(` ${Ne.dim}${"\u2500".repeat(40)}${Ne.reset}`));for(let o of nt){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=nt.filter(o=>o.status==="done").length,s=nt.filter(o=>o.status==="failed").length,n=nt.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 $w(){return nt.length>0&&nt.some(t=>t.status==="pending"||t.status==="in_progress")}md.exports={createTasks:fw,updateTask:pw,getTaskList:hw,clearTasks:mw,getReadyTasks:gw,renderTaskList:yw,setOnChange:dw,hasActiveTasks:$w}});var _r=re((gv,yd)=>{var Ys={"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.`}},gd={staleWarn:6e4,staleAbort:12e4,investigationCap:12,postEditCap:10};function ww(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let r of Object.keys(Ys))e.startsWith(r)&&r.length>n&&(s=r,n=r.length);let o=s?{...Ys[s]}:{...gd};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 bw(t){let e=(t||"").toLowerCase(),s=null,n=0;for(let o of Object.keys(Ys))e.startsWith(o)&&o.length>n&&(s=o,n=o.length);return s&&Ys[s].briefing||""}yd.exports={getModelProfile:ww,getModelBriefing:bw,PROFILES:Ys,DEFAULTS:gd}});var ka=re((yv,kd)=>{var{callChat:_w}=Ke(),{estimateTokens:xa}=jt(),$d=process.env.NEX_COMPACTION!=="false",wd=6,bd=2e3,_d=3,xw=`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>`,bn=0;async function kw(t){if(!$d||t.length<wd||bn>=_d)return null;let e=[{role:"system",content:xw},{role:"user",content:xd(t)}];try{let n=((await _w(e,[],{temperature:0,maxTokens:bd})).content||"").trim();if(!n)return bn++,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 bn++,null;let r=t.reduce((a,c)=>a+xa(c.content||"")+(c.tool_calls?xa(JSON.stringify(c.tool_calls)):0),0),i=xa(n);return i>=r*.8?(bn++,null):(bn=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
175
|
+
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return bn++,null}}function vw(){bn=0}function xd(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
|
+
`)}kd.exports={compactMessages:kw,formatMessagesForSummary:xd,resetCompactionFailures:vw,COMPACTION_ENABLED:$d,COMPACTION_MIN_MESSAGES:wd,COMPACTION_SUMMARY_BUDGET:bd,MAX_CONSECUTIVE_FAILURES:_d}});var jt=re(($v,Md)=>{var Sw=require("path");function Sd(){return Ke().getActiveModel()}var Ew={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},Tw={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},_n=new Map,vd=1e3,va=new WeakMap,xn=null;function Rw(){if(xn!==null)return xn;try{let t=Sd(),e=t?.provider||"ollama",s=(t?.id||"").toLowerCase();for(let[n,o]of Object.entries(Tw))if(s.startsWith(n))return xn=o,xn;return xn=Ew[e]||4,xn}catch{return 4}}function Cw(){xn=null}function kn(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=_n.get(e);if(s!==void 0)return _n.delete(e),_n.set(e,s),s;let n=Math.ceil(t.length/Rw());if(_n.size>=vd){let o=vd>>1,r=_n.keys();for(let i=0;i<o;i++)_n.delete(r.next().value)}return _n.set(e,n),n}function Aw(t){if(va.has(t))return va.get(t);let e=JSON.stringify(t);return va.set(t,e),e}function as(t){let s=4;if(t.content&&(s+=kn(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=kn(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=kn(o):o&&(s+=kn(JSON.stringify(o)))}return s}function bt(t){let e=0;for(let s of t)e+=as(s);return e}function Ow(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 xr(t){return!t||t.length===0?0:kn(JSON.stringify(t))}function kr(){return Sd()?.contextWindow||32768}function Nw(t,e){let s=bt(t),n=xr(e),o=s+n,r=kr(),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 Gs=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,Ed=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,Td=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Rd={essential:.6,standard:.65,full:Math.min(Gs,.68)};function Cd(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Gs;try{let{getActiveTier:t}=Fs(),e=t();return Rd[e]??Gs}catch{return Gs}}var Mw=200,Lw=1e3;function Ad(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),h=Math.floor(n*.4),b=t.substring(0,g),x=t.substring(t.length-h);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 h=g+1;for(;h<o.length&&c<l*1.5&&!o[h].trim().startsWith("```");)a.push(o[h]),c+=o[h].length+1,h++;h<o.length&&o[h].trim().startsWith("```")&&(a.push(o[h]),c+=o[h].length+1),g=h}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 h=g-1;for(;h>=0&&d<f*1.5&&!o[h].trim().startsWith("```");)u.push(o[h]),d+=o[h].length+1,h--;h>=0&&o[h].trim().startsWith("```")&&(u.push(o[h]),d+=o[h].length+1),g=h}else u.push(o[g]),d+=o[g].length+1;u.reverse();let m=o.length-a.length-u.length;return a.join(`
|
|
155
182
|
`)+`
|
|
156
|
-
...(${
|
|
183
|
+
...(${m} 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
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
185
|
+
`)}function is(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:Lw,n=e==="aggressive"?50:e==="medium"?100:Mw;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:Ad(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 Od(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(Sw.basename(c)))&&a++;o+=Math.min(30,a*10)}return Math.min(100,o)}function Nd(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 Pw(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 Iw(){rs={msgCount:-1,lastMsgRef:null,result:null}}async function jw(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??Cd(),r=s.safetyMargin??Ed,i=s.keepRecent??Td,a=kr(),c=xr(e),l=Math.floor(a*(o-r)),u=l-c,d=bt(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 m=d,g=null,h=0;t.length>0&&t[0].role==="system"&&(g=t[0],h=1);let b=Math.max(h,t.length-i),x=t.slice(h,b),j=t.slice(b),Y=x.filter(se=>se._pinned),A=x.filter(se=>!se._compacted&&!se._pinned);if(A.length>=6)try{let{compactMessages:se}=ka(),T=await se(A);if(T){let Te=x.filter(fe=>fe._compacted&&!fe._pinned),K=[...Y,...Te,T.message],J=nn(g,K,j),me=bt(J);if(me+c<=l)return{messages:J,compressed:!0,compacted:!0,tokensRemoved:m-me};x=K}}catch(se){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",se.message)}let O=(f-l)/l,C=x.map(se=>is(se,"light")),Z=nn(g,C,j),G=bt(Z);if(G+c<=l)return{messages:Z,compressed:!0,compacted:!1,tokensRemoved:m-G};if(C=x.map(se=>is(se,"medium")),Z=nn(g,C,j),G=bt(Z),G+c<=l)return{messages:Z,compressed:!0,compacted:!1,tokensRemoved:m-G};if(C=x.map(se=>is(se,"aggressive")),Z=nn(g,C,j),G=bt(Z),G+c<=l)return{messages:Z,compressed:!0,compacted:!1,tokensRemoved:m-G};let ue=Nd([...C,...j]),ie=C.map((se,T)=>({msg:se,score:se._pinned?1/0:Od(se,T,C.length,ue),tokens:as(se)}));for(;ie.length>0&&G>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;G-=ie[se].tokens,ie.splice(se,1)}return C=ie.map(se=>se.msg),Z=nn(g,C,j),G=bt(Z),{messages:Z,compressed:!0,compacted:!1,tokensRemoved:m-G}}function nn(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function Dw(t,e){if(!t)return"";if(kn(t)<=e)return t;let n=e*4,o=t.split(`
|
|
191
|
+
`),r=Math.floor(n*.6),i=Math.floor(n*.4),a="",c=0;for(let m of o){if(a.length+m.length+1>r)break;a+=(a?`
|
|
192
|
+
`:"")+m,c++}let l="",u=0;for(let m=o.length-1;m>=c;m--){let g=o[m]+(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 qw=6;function Fw(t,e,s=!1){let n=kr(),o=xr(e),r=Math.floor(n*(s?.35:.5))-o,i=bt(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:qw,d=Math.max(l,t.length-u),f=t.slice(l,d),m=t.slice(d),g=f.map(O=>is(O,"aggressive"));s&&(m=m.map(O=>is(O,"aggressive")));let h=nn(c,g,m),b=bt(h);for(;g.length>0&&b>r;){let O=g.shift();b-=as(O)}s&&b>r&&(m=m.filter(C=>C.role==="user").slice(-1),h=nn(c,[],m),b=bt(h)),h=nn(c,g,m);let x=t.filter(O=>O.role==="user"),j=O=>{let C=typeof O.content=="string"?O.content:"";return C.startsWith("[SYSTEM WARNING]")||C.startsWith("[SYSTEM:")||C.startsWith("BLOCKED:")},Y=x.find(O=>!j(O)),A=[...x].reverse().find(O=>!j(O));if(Y&&!h.find(O=>O===Y)){let O=h.findIndex(Z=>Z.role==="system"),C=O>=0?O+1:0;h.splice(C,0,Y)}return A&&A!==Y&&!h.find(O=>O===A)&&h.push(A),{messages:h,tokensRemoved:i-bt(h)}}Md.exports={estimateTokens:kn,estimateMessageTokens:as,estimateMessagesTokens:bt,estimateDeltaTokens:Ow,estimateToolsTokens:xr,serializeMessage:Aw,getContextWindow:kr,getUsage:Nw,compressMessage:is,compressToolResult:Ad,scoreMessageRelevance:Od,extractActiveFiles:Nd,buildProgressSnapshot:Pw,fitToContext:jw,forceCompress:Fw,truncateFileContent:Dw,invalidateTokenRatioCache:Cw,invalidateFitToContextCache:Iw,getEffectiveCompressionThreshold:Cd,COMPRESSION_THRESHOLD:Gs,TIER_COMPRESSION_THRESHOLDS:Rd,SAFETY_MARGIN:Ed,KEEP_RECENT:Td}});var Ra=re((bv,tf)=>{var{callStream:Bw,getActiveProviderName:Sr,getActiveModelId:Ld,getConfiguredProviders:Ww,getProvider:Pd,getActiveProvider:Id,parseModelSpec:jd}=Ke(),{parseToolArgs:Dd}=Rs(),{filterToolsForModel:Uw,getModelTier:vr}=Fs(),{getModelBriefing:Hw}=_r(),{trackUsage:qd,estimateTokens:Fd}=Qo(),{MultiProgress:Yw,C:wv}=Ye();function Bd(t){return!t||typeof t!="string"?0:typeof Fd=="function"?Fd(t):Math.ceil(t.length/4)}var Hd=15,Gw=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),Wd=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Yd=8,Kw=2,Er=new Map,Gd=600*1e3;function zw(t,e){let s=Er.get(t);return s&&s.agentId!==e&&Date.now()-s.timestamp<Gd?!1:(Er.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Ks(t){Er.delete(t)}function Sa(){Er.clear()}function Ea(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 Kd(t){let e=Ea(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function zd(t,e,s){let n;for(let o=0;o<=Wd;o++)try{return await Bw(t,e,s)}catch(r){n=r;let i=Ea(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<Wd&&Kd(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 Ud=new Set(["ask_user","task_list"]);function Xd(t){return t>=2?new Set([...Ud,"spawn_agents"]):Ud}var Xw=new Set(["write_file","edit_file","patch_file"]),Vd={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:""}},Vw=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Jw=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Jd(t){return Jw.test(t)?"full":Vw.test(t)?"essential":t.length>300?"full":"standard"}function Zd(t){let e=Ww(),s=Sr(),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(vr(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Zw={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Ta(t){if(t.model){let{provider:o,model:r}=jd(t.model),i=o?Pd(o):Id(),a=o||Sr();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=vr(r,a);return{provider:a,model:r,tier:c}}}let e=Jd(t.task),s=Zw[e];if(s){let{provider:o,model:r}=jd(s),i=o?Pd(o):Id(),a=o||Sr();if(i&&i.isConfigured()&&(i.getModel(r)||a==="local")){let c=vr(r,a);return{provider:a,model:r,tier:c}}}let n=Zd(e);if(n){let o=vr(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function Qd(t,e={},s=0){let n=s===0?Hd:Yd,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&&Vd[t.type],f=d&&d.systemSuffix?`
|
|
189
220
|
|
|
190
|
-
${d.systemSuffix}`:"",
|
|
191
|
-
${
|
|
221
|
+
${d.systemSuffix}`:"",m=Ta(t),g=m.provider,h=m.model,b=m.tier,x=Hw(h||Ld()),Y=[{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
|
|
201
|
-
...(truncated)`}let
|
|
202
|
-
${d}`),c+=r(d),c>=i)break}if(a.length===0)return
|
|
226
|
+
`:"")+u+f}];Y.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:A,executeTool:O}=ts(),C=Xd(s),Z=Uw(A.filter(ue=>!C.has(ue.function.name)),b);if(d&&d.allowedTools&&(Z=Z.filter(ue=>d.allowedTools.has(ue.function.name))),h&&!t._skipLog){let ue=b?` (${b})`:"";process.stderr.write(` [sub-agent: ${g}:${h}${ue}]
|
|
227
|
+
`)}let G={};g&&(G.provider=g),h&&(G.model=h);try{for(let ie=0;ie<o;ie++){let se=await zd(Y,Z,G);if(!se||typeof se!="object")throw new Error("Empty or invalid response from provider");{let fe=g||Sr(),$e=h||Ld();if(se.usage){let pe=se.usage.prompt_tokens||0,Re=se.usage.completion_tokens||0;a.input+=pe,a.output+=Re,qd(fe,$e,pe,Re)}else{let pe=se.content||"",Re=Y.map(v=>typeof v.content=="string"?v.content:Array.isArray(v.content)?v.content.map(M=>typeof M=="string"?M:M.text||"").join(""):"").join(" "),w=Bd(Re),I=Bd(pe);a.input+=w,a.output+=I,a._estimated=!0,qd(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),Y.push(K),!Te||Te.length===0){for(let fe of c)Ks(fe);return{task:t.task,status:"done",result:T||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:g&&h?`${g}:${h}`:null}}let J=Te.map(fe=>{let $e=fe.function.name,pe=Dd(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(Xw.has($e)&&pe.path){let v=require("path"),M=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(),M);if(t._readOnlyFiles.some(H=>R===H||R.startsWith(H+"/")||M===H||M.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(M)||!zw(M,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(M),w=M}return i.push($e),e.onUpdate&&e.onUpdate({type:"tool_call",tool:$e,agentId:r}),($e==="spawn_agents"?ef(pe,s+1):O($e,pe,{autoConfirm:!0,silent:!0})).then(v=>{w&&(Ks(w),c.delete(w));let M=String(v??"");return{role:"tool",content:M.length>2e4?M.substring(0,2e4)+`
|
|
228
|
+
...(truncated)`:M,tool_call_id:Re}}).catch(v=>(w&&(Ks(w),c.delete(w)),{role:"tool",content:`ERROR: ${v.message}`,tool_call_id:Re}))}),me=await Promise.all(J);if(Y.push(...me),ie>=7&&Y.length>12)try{let{compressMessage:fe}=jt(),$e=Y.length-6;for(let pe=1;pe<$e;pe++)Y[pe]._subAgentCompressed||(Y[pe]={...fe(Y[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=Dd($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)Ks(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:Y[Y.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:g&&h?`${g}:${h}`:null}}catch(ue){for(let ie of c)Ks(ie);return{task:t.task,status:"failed",result:`Error: ${ue.message}`,toolsUsed:i,tokensUsed:a,modelSpec:g&&h?`${g}:${h}`:null}}}async function ef(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?Gw:Kw,n=e===0?Hd:Yd,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=>Ta(u)),c=o.map((u,d)=>{let f=a[d],m=f.model?` [${f.model}]`:"",g=u.task.substring(0,i-m.length);return`${r}Agent ${d+1}${m}: ${g}${u.task.length>g.length?"...":""}`}),l=new Yw(c);l.start();try{let u=o.map((h,b)=>{let x=a[b],j=Math.min(h.max_iterations||n,n),Y=x.model?{...h,model:`${x.provider}:${x.model}`,_skipLog:!0,max_iterations:j}:{...h,_skipLog:!0,max_iterations:j};return Qd(Y,{onUpdate:()=>{}},e).then(A=>(l.update(b,A.status==="failed"?"error":"done"),A)).catch(A=>(l.update(b,"error"),{task:h.task,status:"failed",result:`Error: ${A.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),d=await Promise.all(u);l.stop(),Sa();let f=["Sub-agent results:",""],m=0,g=0;for(let h=0;h<d.length;h++){let b=d[h],x=b.status==="done"?"\u2713":b.status==="truncated"?"\u26A0":"\u2717",j=b.modelSpec?` [${b.modelSpec}]`:"";f.push(`${x} Agent ${h+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(""),m+=b.tokensUsed.input,g+=b.tokensUsed.output}return f.push(`Total sub-agent tokens: ${m} input + ${g} output`),f.join(`
|
|
229
|
+
`)}catch(u){return l.stop(),Sa(),`ERROR: Sub-agent execution failed: ${u.message}`}}tf.exports={runSubAgent:Qd,executeSpawnAgents:ef,clearAllLocks:Sa,classifyTask:Jd,pickModelForTier:Zd,resolveSubAgentModel:Ta,classifyError:Ea,isRetryableError:Kd,callWithRetry:zd,getExcludedTools:Xd,LOCK_TIMEOUT_MS:Gd,SUB_AGENT_TYPES:Vd}});var Ia=re((_v,gf)=>{var je=require("fs"),zt=require("path"),{atomicWrite:nf,withFileLockSync:sf}=gn(),Qw=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=zt.join(process.cwd(),".nex","brain");return je.existsSync(t)||je.mkdirSync(t,{recursive:!0}),t}function Rr(){return zt.join(ls(),".brain-index.json")}function Oa(){return zt.join(ls(),".embeddings.json")}function zs(){let t=zt.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=zt.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 Xs(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 of(t){let e=zt.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}=Xs(s);return{name:t,content:s,body:o,frontmatter:n}}function e0(t,e){let s=zt.join(ls(),`${t}.md`);nf(s,e),s0(t,e),t0()}function t0(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Oa();je.existsSync(t)&&setImmediate(async()=>{try{await ff()}catch{}})}function n0(t){let e=zt.join(ls(),`${t}.md`);return je.existsSync(e)?(je.unlinkSync(e),o0(t),!0):!1}function Tr(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Qw.has(e))}function Na(t){let e={},{frontmatter:s,body:n}=Xs(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 Tr(a))e[c]=(e[c]||0)+3}for(let i of Tr(n||t))e[i]=(e[i]||0)+1;return e}function Ma(){let t=Rr();if(!je.existsSync(t))return{documents:{}};try{return JSON.parse(je.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function La(t){nf(Rr(),JSON.stringify(t,null,2))}function s0(t,e){sf(Rr(),()=>{let s=Ma(),{frontmatter:n}=Xs(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:Na(e),tags:o,modified:new Date().toISOString()},La(s)})}function o0(t){sf(Rr(),()=>{let e=Ma();delete e.documents[t],La(e)})}function Aa(){let t=zs(),e={documents:{}};for(let s of t){let n=je.readFileSync(s.path,"utf-8"),{frontmatter:o}=Xs(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:Na(n),tags:r,modified:s.modified.toISOString()}}return La(e),e}function rf(){let t=Ma(),e=zs();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return Aa()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return Aa();return t}function af(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=Tr(t);if(o.length===0)return[];let r=rf(),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 cf=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Ca=400,r0=50;async function lf(){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(cf.split(":")[0]))}catch{return!1}}async function Pa(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:cf,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 uf(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 df(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+Ca).join(" ");if(s.push({text:o,offset:n}),n+Ca>=e.length)break;n+=Ca-r0}return s}async function ff(){let t=zs(),e={documents:{}},s=Oa();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=df(r),a=[];for(let c of i){let l=await Pa(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 pf(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=Oa();if(!je.existsSync(o))return[];let r;try{r=JSON.parse(je.readFileSync(o,"utf-8"))}catch{return[]}let i=await Pa(t),a=[];for(let[c,l]of Object.entries(r.documents||{})){let u=0,d="";for(let f of l.chunks||[]){let m=uf(i,f.embedding);m>u&&(u=m,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 hf(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 mf(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=af(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await lf()){let a=await pf(t,{topK:s});r=hf(o,a,{topK:s})}}catch{}return r.map(i=>{let a=of(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},i0=3e5;async function a0(t){if(!t||!t.trim())return"";let e=zt.join(process.cwd(),".nex","brain");if(!je.existsSync(e)||zs().length===0)return"";let n=t.trim().toLowerCase().slice(0,200);if(cs.result!==null&&cs.queryKey===n&&Date.now()-cs.ts<i0)return cs.result;let o;try{o=await mf(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let r;try{r=jt().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 h=g/f;d=d.slice(0,Math.floor(d.length*h))+`
|
|
232
|
+
...(truncated)`}let m=typeof u.score=="number"?u.score.toFixed(2):String(u.score);if(a.push(`--- ${u.name} (relevance: ${m}) ---
|
|
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}gf.exports={getBrainDir:ls,listDocuments:zs,readDocument:of,writeDocument:e0,removeDocument:n0,buildIndex:Aa,getIndex:rf,query:mf,getBrainContext:a0,isEmbeddingAvailable:lf,generateEmbedding:Pa,buildEmbeddingIndex:ff,semanticQuery:pf,cosineSimilarity:uf,_keywordQuery:af,_extractKeywords:Na,_chunkText:df,parseFrontmatter:Xs,tokenize:Tr,_fuseResults:hf}});var Zs=re((xv,Rf)=>{var Le=require("fs"),pt=require("path"),c0=require("os"),{atomicWrite:Cr,withFileLockSync:yf}=gn(),Vs=["user","feedback","project","reference"],l0=50;function vn(){return pt.join(process.cwd(),".nex","memory")}function us(){return pt.join(vn(),"memory.json")}function $f(){return pt.join(vn(),"MEMORY.md")}function u0(){return pt.join(process.cwd(),"NEX.md")}function wf(){return pt.join(c0.homedir(),".nex","NEX.md")}function Ar(){let t=vn();Le.existsSync(t)||Le.mkdirSync(t,{recursive:!0})}function bf(t){let e=pt.join(vn(),t);return Le.existsSync(e)||Le.mkdirSync(e,{recursive:!0}),e}function Js(){let t=us();if(!Le.existsSync(t))return{};try{return JSON.parse(Le.readFileSync(t,"utf-8"))}catch{return{}}}function _f(t){Ar(),Cr(us(),JSON.stringify(t,null,2))}function xf(){let t=us();if(!Le.existsSync(t))return;let e=Js(),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=bf("project"),c=pt.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
|
+
`;Cr(c,u)}Or();try{Le.renameSync(t,t+".bak")}catch{}}function d0(t,e,s,n){if(!Vs.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${Vs.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=bf(t),i=pt.join(r,`${o}.md`);if(Le.existsSync(i))try{if(ja(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,222 +250,222 @@ type: ${t}
|
|
|
219
250
|
---
|
|
220
251
|
|
|
221
252
|
${s}
|
|
222
|
-
`;return
|
|
253
|
+
`;return Cr(i,c),Or(),{ok:!0,path:i,updated:!0}}function f0(t,e){if(!Vs.includes(t))return!1;let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),n=pt.join(vn(),t,`${s}.md`);if(!Le.existsSync(n))return!1;try{return Le.unlinkSync(n),Or(),!0}catch{return!1}}function ja(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 kf(){let t=[],e=vn();for(let s of Vs){let n=pt.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=pt.join(n,r);try{let a=Le.readFileSync(i,"utf-8"),c=ja(a);t.push({type:s,name:c.name||pt.basename(r,".md"),description:c.description,filePath:i})}catch{}}}return t}function Or(){let t=kf(),e=["# Project Memory Index",""];for(let s of t){if(e.length>=l0+2)break;let n=`${s.type}/${pt.basename(s.filePath)}`;e.push(`- [${s.name}](${n}) \u2014 ${s.description||"(no description)"}`)}Ar(),Cr($f(),e.join(`
|
|
223
254
|
`)+`
|
|
224
|
-
`)}function
|
|
225
|
-
${e}`);let s=
|
|
226
|
-
${s}`);let n="",o=
|
|
227
|
-
${d.map(
|
|
255
|
+
`)}function vf(){let t=$f();if(!Le.existsSync(t))return"";try{return Le.readFileSync(t,"utf-8").trim()}catch{return""}}function p0(t,e){Ar(),yf(us(),()=>{let s=Js();s[t]={value:e,updatedAt:new Date().toISOString()},_f(s)})}function h0(t){let e=Js();return e[t]?e[t].value:null}function m0(t){return Ar(),yf(us(),()=>{let e=Js();return t in e?(delete e[t],_f(e),!0):!1})}function Sf(){let t=Js();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Ef(){let t=wf();if(!Le.existsSync(t))return"";try{return Le.readFileSync(t,"utf-8").trim()}catch{return""}}function Tf(){let t=u0();if(!Le.existsSync(t))return"";try{return Le.readFileSync(t,"utf-8").trim()}catch{return""}}function g0(){xf();let t=[],e=Ef();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
256
|
+
${e}`);let s=Tf();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
257
|
+
${s}`);let n="",o=vf();if(o)n=o;else{let d=Sf();d.length>0&&(n=`PROJECT MEMORY:
|
|
258
|
+
${d.map(m=>` ${m.key}: ${m.value}`).join(`
|
|
228
259
|
`)}`)}let r=t.join(`
|
|
229
260
|
|
|
230
261
|
`),i="You can save insights with save_memory(type, name, content) and remove them with delete_memory(type, name).",l=Math.max(1500,16e3-r.length-i.length-10);if(n.length>l&&l>200){let d=n.split(`
|
|
231
|
-
`),f="";for(let
|
|
262
|
+
`),f="";for(let m of d){if(f.length+m.length+1>l-60)break;f+=m+`
|
|
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
|
+
`)}Rf.exports={saveMemory:d0,deleteMemory:f0,scanMemories:kf,rebuildIndex:Or,loadMemoryIndex:vf,remember:p0,recall:h0,forget:m0,listMemories:Sf,loadGlobalInstructions:Ef,loadProjectInstructions:Tf,getMemoryContext:g0,_getMemoryDir:vn,_getMemoryFile:us,_getGlobalNexMdPath:wf,_parseMemoryFile:ja,_migrateIfNeeded:xf,VALID_TYPES:Vs}});var Lf=re((kv,Mf)=>{var Qs=require("fs"),Da=require("path"),qa=process.env.NEX_AUDIT!=="false",Sn=null;function Cf(){return Sn||(Sn=Da.join(process.cwd(),".nex","audit"),Qs.existsSync(Sn)||Qs.mkdirSync(Sn,{recursive:!0}),Sn)}function Af(){let t=new Date().toISOString().split("T")[0];return Da.join(Cf(),`${t}.jsonl`)}function y0(t){if(qa)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Of(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
|
+
`;Qs.appendFileSync(Af(),s,"utf-8")}catch{}}function Of(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 Nf(t={}){let e=Cf(),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=Da.join(e,`${r}.jsonl`);if(!Qs.existsSync(i))continue;let a=Qs.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 $0(t=1){let e=Nf({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 w0(t){qa=t}function b0(){return qa}function _0(){Sn=null}Mf.exports={logToolExecution:y0,sanitizeArgs:Of,readAuditLog:Nf,getAuditSummary:$0,setAuditEnabled:w0,isAuditEnabled:b0,getAuditLogPath:Af,_reset:_0}});var Yf=re((Ev,Hf)=>{var De=require("fs").promises,Pf=require("fs"),Ee=require("path"),Ce=require("util").promisify(require("child_process").exec),Fa=require("util").promisify(require("child_process").execFile),{spawnSync:x0}=require("child_process"),Ba=require("axios"),{isForbidden:k0,isSSHForbidden:v0,isDangerous:S0,isCritical:If,isBashPathForbidden:E0,confirm:Et}=As(),{showDiff:Nr,showNewFile:T0,showEditDiff:vv,confirmFileChange:eo}=pu(),{C:ce,Spinner:R0,getToolSpinnerText:C0}=Ye(),{isGitRepo:Wa,getCurrentBranch:jf,getStatus:A0,getDiff:O0}=rr(),{recordChange:Mr}=ku(),{fuzzyFindText:Df,findMostSimilar:so}=Ku(),{runDiagnostics:to}=Xu(),{findFileInIndex:N0,getFileIndex:Sv}=ha(),{resolveProfile:_t,sshExec:it,scpUpload:M0,scpDownload:L0}=ga(),{resolveDeployConfig:P0,loadDeployConfigs:I0}=cd(),{getEditMode:qf}=Fs(),j0=/^(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/,D0=/^ssh\s/,q0=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function ht(t){return De.access(t).then(()=>!0).catch(()=>!1)}async function Lr(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=at(e);if(s&&await ht(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=at(t+i);if(a&&await ht(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=at(i+a);if(c&&await ht(c))return{fixedPath:c,message:`(auto-fixed: ${o} \u2192 ${a})`}}}let r=Ee.basename(t);if(r&&r.length>2)try{let i=N0(r).map(a=>at(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 F0(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 Wf(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
|
-
${
|
|
246
|
-
`+C.message:""}`}let r=Buffer.alloc(8192),i=await
|
|
247
|
-
`),u=await
|
|
248
|
-
`),
|
|
249
|
-
|
|
250
|
-
[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)}]`:!
|
|
251
|
-
[Large file (${d} lines total) \u2014 use line_start/line_end for other sections]`:"";return`${
|
|
252
|
-
${
|
|
253
|
-
`+u.message:""}`}let r=await
|
|
254
|
-
Most similar text (line ${
|
|
255
|
-
${
|
|
256
|
-
`),
|
|
257
|
-
`),C=`line_start=${Math.max(1,
|
|
258
|
-
|
|
259
|
-
Actual file content around line ${
|
|
260
|
-
${
|
|
273
|
+
`)}function Uf(t,e,s){let n=so(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 Ff=!1,En=null;function B0(){En&&(En(),En=null)}var Ha=null;function W0(t){Ha=t}async function Ua(){if(!Ff){Ff=!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 U0=[/\.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 at(t){let e=Ee.isAbsolute(t)?Ee.resolve(t):Ee.resolve(process.cwd(),t);for(let s of U0)if(s.test(e))return null;return e}var H0=[{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 no(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 Bf(t,e,s={}){switch(t){case"bash":{let n=e.command,o=k0(n);if(o){let d=F0(n);return`BLOCKED: Command matches forbidden pattern: ${o}${d?`
|
|
274
|
+
HINT: ${d}`:""}`}let r=E0(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?If(n):S0(n)){let d=If(n)?"\u26D4":"\u26A0";if(!await Et(` ${d} bash: \`${n}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),Pf.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=D0.test(n.trim())&&!q0.test(n.trim());if(j0.test(n.trim())||c){s.silent||console.log(`${ce.dim} \u25B6 interactive: ${n}${ce.reset}`);let d=x0("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),m=Wf(f,n);return`EXIT ${d.code||1}
|
|
276
|
+
${m}`}}case"read_file":{let n=at(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ht(n)){let C=await Lr(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 Pf.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,m=!e.line_start&&!e.line_end,g=m&&d>f,h=(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 ${h+1}-${b} of ${d}`:`${d} lines`,Y=`File: ${x} (${j}, ${u.size} bytes)`,A=l.slice(h,b).map((C,Z)=>`${h+Z+1}: ${C}`).join(`
|
|
279
|
+
`),O=g?`
|
|
280
|
+
|
|
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)}]`:!m&&d>f?`
|
|
282
|
+
[Large file (${d} lines total) \u2014 use line_start/line_end for other sections]`:"";return`${Y}
|
|
283
|
+
${A}${O}`}case"write_file":{await Ua();let n=at(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await ht(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 to(n,e.content);if(Nr(n,r,e.content,{annotations:u}),!await eo("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let u=await to(n,e.content);if(T0(n,e.content,{annotations:u}),!await eo("Create"))return"CANCELLED: User declined to create file."}let i=Ee.dirname(n);await ht(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),Mr("write_file",n,r,e.content);let l=c?" [chmod +x applied]":"";return`Written: ${n} (${e.content.length} chars)${l}`}case"edit_file":{await Ua();let n=at(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ht(n)){let u=await Lr(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}=Ke();if(qf(u(),d())==="strict"){let g=so(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 m=Df(r,e.old_text);if(m)i=m,a=!0,console.log(`${ce.dim} \u2713 fuzzy whitespace match applied${ce.reset}`);else{let g=Uf(r,e.old_text,e.new_text);if(g){if(!s.autoConfirm){let Y=await to(n,g.content);if(Nr(n,r,g.content,{annotations:Y}),!await eo(`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),Mr("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 h=so(r,e.old_text);if(h){let j=r.split(`
|
|
287
|
+
`),Y=Math.max(0,h.line-6),A=Math.min(j.length,h.line+10),O=j.slice(Y,A).map((Z,G)=>`${Y+G+1}: ${Z}`).join(`
|
|
288
|
+
`),C=`line_start=${Math.max(1,h.line-5)} line_end=${Math.min(j.length,h.line+15)}`;return`ERROR: old_text not found in ${n} (most similar at line ${h.line}, distance ${h.distance})
|
|
289
|
+
|
|
290
|
+
Actual file content around line ${h.line} \u2014 use this to correct old_text:
|
|
291
|
+
${O}
|
|
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 to(n,u);if(Nr(n,r,u,{annotations:d}),!await eo(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),Mr("edit_file",n,r,l),a?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=at(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ht(n)){let l=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),u=at(l),d=await ht(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(m=>!m.name.startsWith(".")&&m.name!=="node_modules");for(let m of f){if(i&&!m.isDirectory()&&!i.test(m.name))continue;let g=m.isDirectory()?"/":"";a.push(`${d}${m.name}${g}`),m.isDirectory()&&await c(Ee.join(l,m.name),u+1,d+" ")}};return await c(n,1,""),a.join(`
|
|
297
|
+
`)||"(empty)"}case"search_files":{let n=at(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 Fa("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
|
|
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
|
-
`+
|
|
280
|
-
Most similar text (line ${
|
|
281
|
-
${
|
|
282
|
-
Most similar text (line ${
|
|
283
|
-
${
|
|
299
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?at(e.path):o,i=e.pattern,a=G=>{let ue=G.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:m,getIndexedCwd:g,refreshIndex:h,isIndexValid:b}=ha(),x=m(),j=g();b(r)||(await h(r),x=m());let Y=x.filter(G=>c.test(G)||u.test(Ee.basename(G))).map(G=>Ee.join(r,G));if(Y.length===0)return f.stop(),"(no matches)";let A=await Promise.all(Y.slice(0,210).map(async G=>{try{let ue=await De.stat(G);return{path:G,mtime:ue.mtimeMs}}catch{return{path:G,mtime:0}}}));A.sort((G,ue)=>ue.mtime-G.mtime);let O=A.map(G=>G.path),C=Y.length>200,Z=O.slice(0,200).join(`
|
|
300
|
+
`);return f.update({count:Y.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?at(e.path):process.cwd();if(e.staged){let{getDiff:c}=rr(),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:m}=zn(),g=new m("grep","Searching staged content...");g.start();let h=[];for(let b of u)try{let x=Ee.join(process.cwd(),b);if(await ht(x)){let j=[...f];j.push(e.pattern,x);let{stdout:Y}=await Fa("grep",j,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let A=Y.trim().split(`
|
|
304
|
+
`).filter(O=>O.trim());h=h.concat(A)}else{let A=Y.split("\0");for(let O=0;O<A.length;O+=2){let C=A[O+1];if(C){let Z=C.split(`
|
|
305
|
+
`).filter(G=>G.trim());for(let G of Z)h.push(`${b}:${G}`)}}}}}catch{}return g.update({count:h.length,detail:"in staged files"}),g.stop(),h.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 Fa("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 m=0;m<f.length;m+=2){let g=f[m],h=f[m+1];if(g&&h){let b=h.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 Ua();let n=at(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ht(n)){let x=await Lr(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}=Ke(),l=qf(a(),c()),u=[],d=!1,f=!1;for(let x=0;x<r.length;x++){let{old_text:j,new_text:Y}=r[x];if(i.includes(j))u.push({old_text:j,new_text:Y});else if(l==="strict"){let A=so(i,j);return A?`ERROR: Patch ${x+1} old_text not found in ${n} (strict mode \u2014 exact match required)
|
|
311
|
+
Most similar text (line ${A.line}, distance ${A.distance}):
|
|
312
|
+
${A.text}`:`ERROR: Patch ${x+1} old_text not found in ${n} (strict mode \u2014 exact match required)`}else{let A=Df(i,j);if(A)u.push({old_text:A,new_text:Y}),d=!0;else{let O=so(i,j);if(O){let C=Math.max(3,Math.ceil(j.length*.05));if(O.distance<=C)u.push({old_text:O.text,new_text:Y}),f=!0;else return`ERROR: Patch ${x+1} old_text not found in ${n}
|
|
313
|
+
Most similar text (line ${O.line}, distance ${O.distance}):
|
|
314
|
+
${O.text}`}else return`ERROR: Patch ${x+1} old_text not found in ${n}`}}}let m=i;for(let{old_text:x,new_text:j}of u)m=m.split(x).join(j);if(!s.autoConfirm){let x=await to(n,m);if(Nr(n,i,m,{annotations:x}),!await eo(d?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await De.writeFile(n,m,"utf-8");let g=/[/\\]\.git[/\\]hooks[/\\]/.test(n)||n.endsWith(".sh")||m.startsWith("#!");g&&await De.chmod(n,493),Mr("patch_file",n,i,m);let h=f?" (auto-fixed)":d?" (fuzzy match)":"",b=g?" [chmod +x applied]":"";return`Patched: ${n} (${r.length} replacements)${h}${b}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let r=await Ba.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 Ba.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 Ba.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}=Ws();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}=Ws();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}=Ws();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=Ws();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 Ha?new Promise(r=>{En=()=>r("CANCELLED"),Ha(n,o).then(i=>{En=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});En=()=>{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=>{En=null,i.close(),r(c.trim()||"(no response)")})})}case"git_status":{if(!await Wa())return"ERROR: Not a git repository";let n=await jf()||"(detached)",o=await A0();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 Wa())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 O0(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await Wa())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}=Ye(),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}=Ra();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=Ke();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}=As(),o=e.branch||await jf()||"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=no(`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=no(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 Et(" 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=no(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 Et(" 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=no(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 Et(` ${a}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=no(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}=Ia(),{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=_t(e.server)}catch(C){return`ERROR: ${C.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,a=v0(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,G)=>{let ue=Math.min(Number(G),20);return`${Z} ${ue}`}),o=o.replace(/(--(?:before|after|context)=)(\d+)/g,(C,Z,G)=>Z+Math.min(Number(G),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 Et(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await it(n,o,{timeout:i,sudo:r}),m=[l,u].filter(Boolean).join(`
|
|
339
370
|
`).trim();if(d!==0)return`EXIT ${d}
|
|
340
|
-
${f||
|
|
371
|
+
${f||m||"(no output)"}`;let g=/\bgrep\b/.test(o),h=m;g&&(h=h.split(`
|
|
341
372
|
`).filter(C=>C!=="--").join(`
|
|
342
|
-
`));let b=
|
|
343
|
-
`);
|
|
344
|
-
`+
|
|
345
|
-
`));let
|
|
346
|
-
`),
|
|
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
|
-
${
|
|
350
|
-
${
|
|
351
|
-
${d}`}}else{let{stdout:c,stderr:l,exitCode:u,error:d}=await
|
|
373
|
+
`));let b=g?60:100,x=h.split(`
|
|
374
|
+
`);x.length>b&&(h=`(${x.length-b} earlier lines omitted \u2014 showing last ${b})
|
|
375
|
+
`+x.slice(-b).join(`
|
|
376
|
+
`));let j=4,Y=h.split(`
|
|
377
|
+
`),A=[],O=0;for(;O<Y.length;){let C=O+1;for(;C<Y.length&&Y[C]===Y[O];)C++;let Z=C-O;if(A.push(Y[O]),Z>j)A.push(`... (${Z-1} identical lines omitted)`);else for(let G=1;G<Z;G++)A.push(Y[O]);O=C}return A.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=_t(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 Et(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await M0(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=_t(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await L0(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 m=(f.stdout||"")+(f.stderr||"");return f.status!==0?`Remote nex-code exited with code ${f.status}.
|
|
380
|
+
${m.slice(-2e3)}`:m.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let 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=_t(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 Et(" 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 it(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:h}=await Ce(a,{timeout:15e3});return(g||h||"(no log output)").trim()}catch(g){return`EXIT ${g.code||1}
|
|
385
|
+
${(g.stderr||g.message||"").toString().trim()}`}let c;try{c=_t(e.server)}catch(g){return`ERROR: ${g.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await it(c,a,{timeout:2e4}),m=[l,u].filter(Boolean).join(`
|
|
355
386
|
`).trim();return d!==0?`EXIT ${d}
|
|
356
|
-
${f||
|
|
357
|
-
${(f.stderr||f.message||"").toString().trim()}`}let i;try{i
|
|
387
|
+
${f||m||"(no output)"}`:m||"(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:m}=await Ce(r,{timeout:1e4});return(f||m||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
|
|
388
|
+
${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=_t(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:a,stderr:c,exitCode:l,error:u}=await it(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:
|
|
360
|
-
${(
|
|
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:m,stderr:g}=await Ce(i,{timeout:15e3});return(m||g||"(no log output)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
391
|
+
${(m.stderr||m.message||"").toString().trim()}`}let a;try{a=_t(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await it(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 Et(" 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:h}=await Ce(a,{timeout:3e4});return(g||h||"(no output)").trim()}catch(g){return`EXIT ${g.code||1}
|
|
395
|
+
${(g.stderr||g.message||"").toString().trim()}`}let c;try{c=_t(e.server)}catch(g){return`ERROR: ${g.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await it(c,a,{timeout:35e3}),m=[l,u].filter(Boolean).join(`
|
|
365
396
|
`).trim();return d!==0?`EXIT ${d}
|
|
366
|
-
${f||
|
|
367
|
-
${
|
|
368
|
-
${(
|
|
397
|
+
${f||m}`:m||"(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 Et(" 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:h}=await Ce(a,{timeout:3e4});return(g||h||`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=_t(e.server)}catch(g){return`ERROR: ${g.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await it(c,a,{timeout:35e3}),m=[l,u].filter(Boolean).join(`
|
|
369
400
|
`).trim();return d!==0?`EXIT ${d}
|
|
370
|
-
${f||
|
|
371
|
-
${
|
|
372
|
-
${
|
|
401
|
+
${f||m}`:m||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...P0(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=_t(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 Et(" 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:
|
|
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:
|
|
405
|
+
${e.deploy_script}`:""}`;let{stdout:m,stderr:g,exitCode:h,error:b}=await it(o,f,{timeout:12e4});if(i=[m,g].filter(Boolean).join(`
|
|
406
|
+
`).trim(),h!==0)return`ERROR (git pull, exit ${h}):
|
|
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(h=>`--exclude="${h}"`).join(" "),f=e.dry_run?"--dry-run":"",m=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,g=`rsync -avz --delete ${f} ${d} ${u} ${m} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:h,stderr:b}=await Ce(g,{timeout:12e4});i=(h||b||"").trim()}catch(h){return`ERROR (rsync): ${(h.stderr||h.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:m}=await it(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
|
-
${
|
|
412
|
+
${m||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"),m=await Promise.race([f(u),new Promise((g,h)=>setTimeout(()=>h(new Error("timeout")),15e3))]);if(m.ok)c=`
|
|
385
416
|
|
|
386
|
-
Health check: \u2713 ${u} \u2192 ${
|
|
417
|
+
Health check: \u2713 ${u} \u2192 ${m.status}`;else return c=`
|
|
387
418
|
|
|
388
|
-
Health check FAILED: ${u} \u2192 HTTP ${
|
|
419
|
+
Health check FAILED: ${u} \u2192 HTTP ${m.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:
|
|
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:m,exitCode:g}=await it(o,u,{timeout:15e3}),h=[f,m].filter(Boolean).join(`
|
|
422
|
+
`).trim();if(g!==0)return c=`
|
|
392
423
|
|
|
393
|
-
Health check FAILED (exit ${
|
|
424
|
+
Health check FAILED (exit ${g}): ${h}`,(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 ${h||"(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=I0(),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=_t(a.server||i),u=(await it(c,"echo OK",{timeout:1e4})).stdout.trim()==="OK",d="unknown";if(u&&a.deploy_script){let m=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(m)try{d=(await it(c,`systemctl is-active ${m[1]}`,{timeout:1e4})).stdout.trim()}catch{d="inactive"}}let f="N/A";if(a.health_check){let m=a.health_check.trim();if(/^https?:\/\//.test(m))try{let g=require("node-fetch"),h=await Promise.race([g(m),new Promise((b,x)=>setTimeout(()=>x(new Error("timeout")),1e4))]);f=h.ok?"healthy":`HTTP ${h.status}`}catch(g){f=`unhealthy: ${g.message.substring(0,50)}`}else try{f=(await it(c,m,{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(
|
|
399
|
-
`),
|
|
400
|
-
`);return
|
|
401
|
-
... (${
|
|
402
|
-
`).filter(Boolean)}catch{return[]}},u=async(
|
|
429
|
+
`)}`}case"frontend_recon":{let n=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(A,O=120)=>{try{let C=Ee.isAbsolute(A)?A:Ee.join(n,A),G=(await De.readFile(C,"utf8")).split(`
|
|
430
|
+
`),ue=G.slice(0,O).join(`
|
|
431
|
+
`);return G.length>O?ue+`
|
|
432
|
+
... (${G.length-O} 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(A=>`-not -path "*/${A}/*"`).join(" "),l=async A=>{try{let{stdout:O}=await Ce(`find "${n}" -type f -name "${A}" ${c} 2>/dev/null | head -10`,{timeout:8e3});return O.trim().split(`
|
|
433
|
+
`).filter(Boolean)}catch{return[]}},u=async(A,O)=>{try{let{stdout:C}=await Ce(`grep -rl "${A}" "${n}" --include="${O}" --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
|
|
435
|
+
`);let d=[...await l("tailwind.config.js"),...await l("tailwind.config.ts"),...await l("tailwind.config.mjs")];if(d.length>0){let A=await i(d[0],80);A&&r.push(`### Tailwind config (${Ee.relative(n,d[0])})
|
|
405
436
|
\`\`\`js
|
|
406
|
-
${
|
|
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"],
|
|
437
|
+
${A}
|
|
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"],m=!1;for(let A of f){let O=await l(A);for(let C of O){let Z=await i(C,100);if(Z&&Z.includes(":root")){r.push(`### CSS Variables (${Ee.relative(n,C)})
|
|
408
439
|
\`\`\`css
|
|
409
|
-
${
|
|
410
|
-
\`\`\``),
|
|
440
|
+
${Z}
|
|
441
|
+
\`\`\``),m=!0;break}}if(m)break}if(!m){let A=await u(":root","*.css");if(A.length>0){let O=await i(A[0],100);O&&r.push(`### CSS Variables (${Ee.relative(n,A[0])})
|
|
411
442
|
\`\`\`css
|
|
412
|
-
${
|
|
413
|
-
\`\`\``),
|
|
443
|
+
${O}
|
|
444
|
+
\`\`\``),m=!0}}m||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"],h=!1;for(let A of g){let O=await l(A);if(O.length>0){let C=await i(O[0],150);if(C){r.push(`### Main layout: ${Ee.relative(n,O[0])}
|
|
416
447
|
\`\`\`html
|
|
417
448
|
${C}
|
|
418
|
-
\`\`\``),
|
|
449
|
+
\`\`\``),h=!0;break}}}h||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
|
|
421
|
-
`).filter(Boolean)}catch{b=[]}if(b.length>0){let
|
|
451
|
+
`);let b=[];if(o){for(let A of["*.html","*.vue","*.jsx","*.tsx"])if(b=await u(o,A),b.length>0)break}if(b.length===0)try{let{stdout:A}=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=A.trim().split(`
|
|
452
|
+
`).filter(Boolean)}catch{b=[]}if(b.length>0){let A=b[0],O=await i(A,150);O?r.push(`### Reference: ${Ee.relative(n,A)}
|
|
422
453
|
\`\`\`html
|
|
423
|
-
${
|
|
454
|
+
${O}
|
|
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 O=j.match(/"vue":\s*"[\^~]?(\d+)/);x.push(O?`Vue.js v${O[1]}`:"Vue.js")}let A=j.match(/"alpinejs":\s*"[\^~]?(\d+)/);A&&x.push(`Alpine.js v${A[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 ht(Ee.join(n,"manage.py"))||(await i(Ee.join(n,"requirements.txt"),50)||"").includes("Django"))&&x.push("Django (server-rendered templates)"),!x.some(A=>A.includes("Alpine"))){let A=await u("alpinejs","*.html");if(A.length>0){let C=(await i(A[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(A=>A.includes("HTMX"))||(await u("htmx","*.html")).length>0&&x.push("HTMX (via CDN)"),x.length>0?(r.push(x.map(A=>`- ${A}`).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
|
|
432
|
-
`).trim();return{out:
|
|
433
|
-
`+
|
|
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=_t(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:m}=await it(o,c,{timeout:l}),g=[u,d].filter(Boolean).join(`
|
|
463
|
+
`).trim();return{out:m&&f!==0&&!u.trim()?(m+`
|
|
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 Et(`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:h}=await r(g,6e4);return h||"(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:m}=await r(d,12e4);return m!==0?`EXIT ${m}
|
|
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}
|
|
@@ -468,12 +499,12 @@ if [ -n "$EXPIRY" ]; then
|
|
|
468
499
|
fi
|
|
469
500
|
`.trim();let{out:l,exitCode:u}=await r(c,25e3),d=/notAfter=|Days until expiry:/i.test(l);return u!==0&&!d?`EXIT ${u}
|
|
470
501
|
${l}`:l||"(no cert info returned)"}case"log_tail":{if(!e.path)return"ERROR: path is required for log_tail";let l=`tail -n ${e.lines||100} ${e.path} 2>&1`,{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
|
|
471
|
-
${u}`:u||"(empty log)"}case"find_large":{let c=e.path||"/",l=e.limit||20,u=e.min_size||"100M",d=`find ${c} -xdev -type f -size +${u} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${l}`,{out:f,exitCode:
|
|
502
|
+
${u}`:u||"(empty log)"}case"find_large":{let c=e.path||"/",l=e.limit||20,u=e.min_size||"100M",d=`find ${c} -xdev -type f -size +${u} 2>/dev/null | xargs du -sh 2>/dev/null | sort -rh | head -${l}`,{out:f,exitCode:m}=await r(d,6e4);return m!==0?`EXIT ${m}
|
|
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}=Zs(),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}=Zs();return n(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:n}=ur(),o=await n(t,e,s);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function Y0(t,e,s={}){let{emit:n}=ur(),{logToolExecution:o}=Lf(),r=Date.now(),i=s.silent?null:C0(t,e);if(!i){let c=await Bf(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 R0(i);a.start();try{let c=await Bf(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}}Hf.exports={TOOL_DEFINITIONS:H0,executeTool:Y0,resolvePath:at,autoFixPath:Lr,autoFixEdit:Uf,enrichBashError:Wf,cancelPendingAskUser:B0,setAskUserHandler:W0,fileExists:ht}});var ts=re((Tv,Gf)=>{Gf.exports=Yf()});var Ga=re((Cv,Kf)=>{var{loadServerProfiles:oo,resolveProfile:Rv,sshExec:G0}=ga(),Ya={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 K0(){let t=oo();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&&Ya[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 Ya[o])s.push(`- ${i}`)}}return s.join(`
|
|
507
|
+
`)}function z0(t){let e=oo();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function X0(){return Object.keys(oo())}function V0(){let t=require("fs"),s=require("path").join(process.cwd(),"NEX.md"),n="";try{n=t.readFileSync(s,"utf-8")}catch{}let o=oo(),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 m=o[f],g=m.user?`${m.user}@${m.host}`:m.host,h=m.port&&Number(m.port)!==22?`:${m.port}`:"";return` - **${f}**: ${g}${h}${m.os?` (${m.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,46 @@ ${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.${J0(o)}`}function J0(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 Z0(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=oo();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 G0(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}}Kf.exports={getServerContext:K0,getDeploymentContextBlock:V0,hasServerOS:z0,getProfileNames:X0,probeUrlServer:Z0,OS_HINTS:Ya}});var Jf=re((Av,Vf)=>{var st=require("fs").promises,zf=require("fs"),He=require("path"),Pr=require("util").promisify(require("child_process").exec),{C:ds}=Ye(),{getMergeConflicts:Xf}=rr(),{getServerContext:Q0}=Ga(),eb=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function tb(t){try{return zf.readFileSync(t,"utf-8").split(`
|
|
538
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function nb(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 sb(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:n=[]}={}){let o=He.join(t,".gitignore"),r=[...n,...tb(o)],i=0,a=[He.basename(t)+"/"];function c(l,u,d){if(d>e||i>=s)return;let f;try{f=zf.readdirSync(l,{withFileTypes:!0})}catch{return}f.sort((g,h)=>g.isDirectory()!==h.isDirectory()?g.isDirectory()?-1:1:g.name.localeCompare(h.name));let m=f.filter(g=>!(eb.has(g.name)||g.name.startsWith(".")&&g.name!==".env.example"||nb(g.name,r)));for(let g=0;g<m.length;g++){if(i>=s){a.push(`${u}\u2514\u2500\u2500 \u2026 (truncated)`);break}let h=m[g],b=g===m.length-1,x=b?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",j=u+(b?" ":"\u2502 "),Y=h.isDirectory()?h.name+"/":h.name;a.push(`${u}${x}${Y}`),i++,h.isDirectory()&&c(He.join(l,h.name),j,d+1)}}return c(t,"",1),a.join(`
|
|
539
|
+
`)}var Ka=new Map,fs=new Map,Ir=null,ob=3e4;async function Dt(t){try{return await t()}catch{return null}}async function rb(){if(!Ir||Date.now()>Ir)return!1;let t=[He.join(process.cwd(),"package.json"),He.join(process.cwd(),"README.md"),He.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=He.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 ib(){let t=[He.join(process.cwd(),"package.json"),He.join(process.cwd(),"README.md"),He.join(process.cwd(),".gitignore"),He.join(process.cwd(),".git","HEAD"),He.join(process.cwd(),"CLAUDE.md"),He.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let s=await st.stat(e);fs.set(e,s.mtimeMs)}catch{fs.delete(e)}}async function ab(t){let e="fileContext",s=Ka.get(e),n=!1;if(s&&await rb()&&(n=!0),!n){let l=[],u=He.join(t,"package.json");if(await Dt(()=>st.access(u).then(()=>!0).catch(()=>!1)))try{let A=await st.readFile(u,"utf-8"),O=JSON.parse(A),C={name:O.name,version:O.version};O.scripts&&(C.scripts=Object.keys(O.scripts).slice(0,15)),O.dependencies&&(C.deps=Object.keys(O.dependencies).length),O.devDependencies&&(C.devDeps=Object.keys(O.devDependencies).length),l.push(`PACKAGE: ${JSON.stringify(C)}`)}catch{}let f=He.join(t,"README.md");if(await Dt(()=>st.access(f).then(()=>!0).catch(()=>!1))){let O=(await st.readFile(f,"utf-8")).split(`
|
|
509
540
|
`).slice(0,50);l.push(`README (first 50 lines):
|
|
510
|
-
${
|
|
511
|
-
`)}`)}let
|
|
512
|
-
${
|
|
541
|
+
${O.join(`
|
|
542
|
+
`)}`)}let g=He.join(t,".gitignore");if(await Dt(()=>st.access(g).then(()=>!0).catch(()=>!1))){let A=await st.readFile(g,"utf-8");l.push(`GITIGNORE:
|
|
543
|
+
${A.trim()}`)}let b=He.join(t,"CLAUDE.md");if(await Dt(()=>st.access(b).then(()=>!0).catch(()=>!1))){let A=await st.readFile(b,"utf-8");A.trim()&&l.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
|
|
544
|
+
${A.trim()}`)}let j=He.join(t,".nex","CLAUDE.md");if(await Dt(()=>st.access(j).then(()=>!0).catch(()=>!1))){let A=await st.readFile(j,"utf-8");A.trim()&&l.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
|
|
545
|
+
${A.trim()}`)}s=l.join(`
|
|
513
546
|
|
|
514
|
-
`),
|
|
547
|
+
`),Ka.set(e,s),Ir=Date.now()+ob,await ib()}let o=[s],[r,i,a,c]=await Promise.all([Dt(async()=>{let{stdout:l}=await Pr("git branch --show-current",{cwd:t,timeout:5e3});return l.trim()}),Dt(async()=>{let{stdout:l}=await Pr("git status --short",{cwd:t,timeout:5e3});return l.trim()}),Dt(async()=>{let{stdout:l}=await Pr("git log --oneline -5",{cwd:t,timeout:5e3});return l.trim()}),Xf()]);if(r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
|
|
515
548
|
${i}`),a&&o.push(`RECENT COMMITS:
|
|
516
549
|
${a}`),c&&c.length>0){let l=c.map(u=>` ${u.file}`).join(`
|
|
517
550
|
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
518
|
-
${l}`)}try{let l=
|
|
551
|
+
${l}`)}try{let l=Q0();l&&o.push(l)}catch{}return o.join(`
|
|
519
552
|
|
|
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(
|
|
553
|
+
`)}async function cb(t){let e=He.join(t,"package.json"),s="";if(await Dt(()=>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([Dt(async()=>{let{stdout:i}=await Pr("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Xf()]);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()}Vf.exports={gatherProjectContext:ab,printContext:cb,generateFileTree:sb,_clearContextCache:()=>{Ka.clear(),fs.clear(),Ir=null}}});var Dr=re((Ov,ep)=>{var Tt=require("fs"),jr=require("path"),{atomicWrite:lb}=gn();function io(){return jr.join(process.cwd(),".nex","sessions")}function za(){let t=io();Tt.existsSync(t)||Tt.mkdirSync(t,{recursive:!0})}function Xa(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return jr.join(io(),`${e}.json`)}function Va(t,e,s={}){za();let n=Xa(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 lb(n,JSON.stringify(o,null,2)),{path:n,name:t}}function Zf(t){let e=Xa(t);if(!Tt.existsSync(e))return null;try{return JSON.parse(Tt.readFileSync(e,"utf-8"))}catch{return null}}function Qf(){za();let t=io(),e=Tt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Tt.readFileSync(jr.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 ub(t){let e=Xa(t);return Tt.existsSync(e)?(Tt.unlinkSync(e),!0):!1}function db(){let t=Qf();return t.length===0?null:Zf(t[0].name)}var Tn=null,Xt=null,ro=null;function fb(t,e={}){t.length!==0&&(Tn&&clearTimeout(Tn),Xt=t,ro=e||{},Tn=setTimeout(()=>{Xt&&Xt.length>0&&Va("_autosave",Xt,ro),Tn=null,Xt=null,ro=null},5e3))}function pb(){Tn&&(clearTimeout(Tn),Tn=null),Xt&&Xt.length>0&&(Va("_autosave",Xt,ro),Xt=null,ro=null)}function hb(){za();let t=io(),e=Tt.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=jr.join(t,r);try{let a=Tt.statSync(i);new Date(a.mtime)<n&&(Tt.unlinkSync(i),o++)}catch{}}return o}ep.exports={saveSession:Va,loadSession:Zf,listSessions:Qf,deleteSession:ub,getLastSession:db,autoSave:fb,flushAutoSave:pb,clearOldSessions:hb,_getSessionsDir:io}});var qr=re((Nv,cp)=>{"use strict";var ao=require("fs"),tp=require("path");function np(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 mb(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 sp(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 op(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 rp(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 ip(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 ap(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=np(t),o=sp(t),r=n.length,i=mb(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||"",M=`${I} ${v}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(M)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(M)})&&(e-=1,s.push("grep used with >20 context lines (context flood risk)"));let d=t.some(w=>w.role==="assistant"),f=op(t),g=rp(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=ip(a),j=0,Y="";for(let[w,I]of x)I>j&&(j=I,Y=w);if(j>=3){let[w]=Y.split("|");e-=1,s.push(`Same tool call repeated ${j}\xD7 (tool: ${w})`)}let A=!1,O=t.findIndex(w=>w.role==="user"&&typeof w.content=="string"&&w.content.includes("[SYSTEM STOP]")&&w.content.includes('"valid":true'));O>=0&&n.filter(I=>I.index>O).length>0&&(A=!0),A&&(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 M=w.input.line_start||1,R=w.input.line_end||M+350;v.ranges.push([M,R])}}function G(w,I,v){for(let[M,R]of v){let k=Math.max(w,M),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&&G(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&&G(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=[],M=!1;for(let[R,k]of I.ranges){if(v.length>0&&G(R,k,v)){M=!0;break}v.push([R,k])}!M&&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,J="";for(let[w,I]of Te)w.split("/").pop().includes(".")&&I.size>K&&(K=I.size,J=w);if(K>=3){e-=.75;let w=J.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 M=I.size;if(M>=1){let R=Math.min(M*.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 M=new Map;for(let xe=0;xe<=v.length-3;xe++){let ge=v.slice(xe,xe+3).join("").trim();ge.length>30&&M.set(ge,(M.get(ge)||0)+1)}let R=0,k="";for(let[xe,ge]of M)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(M=>Array.isArray(M.tool_calls)?M.tool_calls.some(R=>w.has(R.function?.name)):Array.isArray(M.content)?M.content.some(R=>R.type==="tool_use"&&w.has(R.name)):!1);t.some(M=>M.role==="assistant"&&typeof M.content=="string"&&(M.content.includes("## Steps")||M.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 M=[w,I,v].filter(Boolean).length;if(M>0){let R=Math.min(M*.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),M=v.some(k=>/pip\s+install|python\s+-m\s+venv/.test(k)),R=v.some(k=>/npm\s+install/.test(k));w&&!M?(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),M=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,R=v.split(`
|
|
554
|
+
`).find(k=>{let H=k.trim();return H.length>0&&H.length<=30&&/^\d/.test(H)&&/=/.test(H)&&!/[a-zA-Z]/.test(H)});if(M.test(v)||R){e-=1.5;let k=(R||v.split(`
|
|
555
|
+
`)[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(M=>M&&M.type==="tool_use")));if(w!==-1&&I!==-1&&w<I){let v=t[w],M="";typeof v.content=="string"?M=v.content:Array.isArray(v.content)&&(M=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(M),k=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(M);(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,M=/"\s*:\s*$/.test(w.trimEnd()),R=/[,\[{]\s*$/.test(w.trimEnd());(v||M||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,M)=>{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:M}))});let I=0;for(let v of w){let M=null;for(let k of t){if(k.role==="tool"&&k.tool_call_id===v.id&&typeof k.content=="string"){M=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){M=typeof H.content=="string"?H.content:"";break}}}if(!M)continue;M.split(`
|
|
556
|
+
`).filter(k=>k.trim()).length<5&&/^\s*\[/.test(M)&&!/\]\s*$/.test(M.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 M of a){if((M.name==="bash"||M.name==="Bash")&&M.input?.command&&/git\s+commit\b/.test(M.input.command)){w&&(v=Math.max(v,I)),w=!0,I=0;continue}w&&(M.name==="bash"||M.name==="Bash")&&M.input?.command&&/git\s+(status|diff|log|show)\b/.test(M.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 gb(t){try{let{loadSession:e}=Dr(),s=e(t);return s?ap(s.messages||[]):null}catch{return null}}function yb(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
557
|
${o}${f}${r}`}let c="";for(let u of a.slice(0,4))c+=`
|
|
525
558
|
${i}\u26A0${r} ${o}${u}${r}`;let l=a.length-4;return l>0&&(c+=`
|
|
526
|
-
${o}(+${l} more)${r}`),c}function
|
|
559
|
+
${o}(+${l} more)${r}`),c}function $b(t,e={}){try{let s=tp.join(process.cwd(),".nex");ao.existsSync(s)||ao.mkdirSync(s,{recursive:!0});let n=tp.join(s,"benchmark-history.json"),o=[];if(ao.existsSync(n))try{o=JSON.parse(ao.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)),ao.writeFileSync(n,JSON.stringify(o,null,2))}catch{}}cp.exports={scoreMessages:ap,scoreSession:gb,formatScore:yb,appendScoreHistory:$b,_extractToolCalls:np,_extractToolResults:sp,_getLastAssistantText:op,_getLastNAssistantTexts:rp,_countDuplicateToolCalls:ip}});var ps=re((Mv,pp)=>{"use strict";var wb=require("os"),Ja=require("path"),sn=require("fs"),co=Ja.join(wb.homedir(),".nex-code","model-routing.json"),Fr={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}},lp=["agentic","frontend","sysadmin","data","coding"];function bb(t){if(!t||t.length<8)return null;for(let e of lp){let s=Fr[e];if(!s.pattern||s.pattern.test(t))return s}return Fr.coding}function lo(){try{if(sn.existsSync(co))return JSON.parse(sn.readFileSync(co,"utf-8"))}catch{}return{}}function up(t){let e=Fr[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:lo()[t]||null}var dp={plan:10,implement:35,verify:8},Za={plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function fp(){let t=lo();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=Ke();if(e()==="ollama")return Za}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Za:null}function _b(t,e){let s=fp();return s?.[t]?s[t]:e?up(e):null}function xb(t){return lo().phaseBudgets?.[t]||dp[t]||20}function kb(){return process.env.NEX_PHASE_ROUTING==="0"?!1:fp()!==null}function vb(t){let e=Ja.dirname(co);sn.existsSync(e)||sn.mkdirSync(e,{recursive:!0});let s=lo(),n={...s,...t};!t.phases&&s.phases&&(n.phases=s.phases),!t.phaseBudgets&&s.phaseBudgets&&(n.phaseBudgets=s.phaseBudgets),sn.writeFileSync(co,JSON.stringify(n,null,2));try{let o=Ja.join(e,".env"),r="";sn.existsSync(o)&&(r=sn.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)),sn.writeFileSync(o,i.filter(c=>c.trim()!=="").join(`
|
|
560
|
+
`)+`
|
|
561
|
+
`)}catch{}}pp.exports={CATEGORIES:Fr,DETECTION_ORDER:lp,detectCategory:bb,getModelForCategory:up,getModelForPhase:_b,getPhaseBudget:xb,isPhaseRoutingEnabled:kb,DEFAULT_PHASE_BUDGETS:dp,BUILTIN_PHASE_DEFAULTS:Za,saveRoutingConfig:vb,loadRoutingConfig:lo,ROUTING_CONFIG_PATH:co}});var yp=re((Lv,gp)=>{"use strict";var Rn=require("fs"),uo=require("path"),Sb=require("os"),{detectCategory:Eb}=ps(),hs=uo.join(Sb.homedir(),".nex-code","examples"),Qa=uo.join(__dirname,"..","examples");function hp(t){try{let s=Rn.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
562
|
A: |`);if(r===-1)return null;let i=s.slice(r+5),a=[],c=0;for(let u of i.split(`
|
|
528
563
|
`))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
|
|
564
|
+
`).trim();return{user:o,assistant:l}}catch{return null}}function mp(t){let e=`${t}.md`,s=uo.join(hs,e);if(Rn.existsSync(s)){let o=hp(s);if(o)return o}let n=uo.join(Qa,e);return Rn.existsSync(n)?hp(n):null}function Tb(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=Eb(t);return e?mp(e.id):null}function Rb(){let t=new Set;for(let e of[hs,Qa])try{for(let s of Rn.readdirSync(e))s.endsWith(".md")&&t.add(s.replace(".md",""))}catch{}return[...t].sort()}function Cb(t,e){Rn.existsSync(hs)||Rn.mkdirSync(hs,{recursive:!0});let s=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
|
|
530
565
|
|
|
531
566
|
user: ${e.user}
|
|
532
567
|
|
|
@@ -534,14 +569,14 @@ A: |
|
|
|
534
569
|
${e.assistant.split(`
|
|
535
570
|
`).map(n=>` ${n}`).join(`
|
|
536
571
|
`)}
|
|
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
|
|
572
|
+
`;Rn.writeFileSync(uo.join(hs,`${t}.md`),s,"utf-8")}gp.exports={getFewShotForInput:Tb,loadExampleForCategory:mp,listAvailableExamples:Rb,savePrivateExample:Cb,PRIVATE_EXAMPLES_DIR:hs,BUNDLED_EXAMPLES_DIR:Qa}});var kp=re((Iv,xp)=>{var mt=require("fs"),ms=require("path"),{C:Pv}=Ye(),{atomicWrite:Ab,withFileLockSync:Ob}=gn(),Br={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={...Br};function $p(){let t=ms.join(process.cwd(),".nex","config.json");if(mt.existsSync(t))try{let e=JSON.parse(mt.readFileSync(t,"utf-8"));e.permissions&&(gs={...Br,...e.permissions})}catch{}}function Nb(){let t=ms.join(process.cwd(),".nex"),e=ms.join(t,"config.json");mt.existsSync(t)||mt.mkdirSync(t,{recursive:!0}),Ob(e,()=>{let s={};if(mt.existsSync(e))try{s=JSON.parse(mt.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=gs,Ab(e,JSON.stringify(s,null,2))})}function wp(t){return gs[t]||"ask"}function Mb(t,e){return["allow","ask","deny"].includes(e)?(gs[t]=e,!0):!1}function Lb(t){return wp(t)}function Pb(){return Object.entries(gs).map(([t,e])=>({tool:t,mode:e}))}function Ib(){gs={...Br}}var fo={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 bp(){let t=ms.join(process.cwd(),".nex","config.json");try{return mt.existsSync(t)&&JSON.parse(mt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function jb(t){let e=ms.join(process.cwd(),".nex"),s=ms.join(e,"config.json");mt.existsSync(e)||mt.mkdirSync(e,{recursive:!0});let n={};try{mt.existsSync(s)&&(n=JSON.parse(mt.readFileSync(s,"utf-8")))}catch{n={}}n.teamPermissions=t,mt.writeFileSync(s,JSON.stringify(n,null,2),"utf-8")}function _p(){let t=bp();if(!t)return fo.admin;let e=t.role||"admin",s=fo[e]||fo.admin;return{...s,...t.overrides,blockedTools:[...s.blockedTools||[],...t.overrides?.blockedTools||[]]}}function Db(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 qb(){return Object.entries(fo).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}$p();xp.exports={getPermission:wp,setPermission:Mb,checkPermission:Lb,listPermissions:Pb,loadPermissions:$p,savePermissions:Nb,resetPermissions:Ib,DEFAULT_PERMISSIONS:Br,PERMISSION_PRESETS:fo,loadPresetConfig:bp,savePresetConfig:jb,getEffectivePreset:_p,isToolAllowed:Db,listPresets:qb}});var Hr=re((Dv,Rp)=>{var An=require("fs"),Wr=require("path"),jv=require("readline"),{C:ve}=Ye(),_e=null,tc=!1,nc=null,vp=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Ur(){return Wr.join(process.cwd(),".nex","plans")}function Sp(){let t=Ur();An.existsSync(t)||An.mkdirSync(t,{recursive:!0})}function Fb(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 Bb(){return _e}function Wb(t){tc=t}function Ub(){return tc}function Hb(){return!_e||_e.status!=="draft"?!1:(_e.status="approved",_e.updatedAt=new Date().toISOString(),!0)}function Yb(){return!_e||_e.status!=="approved"?!1:(_e.status="executing",!0)}function ec(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 Gb(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(`
|
|
573
|
+
${ve.bold}${ve.cyan}Plan: ${t.task}${ve.reset}`),s.push(`${ve.dim}Status: ${e[t.status]||t.status}${ve.reset}
|
|
574
|
+
`);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(`
|
|
575
|
+
`)}function Kb(t){if(t||(t=_e),!t)return null;Sp();let e=Wr.join(Ur(),`${t.name}.json`);return An.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function zb(t){let e=Wr.join(Ur(),`${t}.json`);if(!An.existsSync(e))return null;try{let s=JSON.parse(An.readFileSync(e,"utf-8"));return _e=s,s}catch{return null}}function Xb(){Sp();let t=Ur(),e=An.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(An.readFileSync(Wr.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 Vb(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 Jb(t){nc=t}function Zb(){return nc}function Qb(){_e=null,tc=!1,nc=null,s_()}function e_(){return`
|
|
541
576
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
542
577
|
|
|
543
578
|
# Allowed Tools (read-only)
|
|
544
|
-
You may ONLY use these tools: ${[...
|
|
579
|
+
You may ONLY use these tools: ${[...vp].join(", ")}
|
|
545
580
|
Any other tool call will be blocked and returned with an error.
|
|
546
581
|
|
|
547
582
|
# MANDATORY: Read Before You Plan
|
|
@@ -585,23 +620,23 @@ Bullet list of potential issues and mitigations.
|
|
|
585
620
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
586
621
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
587
622
|
- 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
|
|
623
|
+
- 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 Cn=0;function t_(){!_e||_e.status!=="executing"||(Cn>0&&ec(Cn-1,"done"),Cn<_e.steps.length&&(ec(Cn,"in_progress"),Cn++))}function n_(){if(!_e||_e.status!=="executing"||_e.steps.length===0)return null;let t=Math.min(Cn,_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 s_(){Cn=0}var Ep=["interactive","semi-auto","autonomous"],Tp="interactive";function o_(t){return Ep.includes(t)?(Tp=t,!0):!1}function r_(){return Tp}Rp.exports={createPlan:Fb,getActivePlan:Bb,setPlanMode:Wb,isPlanMode:Ub,approvePlan:Hb,startExecution:Yb,updateStep:ec,formatPlan:Gb,savePlan:Kb,loadPlan:zb,listPlans:Xb,clearPlan:Qb,getPlanModePrompt:e_,setPlanContent:Jb,getPlanContent:Zb,extractStepsFromText:Vb,advancePlanStep:t_,getPlanStepInfo:n_,PLAN_MODE_ALLOWED_TOOLS:vp,setAutonomyLevel:o_,getAutonomyLevel:r_,AUTONOMY_LEVELS:Ep}});var qp=re((qv,Dp)=>{var{C:_}=Ye();function Cp(){return Math.max(10,(process.stdout.columns||80)-2)}function i_(t){if(!t)return"";let e=t.split(`
|
|
624
|
+
`),s=[],n=!1,o="";for(let r of e){let i=Cp();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(` ${oc(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${_.bold}${_.cyan} ${On(r.substring(4))}${_.reset}`);continue}if(r.startsWith("## ")){s.push(`${_.bold}${_.cyan} ${On(r.substring(3))}${_.reset}`);continue}if(r.startsWith("# ")){s.push(`${_.bold}${_.cyan}${On(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} ${Nn(c)}`;s.push(Mn(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} ${Nn(u)}`,f=c+" ".repeat(l.length+2);s.push(Mn(d,i,f));continue}}s.push(Mn(Nn(r),i))}return s.join(`
|
|
625
|
+
`)}function On(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Nn(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 oc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Ap(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Op(t):e==="json"||e==="jsonc"?Np(t):e==="python"||e==="py"?Mp(t):e==="go"||e==="golang"?Lp(t):e==="rust"||e==="rs"?Pp(t):e==="css"||e==="scss"||e==="less"?Ip(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?jp(t):t:""}function Ap(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 Op(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 Np(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 Mp(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 Lp(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 Pp(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 Ip(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 jp(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 Mn(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
626
|
`+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
|
-
`)}};
|
|
627
|
+
`+s,a=i,o=s.length+1),i++}return n+=t.slice(a),n}function a_(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(`
|
|
628
|
+
`)}function c_(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 sc=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(`
|
|
629
|
+
`))!==-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}
|
|
630
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let s=Cp();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${_.dim}${"\u2500".repeat(40)}${_.reset}
|
|
631
|
+
`),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}
|
|
632
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${oc(e,this.codeBlockLang)}
|
|
633
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${_.bold}${_.cyan} ${On(e.substring(4))}${_.reset}
|
|
634
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${_.bold}${_.cyan} ${On(e.substring(3))}${_.reset}
|
|
635
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${_.bold}${_.cyan}${On(e.substring(2))}${_.reset}
|
|
636
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${_.cyan}\u2022${_.reset} ${Nn(r)}`,a=Mn(i,s,o+" ");this._safeWrite(`${a}
|
|
637
|
+
`);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} ${Nn(a)}`,l=r+" ".repeat(i.length+2),u=Mn(c,s,l);this._safeWrite(`${u}
|
|
638
|
+
`);return}}let n=Mn(Nn(e),s);this._safeWrite(`${n}
|
|
639
|
+
`)}};Dp.exports={renderMarkdown:i_,renderInline:Nn,stripHeadingMarkers:On,highlightCode:oc,highlightJS:Ap,highlightBash:Op,highlightJSON:Np,highlightPython:Mp,highlightGo:Lp,highlightRust:Pp,highlightCSS:Ip,highlightHTML:jp,renderTable:a_,renderProgress:c_,wrapAnsi:Mn,StreamRenderer:sc}});var Hp=re((Fv,Up)=>{var{execSync:l_}=require("child_process"),rc=require("path"),po=require("fs"),ic=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Fp(){return rc.join(process.cwd(),".nex","hooks")}function u_(){return rc.join(process.cwd(),".nex","config.json")}function Bp(){let t=u_();if(!po.existsSync(t))return{};try{return JSON.parse(po.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Yr(t){if(!ic.includes(t))return[];let e=[],s=Fp(),n=rc.join(s,t);po.existsSync(n)&&e.push(n);let o=Bp();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function Wp(t,e={},s=3e4){try{return{success:!0,exitCode:0,output:l_(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 d_(t,e={}){let s=Yr(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=Wp(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 f_(t){return Yr(t).length>0}function p_(){let t=[];for(let e of ic){let s=Yr(e);s.length>0&&t.push({event:e,commands:s})}return t}function h_(){let t=Fp();return po.existsSync(t)||po.mkdirSync(t,{recursive:!0}),t}Up.exports={HOOK_EVENTS:ic,loadHookConfig:Bp,getHooksForEvent:Yr,executeHook:Wp,runHooks:d_,hasHooks:f_,listHooks:p_,initHooksDir:h_}});var rh=re((Hv,oh)=>{"use strict";var{callWithRetry:Gp,runSubAgent:m_,clearAllLocks:g_}=Ra(),{parseModelSpec:Kp,getActiveProviderName:Bv,getActiveModelId:Wv}=Ke(),{detectCategory:y_,getModelForCategory:Yp}=ps(),{MultiProgress:$_,C:de}=Ye(),{getModelBriefing:Uv}=_r(),zp=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Gr=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Xp="devstral-2:123b",Vp="kimi-k2.5",Jp=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
|
|
605
640
|
|
|
606
641
|
RULES:
|
|
607
642
|
- Output ONLY a JSON array, no markdown fences, no explanation.
|
|
@@ -616,7 +651,7 @@ RULES:
|
|
|
616
651
|
- If the request is simple (single goal), return an array with exactly 1 item.
|
|
617
652
|
|
|
618
653
|
USER REQUEST:
|
|
619
|
-
{prompt}`,
|
|
654
|
+
{prompt}`,Zp=`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
655
|
|
|
621
656
|
RULES:
|
|
622
657
|
- Output ONLY a JSON object with these fields:
|
|
@@ -630,16 +665,16 @@ ORIGINAL REQUEST:
|
|
|
630
665
|
{prompt}
|
|
631
666
|
|
|
632
667
|
SUB-AGENT RESULTS:
|
|
633
|
-
{results}`;async function
|
|
634
|
-
${e.slice(0,200)}`)}async function
|
|
668
|
+
{results}`;async function Qp(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 eh(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 w_(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 ac(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:
|
|
669
|
+
${e.slice(0,200)}`)}async function th(t,e,s={}){let n=s.maxSubTasks||Gr,r=[{role:"system",content:Jp.replace("{maxSubTasks}",String(n)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let h=Kp(e);h.provider&&(i.provider=h.provider),h.model&&(i.model=h.model)}let c=(await Gp(r,[],i)).content||"",l=ac(c);if(!Array.isArray(l))throw new Error(`Decompose returned non-array: ${typeof l}`);let u=10,f=l.slice(0,n).map((h,b)=>({id:h.id||`t${b+1}`,task:String(h.task||""),scope:Array.isArray(h.scope)?h.scope:[],estimatedCalls:typeof h.estimatedCalls=="number"?Math.min(h.estimatedCalls,u):8,priority:typeof h.priority=="number"?h.priority:b+1})).filter(h=>h.task.length>0),m=f.reduce((h,b)=>h+b.estimatedCalls,0),g=Gr*u;if(m>g){let{debugLog:h}=er();h(`\x1B[33m \u26A0 Orchestrator: total estimated calls ${m} > ${g} \u2014 consider raising maxSubTasks\x1B[0m`)}return f}async function nh(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
670
|
Task: ${u.task}
|
|
636
671
|
Result: ${u.result}
|
|
637
672
|
Tools: ${(u.toolsUsed||[]).join(", ")||"none"}`}).join(`
|
|
638
673
|
|
|
639
|
-
`),r=[{role:"system",content:
|
|
640
|
-
${
|
|
641
|
-
`),i("decomposing"),console.log(`${
|
|
642
|
-
`);let u=Date.now(),d=
|
|
674
|
+
`),r=[{role:"system",content:Zp.replace("{prompt}",e).replace("{results}",n)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(s){let u=Kp(s);u.provider&&(i.provider=u.provider),u.model&&(i.model=u.model)}let c=(await Gp(r,[],i)).content||"",l=ac(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 b_(t,e={}){let s=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Vp,n=e.workerModel||Xp,o=e.maxParallel||zp,r=e.maxSubTasks||Gr,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
|
|
675
|
+
${de.bold}Orchestrator${de.reset} ${de.dim}model: ${s} | workers: ${n} | max parallel: ${o}${de.reset}
|
|
676
|
+
`),i("decomposing"),console.log(`${de.dim}Phase 1: Decomposing prompt into sub-tasks...${de.reset}`);let c;try{c=await th(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 J=K.scope.filter(Boolean);J.length>0&&console.log(` ${de.dim}scope: ${J.join(", ")}${de.reset}`)}console.log("");let l=new Map;for(let K=0;K<c.length;K++)for(let J of c[K].scope)J&&!l.has(J)&&l.set(J,K);i("executing"),console.log(`${de.dim}Phase 2: Running ${c.length} sub-agents (max ${o} parallel)...${de.reset}
|
|
677
|
+
`);let u=Date.now(),d=eh(o),f={findings:[],_lock:!1},m=c.map(K=>{let J=y_(K.task);return(J?Yp(J.id):null)||n}),g=c.map((K,J)=>{let me=`Agent ${J+1} [${m[J]}]: `,fe=Math.max(20,60-me.length),$e=K.task.substring(0,fe)+(K.task.length>fe?"...":"");return me+$e}),h=new $_(g);h.start();let b=`
|
|
643
678
|
You are a focused coding agent executing ONE specific sub-task.
|
|
644
679
|
Your scope is limited to the files listed in your task definition.
|
|
645
680
|
|
|
@@ -660,40 +695,40 @@ RULES:
|
|
|
660
695
|
- If your task says "add X to README" \u2014 add it, don't check if it exists first.
|
|
661
696
|
- Max 10 tool calls. If you need more, you are doing too much \u2014 narrow your scope.
|
|
662
697
|
- 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:O,synthesis:
|
|
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
|
|
698
|
+
`,x=new Map;for(let K=0;K<c.length;K++){let J=c[K].priority||1;x.has(J)||x.set(J,[]),x.get(J).push({st:c[K],idx:K})}let j=[...x.keys()].sort((K,J)=>K-J),Y=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 A(fe,$e,{acquire:d,subTaskModels:m,labels:g,progress:h,sharedContext:f,_fileOwnership:l,workerModel:n,WORKER_SYSTEM_PROMPT:b});return Y[$e]=Re,Re}finally{pe()}});await Promise.all(me)}async function A(K,J,me){try{let fe=f.findings.filter(H=>H.agentId!==K.id).map(H=>`Agent ${H.agentId} found: ${H.summary}`).join(`
|
|
699
|
+
`),$e=[...l.entries()].filter(([,H])=>H===J).map(([H])=>H),pe=[...l.entries()].filter(([,H])=>H!==J).map(([H])=>H),Re=[fe?`Prior agent findings:
|
|
700
|
+
${fe}
|
|
701
|
+
`:"",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=sh(K.task),I=m[J],v=process.env.NEX_FALLBACK_MODEL||Yp("agentic")||n,M=0,R=await Qp(async()=>{let H=M>0;H&&(h.update(J,"retry"),process.stderr.write(` ${de.dim}[Agent ${J+1}] retrying after error...${de.reset}
|
|
702
|
+
`)),M++;let Se=H&&I!==v?v:I;return m_({task:K.task,type:w,context:Re.length>0?Re.join(`
|
|
703
|
+
`):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 ${J+1} [${Se}]`,hi=xe.tool||"...";h.labels[J]=`${ge}: ${hi}`}}})},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:[]}),h.labels[J]=g[J],h.update(J,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:J}}catch(fe){return h.labels[J]=g[J],h.update(J,"error"),{task:K.task,status:"failed",result:`Error: ${fe.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let O;try{O=Y}finally{h.stop({silent:!0}),g_()}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<O.length;K++){let J=O[K],fe=J.status==="done"||J.status==="truncated"&&J.result&&!J.result.startsWith("Error")?`${de.green}\u2713${de.reset}`:`${de.red}\u2717${de.reset}`,$e=J._scope&&J._scope.length>0?J._scope.map(w=>w.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],pe=$e.length>0?$e.join(", "):J.task.substring(0,35)+(J.task.length>35?"...":""),Re=K===O.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 G;try{G=await nh(O,t,s)}catch(K){console.log(`${de.yellow}Synthesize failed: ${K.message} \u2014 using raw results.${de.reset}`),G={summary:O.map(J=>J.result).join(`
|
|
704
|
+
`),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(`
|
|
705
|
+
${de.bold}Summary:${de.reset} ${G.summary}${T}`),G.conflicts.length>0){console.log(`${de.yellow}Conflicts:${de.reset}`);for(let K of G.conflicts)console.log(` - ${K}`)}G.commitMessage&&console.log(`${de.dim}Suggested commit: ${G.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}
|
|
706
|
+
`),{results:O,synthesis:G,totalTokens:a}}var __=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,x_=/\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 sh(t){if(!t)return"implement";let e=__.test(t);return x_.test(t)?"implement":e?"explore":"implement"}oh.exports={runOrchestrated:b_,decompose:th,synthesize:nh,detectComplexPrompt:w_,extractJSON:ac,createSemaphore:eh,DECOMPOSE_PROMPT:Jp,SYNTHESIZE_PROMPT:Zp,DEFAULT_ORCHESTRATOR_MODEL:Vp,DEFAULT_WORKER_MODEL:Xp,DEFAULT_MAX_PARALLEL:zp,DEFAULT_MAX_SUBTASKS:Gr,withRetry:Qp,_classifyWorkerType:sh}});var Th=re((Vv,Eh)=>{var{C:p,Spinner:$s,TaskProgress:k_,formatToolCall:v_,formatToolSummary:bc,formatSectionHeader:Kr,formatMilestone:S_,setActiveTaskProgress:Yv,getThinkingVerb:cc,setActiveModelForSpinner:E_}=Ye(),{debugLog:F,warnLog:Gv}=er(),{MilestoneTracker:T_}=su(),{callStream:ih}=Ke(),{parseToolArgs:R_}=Rs(),{executeTool:C_}=ts(),{gatherProjectContext:A_}=Jf(),{fitToContext:O_,forceCompress:qt,getUsage:Rt,estimateTokens:N_,buildProgressSnapshot:M_}=jt(),{autoSave:L_,flushAutoSave:P_}=Dr(),{scoreMessages:I_,formatScore:j_,appendScoreHistory:D_}=qr(),{detectCategory:q_,getModelForPhase:_c,getPhaseBudget:Ln,isPhaseRoutingEnabled:F_}=ps();function qe(t){L_(t),P_()}function B_(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 lc(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=I_(t);if(!s)return;console.log(j_(s,p));try{let{_getSessionsDir:n}=Dr(),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=Io();D_(s.score,{version:o.version,model:n?n():null,sessionName:"_autosave",issues:s.issues})}catch{}}catch{}}var{getMemoryContext:W_}=Zs(),{getDeploymentContextBlock:U_,probeUrlServer:H_}=Ga(),{getFewShotForInput:Y_}=yp(),{checkPermission:G_,setPermission:K_,savePermissions:z_}=kp(),{confirm:$h,setAllowAlwaysHandler:X_,getAutoConfirm:V_}=As(),{isPlanMode:xo,getPlanModePrompt:J_,PLAN_MODE_ALLOWED_TOOLS:wh,setPlanContent:Z_,extractStepsFromText:Q_,createPlan:ex,getActivePlan:Kv,startExecution:zv,advancePlanStep:tx,getPlanStepInfo:nx}=Hr(),{StreamRenderer:sx}=qp(),{runHooks:ah}=Hp(),{routeMCPCall:ox,getMCPToolDefinitions:rx}=ra(),{getSkillInstructions:ix,getSkillToolDefinitions:ax,routeSkillCall:cx,matchSkillTriggers:lx}=sa(),{trackUsage:ch,estimateTokens:lh}=Qo();function uh(t){return!t||typeof t!="string"?0:typeof lh=="function"?lh(t):Math.ceil(t.length/4)}var{validateToolArgs:ux}=ca(),{filterToolsForModel:dh,getModelTier:dx,PROVIDER_DEFAULT_TIER:Xv}=Fs(),{getConfiguredProviders:fx,getActiveProviderName:ws,getActiveModelId:Ot,setActiveModel:fh,MODEL_EQUIVALENTS:ii}=Ke(),{getModelProfile:px,getModelBriefing:hx}=_r(),Mc=require("fs"),Lc=require("path"),mx=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function gx(t){let e=S_(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
|
|
707
|
+
`)}var ph=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function yx(t){let e=[],s;for(ph.lastIndex=0;(s=ph.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):Lc.resolve(n);Mc.existsSync(o)&&e.push({raw:n,abs:o})}return e}function $x(t){let e=Mc.readFileSync(t),s=Lc.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 bh(t){let e=yx(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}=$x(n.abs);s.push({type:"image",media_type:r,data:o})}catch{}return s.length>1?s:t}var wx=[/\bwtf\b/i,/\buff\b/i,/\bugh\b/i,/\bffs\b/i,/\bargh\b/i,/why (?:isn'?t|doesn'?t|won'?t|can'?t|don'?t)/i,/(?:still|again) (?:broken|not working|failing|wrong)/i,/already told you/i,/come on[!.]/i,/seriously\?/i,/how (?:many|much) (?:times|more)/i,/nothing (?:works?|is working)/i];function _h(t){return typeof t!="string"||!t?!1:wx.some(e=>e.test(t))}function bx(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=`
|
|
708
|
+
|
|
709
|
+
[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 xc(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let s=t.split(`
|
|
675
710
|
`),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
711
|
|
|
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
|
|
712
|
+
\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 uc=null,dc=null,fc=null;function et(){if(uc===null){let{TOOL_DEFINITIONS:t}=ts();uc=t}return dc===null&&(dc=ax()),fc===null&&(fc=rx()),[...uc,...dc,...fc]}var kc=50;function _x(t){Number.isFinite(t)&&t>0&&(kc=t)}var Vr=()=>null;function xx(t){Vr=t}var go=null,vc=null,bs=null,Jr=new Map,kx=1e4,vx=6e3,Sx=/\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 Ex(t){return!t||typeof t!="string"?t:t.replace(Sx,(e,s)=>`${s}=***REDACTED***`)}var Tx=7e3,Rx=4e3;function Cx(t,e=null){let s=Ex(t),n=N_(s),o=e==="read_file"?Tx:kx,r=e==="read_file"?Rx:vx;if(n>o)try{let{compressToolResult:i}=jt();return i(s,r)}catch{return s}return s}function xh(t){try{let{getActiveModel:e}=Ke(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Jr.has(n))return Jr.get(n);let o=dh(t);return Jr.set(n,o),o}catch{return dh(t)}}function Ax(){Jr.clear()}var yo={hash:null,ts:0},Ox=3e4;async function kh(){if(yo.hash&&Date.now()-yo.ts<Ox)return yo.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}=Zs(),a=i();a&&o.push(`memory:${a}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Mc.existsSync(i)){let a=await t.stat(i);o.push(`brain:${a.mtimeMs}`)}}catch{}let r=o.join("|");return yo={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function Sc(){go=null,vc=null,yo={hash:null,ts:0},bs=null}var Nx=new Set(["spawn_agents"]),pc=5,hc=3,zr=2,hh=6e4,mc=12e4,Mx=process.env.NEX_STALE_AUTO_SWITCH!=="0";function Lx(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{}}X_(t=>{K_(t,"allow"),z_(),console.log(`${p.green} \u2713 ${t}: always allow${p.reset}`)});async function Px(t){let e=t.function.name,s=R_(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let u=et().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
713
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
679
714
|
|
|
680
715
|
Expected JSON schema for "${e}":
|
|
681
716
|
${d}
|
|
682
717
|
|
|
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=(
|
|
718
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=ux(e,s);if(!o.valid){F(`${p.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
719
|
+
`)[0]}${p.reset}`);let l=(gh.get(e)||0)+1;gh.set(e,l);let u=l>=2?`${o.error}
|
|
685
720
|
|
|
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(h)&&!/npm|yarn|pnpm|make|git\b/.test(h)?
|
|
690
|
-
HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(h)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test(h)&&(
|
|
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
|
-
${
|
|
721
|
+
[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(xo()&&!wh.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 an++,F(`${p.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${an})${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=G_(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 $h(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 Ix(t,e,s={}){let n=await cx(t,e);if(n!==null)return n;let o=await ox(t,e);return o!==null?o:C_(t,e,s)}function jx(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 gc(t,e=!1){e||console.log(v_(t.fnName,t.args));let s=ah("pre-tool",{tool_name:t.fnName}),n=s.results;if(s.blocked){let h=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${s.blockReason}`;e||console.log(`${p.yellow} [hook pre-tool] BLOCKED: ${s.blockReason}${p.reset}`);let b=bc(t.fnName,t.args,h,!0);return e||console.log(b),{msg:{role:"tool",content:h,tool_call_id:t.callId},summary:b}}if(!e&&n.length>0)for(let h of n)h.success?console.log(`${p.dim} [hook pre-tool] ${h.command} \u2192 ${h.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook pre-tool] ${h.command} \u2192 ERROR: ${h.error}${p.reset}`);Wt?.onToolStart&&Wt.onToolStart(t.fnName,t.args);let o=await Ix(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=String(o??""),i=r.length>5e4?r.substring(0,5e4)+`
|
|
722
|
+
...(truncated ${r.length-5e4} chars)`:r,a=i.split(`
|
|
723
|
+
`)[0],c=a.startsWith("ERROR")||a.includes("CANCELLED")||a.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(i)&&/✗ Agent/.test(i),l=bc(t.fnName,t.args,i,c);e||console.log(l),Wt?.onToolEnd&&Wt.onToolEnd(t.fnName,l,!c);let d=ah("post-tool",{tool_name:t.fnName}).results;if(!e&&d.length>0)for(let h of d)h.success?console.log(`${p.dim} [hook post-tool] ${h.command} \u2192 ${h.output||"ok"}${p.reset}`):console.log(`${p.yellow} [hook post-tool] ${h.command} \u2192 ERROR: ${h.error}${p.reset}`);let m=Cx(i,t.fnName);if(t.fnName==="bash"&&t.args?.command){let h=t.args.command.trim();!/cat\s*>|<</.test(h)&&/\bcat\s+\S/.test(h)?m+=`
|
|
724
|
+
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(h)&&!/npm|yarn|pnpm|make|git\b/.test(h)?m+=`
|
|
725
|
+
HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`:/\bfind\s+\S/.test(h)&&!/git\b|npm\b|-exec\b|-delete\b|-print0\b/.test(h)&&(m+=`
|
|
726
|
+
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:m,tool_call_id:t.callId},summary:l}}var Dx=[{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 yc(t){for(let{re:e,label:s}of Dx){let n=t.match(e);if(n){let o=(n[1]||"").trim();return o?`${s}: ${o}`:s}}return null}async function qx(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=jx(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 gc(t[c],e);n[c]=l,o.push(u)}else{let c=r.map(u=>gc(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(bc(l.fnName,l.args||{},l.errorResult.content,!0));continue}if(Nx.has(l.fnName)){await a(),l.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:u,summary:d}=await gc(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=[],mh=300,vh=900*1e3;function Ft(t,e){let s=t.get(e);return s?Date.now()-s.ts>vh?(t.delete(e),0):s.count:0}function Pn(t,e){let s=t.get(e),n=s&&Date.now()-s.ts<=vh?s.count+1:1;return t.set(e,{count:n,ts:Date.now()}),n}function $c(t,e,s){t.set(e,{count:s,ts:Date.now()})}var Pc=new Map,Ic=new Map,ko=new Map,jc=new Map,vo=new Map,rn=new Map,Vt=new Map,So=new Map,xt=new Map,qn=new Map,gh=new Map,ai=new Map,ci=new Map,kt=0,$o=0,Zr=0,Ec="",Qr=0,gt=!1,Xr=0,ei=0,In=-1,Tc=!1,ti=0,ni=!1,Bt=0,Ct=!1,Jt=0,At=0,Xe=!1,ct="",wo=0,on=0,si="",jn=0,Dn=0,oi="",vt=!1,Rc=!1,Eo=new Map,To=new Set,bo=null,wc=!1,ho=0,yh=!1,Pe="plan",li=0,we=!1,an=0,Zt=null,Cc=null,Ac=null,_o=0,_s=null;function ys(t,e){t===Ec?(Qr++,er().DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${Qr})${p.reset}
|
|
727
|
+
`)):(Ec=t,Qr=1,F(`${e} \u26A0 ${t}${p.reset}`))}var ri=[];function Fx(t){ri.push(t.trim())}function Bx(){return ri.length===0?null:ri.splice(0,ri.length).join(`
|
|
728
|
+
`)}function mo(t,e,s,n){if(!we)return null;let o=Pe;Pe=t,li=0,Zt=_c(t,_s),Bt=0,Ct=!1,Jt=0,At=0,rn.clear(),Vt.clear(),qn.clear(),ai.clear(),ci.clear(),Ic.clear(),ko.clear(),jc.clear(),vo.clear(),Pc.clear(),So.clear();let r;if(t==="implement")Cc=e?.slice(0,800)||"",r=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
|
|
729
|
+
${Cc}
|
|
695
730
|
|
|
696
|
-
Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`;else if(t==="verify"){
|
|
731
|
+
Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`;else if(t==="verify"){Ac=e?.slice(0,500)||"";let i=s?[...s].join(", "):"none";r=`[PHASE: VERIFICATION] Implementation complete. Verify the changes:
|
|
697
732
|
1. Read each modified file and confirm changes are correct
|
|
698
733
|
2. If test command exists (npm test / pytest): run it
|
|
699
734
|
3. If linter exists: run it
|
|
@@ -701,18 +736,18 @@ Now implement the fix/changes. Do not investigate further \u2014 edit files dire
|
|
|
701
736
|
Report PASS (all good) or FAIL (list specific issues).
|
|
702
737
|
|
|
703
738
|
Files modified: ${i}
|
|
704
|
-
Summary: ${
|
|
739
|
+
Summary: ${Ac}`}return F(`${p.cyan} \u21B3 Phase transition: ${o} \u2192 ${t} (model: ${Zt||"default"})${p.reset}`),r?{role:"user",content:r}:null}function Wx(){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
740
|
`];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
741
|
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
742
|
`)+`
|
|
708
743
|
|
|
709
|
-
`}function
|
|
744
|
+
`}function Ux(){if(bs!==null)return bs;try{let e=fx().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:dx(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
745
|
# Sub-Agent Model Routing
|
|
711
746
|
|
|
712
747
|
`;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
748
|
|---|---|---|
|
|
714
749
|
`;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
|
|
715
|
-
`;return
|
|
750
|
+
`;return bs=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),bs="",""}}var Oc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function Hx(t){let e=t.indexOf(Oc);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+Oc.length).trimStart()}}async function Nc(){let t=await kh()+":"+Ot();if(go!==null&&t===vc)return go;let e=await A_(process.cwd()),s=W_(),n=ix(),o=xo()?J_():"",r=Wx(),i=U_(),a=hx(Ot());return go=`${a?`## Model Briefing
|
|
716
751
|
${a}
|
|
717
752
|
|
|
718
753
|
---
|
|
@@ -733,18 +768,19 @@ ${o}
|
|
|
733
768
|
${r?`${r}
|
|
734
769
|
`:""}${i?`${i}
|
|
735
770
|
|
|
736
|
-
`:""}${
|
|
771
|
+
`:""}${V_()?`# YOLO Mode \u2014 Auto-Execute
|
|
737
772
|
|
|
738
773
|
You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
|
|
739
774
|
- NEVER ask for confirmation \u2014 just execute tasks directly
|
|
740
775
|
- NEVER end responses with questions like "Soll ich...?", "M\xF6chtest du...?", "Shall I...?"
|
|
741
776
|
- When you have enough information, implement the fix immediately \u2014 do not propose or ask
|
|
742
777
|
- If something is ambiguous, make a reasonable assumption and state it, then proceed
|
|
743
|
-
- OVERRIDE "simple questions": If the user pastes any server error
|
|
778
|
+
- OVERRIDE "simple questions": If the user pastes any server error message, SSH investigate FIRST \u2014 NEVER answer from training knowledge alone
|
|
744
779
|
- **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
780
|
- 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
781
|
|
|
747
782
|
`:""}
|
|
783
|
+
<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->
|
|
748
784
|
|
|
749
785
|
# Plan Mode
|
|
750
786
|
|
|
@@ -958,7 +994,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
|
|
|
958
994
|
- Instead: use bash with inline node -e '...' for quick one-off checks.
|
|
959
995
|
- If the test is worth keeping, write it to tests/ with a proper name.
|
|
960
996
|
- Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
|
|
961
|
-
${
|
|
997
|
+
${Ux()}
|
|
962
998
|
|
|
963
999
|
# Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
|
|
964
1000
|
|
|
@@ -1149,67 +1185,72 @@ class ErrorBoundary extends React.Component {
|
|
|
1149
1185
|
- Use migrations for schema changes, never manual ALTER TABLE
|
|
1150
1186
|
- Add database-level constraints (unique, foreign key, check) not just app-level
|
|
1151
1187
|
|
|
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} ${
|
|
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
|
|
1188
|
+
`,vc=t,go}function Sh(){Pc.clear(),Ic.clear(),ko.clear(),jc.clear(),vo.clear(),rn.clear(),Vt.clear(),So.clear(),xt.clear(),qn.clear(),ai.clear(),ci.clear(),kt=0,$o=0,Zr=0,gt=!1,ei=0,In=-1,Tc=!1,ti=0,ni=!1,Bt=0,Ct=!1,Jt=0,At=0,Xe=!1,ct="",wo=0,si="",jn=0,oi="",Dn=0,vt=!1,Rc=!1,Pe="plan",li=0,we=!1,Zt=null,Cc=null,Ac=null,_o=0,an=0,_s=null,Eo.clear(),To.clear(),Ec="",Qr=0}function Yx(){q=[],bo=null,Sh();try{let{resetCompactionFailures:t}=ka();t()}catch{}}function Gx(){q.length>mh&&q.splice(0,q.length-mh)}function Kx(){return q.length}function zx(){return q}function Xx(t){q=t}async function Vx(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),n=(d,f)=>new Promise(m=>{t(d,f,{cwd:s,timeout:3e3},(g,h)=>{m(g?"":(h||"").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(`
|
|
1189
|
+
`):[]).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=Lc.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 m=f.slice(0,5).join(" \xB7 "),g=f.length>5?` +${f.length-5}`:"";l+=`
|
|
1190
|
+
\u{1F4E6} ${m}${g}`}}catch{}return l}function Jx(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(`
|
|
1191
|
+
${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`;Jx(l)}if(To.size>0&&Eo.size>0)for(let l of To){let u=Eo.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 Zx(){if(!process.stdout.isTTY)return{action:"quit"};let t=ws(),e=Ot(),s=ii.fast?.[t],n=ii.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 m=f.toLowerCase().trim();if(process.stdout.write(`${m}
|
|
1192
|
+
`),f==="")return a({action:"quit"});let g=i.find(h=>h.key===m);!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 Wt=null;async function Qx(t,e=null,s={}){let n=px(Ot());hh=n.staleWarn,mc=n.staleAbort,Wt=e;let o=t;bo&&typeof t=="string"&&(o=`${bo}
|
|
1193
|
+
|
|
1194
|
+
${t}`,bo=null),typeof o=="string"&&_h(o)&&(o+=`
|
|
1157
1195
|
|
|
1158
|
-
|
|
1159
|
-
`+
|
|
1160
|
-
`)}catch(be){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",be.message)}let
|
|
1161
|
-
${
|
|
1196
|
+
[Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=bh(o);q.push({role:"user",content:r}),Gx();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}=rh(),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 k_(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 Nc(),f=d;try{let{getBrainContext:be}=Ia(),ke=await be(t);ke&&(f=d+`
|
|
1197
|
+
`+ke+`
|
|
1198
|
+
`)}catch(be){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",be.message)}let g=lx(typeof t=="string"?t:"");if(g.length>0){let be=g.map(ke=>`[Triggered: ${ke.name}]
|
|
1199
|
+
${ke.instructions}`).join(`
|
|
1162
1200
|
`);f+=`
|
|
1163
1201
|
`+be+`
|
|
1164
|
-
`}let
|
|
1165
|
-
${
|
|
1166
|
-
`),
|
|
1202
|
+
`}let h=[{role:"system",content:f},...q];E_(Ot());let b=new $s(cc());b.start();let x=q.length===1,j=x?Vx().catch(()=>null):Promise.resolve(null),Y=x?H_(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),A=et(),[{messages:O,compressed:C,compacted:Z,tokensRemoved:G},ue,ie]=await Promise.all([O_(h,A),j,Y]),se=Rt(h,A);if(b.stop(),ue&&console.log(`${p.dim}${ue}${p.reset}`),Z)console.log(`${p.dim} [context compacted \u2014 summary (~${G} tokens freed)]${p.reset}`);else if(C){let be=se.limit>0?Math.round(G/se.limit*100):0;F(`${p.dim} [context compressed \u2014 ~${G} 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=O;if(ie&&x&&(T=[T[0],{role:"user",content:`[Server probe at task start]
|
|
1203
|
+
${ie}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...T.slice(1)]),x){let be=Y_(typeof t=="string"?t:"");be&&(T=[T[0],{role:"user",content:be.user},{role:"assistant",content:be.assistant},...T.slice(1)])}if(Rt(T,et()).percentage>=65){let{messages:ke,tokensRemoved:Ae}=qt(T,et());Ae>0&&(T=ke,console.log(`${p.dim} [pre-flight compress \u2014 ${Ae} tokens freed, now ${Math.round(Rt(T,et()).percentage)}% used]${p.reset}`))}let Te=0,K=0,J=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(!Xe){let be=q.filter(Ae=>Ae.role==="user"||Ae.role==="tool").map(Ae=>typeof Ae.content=="string"?Ae.content:"").join(`
|
|
1204
|
+
`),ke=yc(be);ke&&(Xe=!0,ct=ke.slice(0,120),F(`${p.yellow} \u26A1 Root cause in briefing: ${ct} \u2014 fix phase active from start (read budget: 3)${p.reset}`))}!Xe&&!vt&&/\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)&&(vt=!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=F_(),we&&(_s=q_(Re)?.id||"coding",Pe="plan",Zt=_c("plan",_s),li=0,_o=0,an=0,process.stdout.isTTY&&console.log(`${p.dim} \u21B3 Phase routing: plan(${Zt||"default"}) \u2192 implement \u2192 verify${p.reset}`),F(`${p.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${Zt||"default model"} (category: ${_s})${p.reset}`)));let v=0,M=new Map,R=new Set,k=new Set,H=Date.now(),Se=new T_(mx),xe=So,ge=s.skillLoop?10:1,hi=3*ge,Wh=5*ge,Kc=Pc,Uh=5*ge,Hh=8*ge,Yh=Ic,Gh=(we?6:4)*ge,Kh=(we?10:7)*ge,mi=ko,zh=(we?5:3)*ge,Co=(we?8:5)*ge,Xh=jc,Vh=(we?4:3)*ge,Jh=(we?6:4)*ge,Zh=3*ge,Qh=4*ge,Fn=rn,em=(we?3:2)*ge,tm=(we?5:3)*ge,Bn=(we?6:4)*ge,nm=25,cn=0,sm=6*ge,om=10*ge,ln=0,zc=5*ge,un=0,rm=2*ge,im=3,gi=0,vs=10,am=16,Xc=s.skillLoop?999:n.investigationCap,We,Nt=s.maxIterations||(we?Ln(Pe):kc),yi=0,Vc=3,$i=!1,Ao=0;e:for(;;){for($i=!1,We=0;We<Nt&&!Vr()?.aborted;We++){{let $=et(),y=Rt(T,$),ee=v===0?65:78;if(y.percentage>=ee){if(R.size>0||we&&Pe!=="plan"){let Q=M_(q,{filesModified:R,currentPhase:we?Pe:null});if(Q){let D=T.findIndex(L=>L._progressSnapshot);D!==-1&&T.splice(D,1);let le=T.findIndex(L=>L.role==="system");T.splice(le+1,0,Q)}}let{messages:S,tokensRemoved:N}=qt(T,$,v===0);if(N>0&&(T=S,N>50&&console.log(`${p.dim} [auto-compressed \u2014 ~${N} tokens freed, now ${Math.round(Rt(T,$).percentage)}%]${p.reset}`),vt&&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(gt&&!Xe&&wo<2){wo++;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 #${wo} injected \u2014 model told to synthesize${p.reset}`)}gt||(wo=0);let ke=!0;v>0&&tx();let Ae=null;if(l&&l.isActive())l._paused&&l.resume();else if(!l){let $,y=nx();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?`${cc()} (step ${v+1})`:cc();Ae=new $s($),Ae.start()}let Wn=!0,ut="",Un=!1,Je=new sx,Mt,wi=Date.now(),Oo=!1,bi=new AbortController,Jc=setInterval(()=>{let $=Date.now()-wi;if($>=mc)Je._clearCursorLine(),F(`${p.yellow} \u26A0 Stream stale for ${Math.round($/1e3)}s \u2014 aborting and retrying${p.reset}`),bi.abort();else if($>=hh&&!Oo){Oo=!0,Je._clearCursorLine();let y=ii.fast?.[ws()],ee=J>0?` (retry ${J+1}/${zr})`:"",S=Math.round((mc-$)/1e3);F(`${p.yellow} \u26A0 No tokens received for ${Math.round($/1e3)}s \u2014 waiting...${ee}${p.reset}`),y&&y!==Ot()?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),yt="",Ut=null;try{let $=xh(et()),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;xo()?S=$.filter(D=>wh.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 N=Vr(),Q=new AbortController;N&&N.addEventListener("abort",()=>Q.abort(),{once:!0}),bi.signal.addEventListener("abort",()=>Q.abort(),{once:!0}),Mt=await ih(T,S,{signal:Q.signal,...Zt?{model:Zt}:{},onThinkingToken:()=>{wi=Date.now(),Oo=!1,Wt?.onThinkingToken&&Wt.onThinkingToken()},onToken:D=>{if(wi=Date.now(),Oo=!1,Wt?.onToken){Wt.onToken(D),ut+=D;return}if(ut+=D,!Un&&ut.length>400&&ut.length%250<D.length+1){let le=xc(ut,3);le.truncated&&(Un=!0,Je._clearCursorLine?.(),F(`${p.yellow} \u26A0 LLM stream loop detected (${le.repeatCount}\xD7 repeated) \u2014 suppressing display${p.reset}`))}Un||(yt+=D,process.stdout.isTTY?Ut||(Ut=setTimeout(()=>{yt&&Je&&Je.push(yt),yt="",Ut=null},50)):(Je.push(yt),yt=""),Wn&&(l&&!l._paused?l.pause():Ae&&Ae.stop(),ke||(ke=!0),Je.startCursor(),Wn=!1))}})}catch($){if(clearInterval(Jc),Ut&&(clearTimeout(Ut),Ut=null),yt&&Je&&(Je.push(yt),yt=""),l&&!l._paused&&l.pause(),Ae&&Ae.stop(),Je.stopCursor(),bi.signal.aborted&&!Vr()?.aborted){if(J++,J>zr){if(me<1){me++,ys("Stale retries exhausted \u2014 last-resort force-compress...",p.yellow);let le=et(),{messages:L,tokensRemoved:B}=qt(T,le);T=L,B>50&&F(`${p.dim} [force-compressed \u2014 ~${B} tokens freed]${p.reset}`),J=0,We--;continue}l&&(l.stop(),l=null);let D=await Zx();if(D.action==="quit"){c(null),Fe(v,M,R,k,H),qe(q);break}D.action==="switch"&&(fh(`${D.provider}:${D.model}`),console.log(`${p.green} \u2713 Switched to ${D.provider}:${D.model}${p.reset}`)),J=0,We--;continue}let N=J===1?3e3:5e3;if(J>=1&&pe<1){pe++,ys(`Stale retry ${J}/${zr} \u2014 force-compressing before retry...`,p.yellow);let D=et(),{messages:le,tokensRemoved:L}=qt(T,D,!0);if(T=le,L>0&&L>50&&F(`${p.dim} [force-compressed \u2014 ~${L} tokens freed]${p.reset}`),Mx){let B=ii.fast?.[ws()];B&&B!==Ot()&&(fh(`${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 ${J}/${zr} \u2014 retrying in ${N/1e3}s...${p.reset}`);let Q=new $s(`Waiting ${N/1e3}s before retry...`);Q.start(),await new Promise(D=>setTimeout(D,N)),Q.stop(),We--;continue}if($.name==="AbortError"||$.name==="CanceledError"||$.message?.includes("canceled")||$.message?.includes("aborted")){l&&(l.stop(),l=null),c(null),Fe(v,M,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): ${Ot?Ot():"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,M,R,k,H),qe(q);break}else if($.message.includes("400")){if(me<3&&fe<$e){me++,fe++;let N=v===0&&me===1,Q=N||me===3||pe>0;if(N){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=et(),{messages:le,tokensRemoved:L}=qt(T,D,Q);T=le,L>50&&F(`${p.dim} [force-compressed \u2014 ~${L} tokens freed]${p.reset}`),We--;continue}{let N=T.find(W=>W.role==="system"),Q=T.find(W=>W.role==="user"&&!String(W.content).startsWith("[SYSTEM")&&!String(W.content).startsWith("BLOCKED:")),D=[N,Q].filter(Boolean),{getUsage:le}=jt(),L=jt().estimateMessagesTokens(D),B=jt().estimateMessagesTokens(T);if(L<B){let W=[],z=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," "));z.length>0&&W.push(`Key findings:
|
|
1167
1205
|
`+z.map(ne=>`- ${ne}`).join(`
|
|
1168
|
-
`));let
|
|
1206
|
+
`));let V=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
1207
|
`).slice(0,8).join(`
|
|
1170
|
-
`).slice(0,500));if(
|
|
1171
|
-
`+
|
|
1172
|
-
`)),
|
|
1173
|
-
${JSON.stringify(
|
|
1208
|
+
`).slice(0,500));if(V.length>0&&W.push(`Tool results summary:
|
|
1209
|
+
`+V.map(ne=>`- ${ne}`).join(`
|
|
1210
|
+
`)),R.size>0){let ne=[...R].map(Me=>Me.split("/").slice(-2).join("/")).join(", ");W.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(", ");W.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:vt,wipeNumber:$o+1,timestamp:Date.now()},null,2)),W.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(Ge=>Ge.type==="text").map(Ge=>Ge.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(Ge=>Ge.trim()).filter(Boolean),Ue=[...R],$t=Me.filter(Ge=>!Ue.some(ki=>ki.endsWith(Ge)||Ge.endsWith(ki.split("/").pop())));he=$t.length;let dt=[...q].reverse().find(Ge=>Ge.role==="tool"&&typeof Ge.content=="string"&&!Ge.content.startsWith("BLOCKED:")&&Ge.content.length>5),Yt={completed:Ue.map(Ge=>Ge.split("/").slice(-2).join("/")),pending:$t.length>0?$t:Ue.length===0?["(task files not yet identified)"]:[],lastEdit:dt?dt.content.trim().slice(0,120):null};(Yt.completed.length>0||Yt.pending.length>0)&&W.unshift(`Work manifest:
|
|
1211
|
+
${JSON.stringify(Yt,null,2)}`)}if(W.length>0){let ne={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
|
|
1174
1212
|
${W.join(`
|
|
1175
1213
|
`)}
|
|
1176
|
-
Continue implementing the fixes based on these findings.`};
|
|
1177
|
-
Files modified so far: ${[...
|
|
1214
|
+
Continue implementing the fixes based on these findings.`};D.push(ne)}if($o>=3){let ne=R.size>0?`
|
|
1215
|
+
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,M,R,k,H,{suppressHint:!0}),qe(q);break}T=D,$o++,In=12+Math.min(he*3,15),Tc=!0,ti=R.size,ni=!1,kt=0,I=0;for(let[ne,Me]of rn){let Ue=Me?.count??Me??0;$c(rn,ne,Ue>=2?Ue:1)}for(let[ne]of Vt)Ft(rn,ne)<2&&Vt.delete(ne);xt.clear(),qn.clear(),vt&&At>0&&(Ct=!0,F(`${p.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${At} edits already made)${p.reset}`));for(let[ne]of ko)$c(ko,ne,Co-1);if(ys(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${B-L} tokens freed)`,p.yellow),$o>=1){let ne=[...rn.entries()].filter(([,dt])=>dt>=Bn).map(([dt])=>dt.split("/").slice(-1)[0]),Me=ne.length>0?`
|
|
1178
1216
|
|
|
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
|
-
${
|
|
1217
|
+
Files already at read cap \u2014 use grep_search instead: ${ne.join(", ")}`:"",$t={role:"user",content:gt&&!Xe?"[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($t),T.push($t)}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>pc){console.log(`${p.red} Rate limit: max retries (${pc}) exceeded. Try again later or use /budget to check your limits.${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,M,R,k,H),qe(q);break}let N=Math.min(1e4*Math.pow(2,Te-1),12e4),Q=new $s(`Rate limit \u2014 waiting ${Math.round(N/1e3)}s (retry ${Te}/${pc})`);Q.start(),await new Promise(D=>setTimeout(D,N)),Q.stop();continue}let ee=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return Ke().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>hc){console.log(`${p.red} Network error: max retries (${hc}) exceeded. Check your connection and try again.
|
|
1218
|
+
Use /undo to revert changes made during this session.${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,M,R,k,H),qe(q);break}let N=Math.min(2e3*Math.pow(2,K-1),3e4),Q=new $s(`API temporarily unavailable \u2014 retrying in ${Math.round(N/1e3)}s (${K}/${hc}). Your changes are safe.`);Q.start(),await new Promise(D=>setTimeout(D,N)),Q.stop(),We--;continue}l&&(l.stop(),l=null),c(null),Fe(v,M,R,k,H),qe(q);break}if(clearInterval(Jc),Te=0,K=0,Wn&&(l&&!l._paused&&l.pause(),Ae&&Ae.stop()),Ut&&(clearTimeout(Ut),Ut=null),yt&&Je&&(Je.push(yt),yt=""),ut&&Je.flush(),K=0,J=0,Mt&&Mt.usage){let $=Mt.usage.prompt_tokens||0,y=Mt.usage.completion_tokens||0;ch(ws(),Ot(),$,y),u+=$+y,l&&l.setStats({tokens:u})}else if(Mt&&!Mt.usage){let $=T.map(S=>typeof S.content=="string"?S.content:Array.isArray(S.content)?S.content.map(N=>typeof N=="string"?N:N.text||"").join(""):"").join(" "),y=uh($),ee=uh(Mt.content||ut||"");ch(ws(),Ot(),y,ee),u+=y+ee,l&&l.setStats({tokens:u})}let{content:Zc,tool_calls:Ht}=Mt,No=xc(Zc||""),Qc=No.truncated?No.text:Zc;No.truncated&&F(`${p.yellow} \u26A0 LLM output loop detected (${No.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${p.reset}`);let Mo=bx(Qc||""),Lt=Mo.truncated?Mo.text:Qc;Mo.truncated&&F(`${p.yellow} \u26A0 LLM output loop detected (${Mo.repeatCount}\xD7 repeated window) \u2014 response truncated${p.reset}`);let _i={role:"assistant",content:Lt||""};if(Ht&&Ht.length>0&&(_i.tool_calls=Ht),q.push(_i),T.push(_i),!Xe&&Lt&&Ht&&Ht.length>0){let $=yc(Lt);if($){Xe=!0,ct=$.slice(0,120),Bt=0,Ct=!1,Jt=0,F(`${p.yellow} \u26A1 Root cause in model analysis: ${ct} \u2014 fix phase (read budget: 3)${p.reset}`);let y={role:"user",content:`[SYSTEM] Root cause identified: ${ct}. Read only the file that needs fixing, then edit it. Do not read other files.`};q.push(y),T.push(y)}}if(!Ht||Ht.length===0){let $=(Lt||"").trim().length>0||ut.trim().length>0,y=!1;if(gt&&$&&(Xr>=2?F(`${p.yellow} \u26A0 SSH permanently blocked after ${Xr} storm warnings \u2014 no further SSH calls allowed${p.reset}`):(gt=!1,kt=vs-4,y=!0)),y&&$){let S=(Lt||"").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<kc-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((Lt||"").slice(0,600)))if(Tc&&In<=0||gt){F(`${p.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${p.reset}`);let N={role:"user",content:"[SYSTEM] Correct \u2014 remote access is currently limited. Summarize what you have found so far and tell the user exactly what specific information (logs, process list, error output) you need from the server to continue."};T.push(N),q.push(N);continue}else{F(`${p.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${p.reset}`);let N={role:"user",content:"[SYSTEM] You have full tool access. Use your tools to investigate and implement the fix directly \u2014 do not say you cannot use tools. If SSH is needed, use a single targeted command that captures the most relevant information rather than multiple sequential calls."};T.push(N),q.push(N);continue}if(s.skillLoop&&$&&v>3&&Ao<5){let S=(Lt||ut||"").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))){Ao=(Ao||0)+1,F(`${p.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${Ao}${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"&&an>=2){F(`${p.cyan} \u21B3 Plan phase: ${an} consecutive blocks \u2014 auto-advancing to implement${p.reset}`),an=0;let S=mo("implement","[auto-advance: task only requires direct action]");if(S){q.push(S),T.push(S),We=0,Nt=Ln("implement");continue}}if(we&&$){let S=(Lt||ut||"").trim();if(Pe==="plan"){let N=mo("implement",S);if(N){q.push(N),T.push(N),We=0,Nt=Ln("implement");continue}}else if(Pe==="implement"&&R.size>0){let N=q.find(le=>le.role==="user"),Q=typeof N?.content=="string"?N.content:"",D=mo("verify",S,R,Q);if(D){q.push(D),T.push(D),We=0,Nt=Math.min(Ln("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&&_o<1){_o++;let D={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
|
|
1219
|
+
${S.slice(0,400)}
|
|
1182
1220
|
|
|
1183
|
-
Fix the identified issues. This is the final attempt.`};
|
|
1221
|
+
Fix the identified issues. This is the final attempt.`};Pe="implement",Zt=_c("implement",_s),q.push(D),T.push(D),We=0,Nt=Ln("implement"),F(`${p.yellow} \u21B3 Verify \u2192 implement loop-back #${_o} (issues found)${p.reset}`);continue}if(F(`${p.green} \u2713 Verification phase complete${Q?" (loop-back exhausted)":" (PASS)"}${p.reset}`),!Q){Fe(v,M,R,k,H),qe(q),lc(q);break e}}}if(xo()&&$&&v===0)if(Zr++,Zr>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
1222
|
|
|
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()){W(),z(!1),
|
|
1223
|
+
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 (${Zr}/2): no files read \u2014 forcing investigation${p.reset}`);continue}if(xo()&&$){let S=(Lt||ut||"").trim();Z_(S),Lx(S);let N=Q_(S);if(N.length>0){let Q=q.find(B=>B.role==="user"),D=typeof Q?.content=="string"?Q.content.slice(0,120):"Task";ex(D,N);let le=N.length===1?"step":"steps",L=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:B,startExecution:W,setPlanMode:z}=Hr();process.stdout.write(`
|
|
1224
|
+
${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${N.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 V=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(V||!1)}catch{}let Me=ne.toString().toLowerCase()[0]||"\r";he(Me)})});if(process.stdout.write(`
|
|
1225
|
+
`),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()){W(),z(!1),Sc(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing ${N.length} ${le}...`);let he=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1188
1226
|
|
|
1189
1227
|
Implement the following plan step by step. All tools are now available.
|
|
1190
1228
|
|
|
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,W=await new Promise(z=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",
|
|
1194
|
-
`),W==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(
|
|
1229
|
+
${S}`;q.push({role:"user",content:he}),T.push({role:"user",content:he}),L=!0}}else console.log(`
|
|
1230
|
+
${p.cyan}${p.bold}Plan ready${p.reset} ${p.dim}(${N.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(L){l&&(l.stop(),l=null),We--;continue}}else{let Q=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:D,startExecution:le,setPlanMode:L}=Hr();process.stdout.write(`
|
|
1231
|
+
${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,W=await new Promise(z=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",V=>{try{process.stdin.setRawMode(B||!1)}catch{}z(V.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
|
|
1232
|
+
`),W==="r")console.log(`${p.red}Plan rejected.${p.reset} Ask follow-up questions to refine.`);else if(D()){le(),L(!1),Sc(),console.log(`${p.green}${p.bold}Approved!${p.reset} Executing...`);let V=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1195
1233
|
|
|
1196
1234
|
Implement the following plan step by step. All tools are now available.
|
|
1197
1235
|
|
|
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
|
-
${
|
|
1236
|
+
${getPlanContent()||Mt.content}`;q.push({role:"user",content:V}),T.push({role:"user",content:V}),Q=!0}}else console.log(`
|
|
1237
|
+
${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,M,R,k,H),vt&&R.size>=3){let S=[...R].map(L=>L.split("/").pop()).slice(0,8).join(", "),N=[...R].some(L=>L.endsWith("package.json")),Q=[...R].some(L=>L.endsWith("requirements.txt")),D=[...R].some(L=>L.endsWith("package-lock.json")||L.endsWith("yarn.lock")||L.endsWith("pnpm-lock.yaml")),le=N&&!D?"npm install not yet run":Q?"pip install not yet run":null;bo=`[Previous session created ${R.size} files: ${S}`+(le?` \u2014 ${le}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(vt&&!Rc&&v>0){let S=[...R].some(V=>V.endsWith("package.json")),N=[...R].some(V=>V.endsWith("requirements.txt")||V.endsWith("Pipfile")||V.endsWith("pyproject.toml")),Q=[...R].some(V=>V.endsWith("package-lock.json")||V.endsWith("yarn.lock")||V.endsWith("pnpm-lock.yaml")),D=q.flatMap(V=>{let oe=Array.isArray(V.tool_calls)?V.tool_calls:[],he=Array.isArray(V.content)?V.content.filter(ne=>ne?.type==="tool_use"):[];return[...oe,...he]}).filter(V=>{let oe=V.function?.name||V.name||"";return oe==="bash"||oe==="Bash"}).map(V=>{try{let oe=V.function?.arguments??V.input??{};return(typeof oe=="string"?JSON.parse(oe):oe)?.command||""}catch{return""}}),le=D.some(V=>/pip\s+install|python\s+-m\s+venv/.test(V)),L=D.some(V=>/npm\s+install/.test(V)),W=[...R].some(V=>/\/App\.(js|ts|jsx|tsx)$/.test(V))&&!S&&!L;if(N&&!le||S&&!Q&&!L||W){Rc=!0;let V=[];N&&!le&&V.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),W?V.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):S&&!Q&&!L&&V.push("npm install");let oe=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${V.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;F(`${p.dim} [post-creation] bootstrapping environment (${V.join(", ")})${p.reset}`),q.push({role:"user",content:oe}),T.push({role:"user",content:oe});continue}}if(v>0&&!s._isSummaryTurn&&B_(Lt))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.",N=[...T,{role:"user",content:S}],D=((await ih(N,[],{}))?.content||"").trim();D&&(console.log(`
|
|
1238
|
+
${D}`),q.push({role:"user",content:S},{role:"assistant",content:D}))}catch{}qe(q),lc(q);return}v++,li++,v>=1&&(ke=!1);for(let $ of Ht){let y=$.function.name;M.set(y,(M.get(y)||0)+1)}if(v>=30&&!yh){yh=!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(Ht.map($=>Px($)));{let $=Rt(T,et()),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&&Ft(Fn,D.args.path)>=1&&!D.args?.line_start).map(D=>D.args.path.split("/").slice(-2).join("/")),N=S.length>0;if(y>=70&&ee&&gi<70||y>=85&&gi<85||N){gi=y;let D=y>=85?"URGENT":"WARNING",le;N?(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 L={role:"user",content:`[SYSTEM ${D}] Context ${Math.round(y)}% used (${$.used}/${$.limit} tokens). ${le}`};if(q.push(L),T.push(L),y>=85){let B=N?` (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 xi=new Map;for(let $ of ye){if(!$.canExecute||$.fnName!=="read_file")continue;let y=$.args?.path;if(!y)continue;let ee=Ft(Fn,y),S=xi.get(y)||0,N=ee+S,Q=$.args?.line_start!=null,D=xt.get(y)||0,le=D>0,L=2;if(N>=Bn){let B=y.split("/").slice(-2).join("/"),W=(qn.get(y)||0)+1;if(qn.set(y,W),W===1)F(`${p.red} \u2716 Blocked: "${B}" read ${N}\xD7 \u2014 hard cap (${Bn}) reached${p.reset}`);else if(W===2){F(`${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 (${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(z),T.push(z)}$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: read_file("${y}") denied \u2014 file already read ${N}\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(N>=1&&Q)if(le&&D<=L){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}`),xt.set(y,D-1)}else if(le&&D>L){let B=y.split("/").slice(-2).join("/");F(`${p.red} \u2716 Edit recovery blocked: "${B}" \u2014 ${L} 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 (${L} 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=Vt.get(y)||[],V=!1;for(let[oe,he]of z){let ne=Math.max(B,oe),Me=Math.min(W,he);if(Me>ne){let Ue=Me-ne,$t=W-B||1,dt=he-oe||1,Yt=Ue/dt>=.7&&Ue/$t<.7,Ge=W-B<=nm;if(Ue>=$t||!Ge&&(Ue/$t>=.7||Ue/dt>=.7)){let vi=y.split("/").slice(-2).join("/"),ol=`${y}:${B}-${W}`,Yn=(ai.get(ol)||0)+1;if(ai.set(ol,Yn),F(Yt?`${p.red} \u2716 Blocked superread: "${vi}" lines ${B}-${W} 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: "${vi}" lines ${B}-${W} (\u226570% overlap with lines ${oe}-${he} already in context, block #${Yn})${p.reset}`),Yn>=2){F(`${p.red} \u2716 Escalated range-block: "${vi}" lines ${B}-${W} \u2014 model ignored BLOCKED, injecting system warning${p.reset}`);let rl={role:"user",content:Yt?`[SYSTEM] Read blocked ${Yn}\xD7 for read_file("${y}", lines ${B}-${W}). 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}-${W}). Lines ${oe}-${he} were already read and will NOT change. Use grep_search to find specific content instead.`};q.push(rl),T.push(rl)}$.canExecute=!1,$.errorResult={role:"tool",content:Yt?`BLOCKED: read_file("${y}", lines ${B}-${W}) 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}-${W}) 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},V=!0;break}}}if(!V){let oe=z.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=Ft(mi,y)>=Co;$.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(N>=1){let B=xt.get(y)||0;if(B>0){let W=y.split("/").slice(-2).join("/");console.log(`${p.cyan} \u21A9 Full re-read: "${W}" \u2014 test-failure recovery (${B} remaining)${p.reset}`);let z=B-1;z<=0?xt.delete(y):xt.set(y,z)}else{let W=y.split("/").slice(-2).join("/"),z=(qn.get(y)||0)+1;if(qn.set(y,z),z===1)F(`${p.red} \u2716 Blocked unbounded re-read: "${W}" \u2014 already in context. Use line_start/line_end for specific sections.${p.reset}`);else if(z===2){F(`${p.red} \u2716 Escalated block: "${W}" \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 ${N}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:$.callId}}}$.canExecute&&xi.set(y,(xi.get(y)||0)+1)}if(on>=3)for(let $ of ye)$.canExecute&&($.fnName!=="read_file"&&$.fnName!=="edit_file"||(F(`${p.red} \u2716 Blocked ${$.fnName} \u2014 ${on} consecutive file-not-found errors, must search first${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ${on} 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"),N=require("path").resolve(process.cwd(),y);if(S.existsSync(N)){let Q=S.statSync(N).size,D=Buffer.byteLength(ee,"utf8"),le=Q>0?D/Q:1;if(le<.6&&Q>200){let L=y.split("/").slice(-2).join("/");console.log(`${p.red} \u2716 write_file shrink guard: "${L}" 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 el=new Map;for(let $ of ye){if(!$.canExecute||$.fnName!=="grep")continue;let y=$.args?.path;if(!y)continue;let ee=el.get(y)||0,S=Ft(mi,y)+ee,N=Ft(Fn,y)>=1,Q=N?Math.min(3,Co):Co;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=Ft(Fn,y),L=le>=Bn;if(L){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:L?`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.`:N?`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&&el.set(y,ee+1)}let cm=5,tl=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=tl.get(ee)||0,N=Ft(Kc,ee)+S;N>=cm&&(F(`${p.yellow} \u26A0 Blocked ssh_exec: same command run ${N}\xD7 \u2014 result already in context${p.reset}`),$.canExecute=!1,$.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${N} times and the output is in your context. Use existing results, try a different command, or run it as a local bash call: bash("ssh user@host 'your command'").`,tool_call_id:$.callId}),$.canExecute&&tl.set(ee,S+1)}if(gt){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&&ei<1)gt=!1,ei++,kt=Math.max(0,vs-2),F(`${p.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${ei}/1)]${p.reset}`);else for(let S of $)S.canExecute=!1,S.errorResult={role:"tool",content:Xe?`BLOCKED: ssh_exec denied \u2014 SSH paused (${vs}+ calls). Root cause is known (${ct}). 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&&!gt){for(let $ of ye)if($.canExecute&&["bash","read_file","find_files"].includes($.fnName)){I++;{let y=et(),{messages:ee}=qt(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&&Ct&&vt&&At>=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(!ni&&R.size>ti){ni=!0,In=5,F(`${p.green} \u2713 Post-wipe progress detected (${R.size-ti} 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 lm=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||lm.has($.fnName))continue;let y=JSON.stringify($.args||{}),ee=`${$.fnName}|${y}`,S=Ft(ci,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}`),Pn(ci,ee)}let Ss=l?{skipSpinner:!0,skipSummaries:!0}:{},um=ye.some($=>$.fnName==="ask_user"),nl=!Ss.skipSummaries&&!ke,Lo=null,Hn=null;nl&&!um?(ke=!0,Ss.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(Hn=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write(Kr(ye,v,!1,"blink")),Lo=!0):Wt||process.stdout.write(Kr(ye,v,!1)+`
|
|
1239
|
+
`)):nl&&(ke=!0,Ss.skipSpinner=!0),l&&l._paused&&l.resume();let Po=null;if(Lo&&process.stdout.isTTY&&ye.some(y=>y.canExecute&&(y.fnName==="bash"||y.fnName==="ssh_exec"))){let y=Date.now();Po=setInterval(()=>{let ee=Math.round((Date.now()-y)/1e3);if(ee>=3){let S=`${Kr(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:Ze,summaries:dm}=await qx(ye,!0,{...Ss,skipSummaries:!0});if(Po&&(clearInterval(Po),Po=null),Lo){Lo=null;let $=Kr(ye,v,!1);Hn!==null?process.stdout.write(`\x1B[${Hn};1H\x1B[2K${$}
|
|
1240
|
+
`):process.stdout.write(`\r\x1B[2K${$}
|
|
1241
|
+
`),Hn=null}if(!Ss.skipSummaries){let $=dm.filter((S,N)=>!(ye[N]&&ye[N].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&&gx(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:"))&&(ln++,ln>=zc)){F(`${p.red} \u2716 Loop abort: ${ln} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,M,R,k,H,{suppressHint:!0}),qe(q);return}}for(let $=0;$<ye.length;$++){let y=ye[$];if(!y.canExecute)continue;let ee=Ze[$].content,S=ee.split(`
|
|
1242
|
+
`)[0],N=!S.startsWith("ERROR")&&!S.startsWith("CANCELLED")&&!S.startsWith("Command failed")&&!S.startsWith("EXIT");if(!N&&(y.fnName==="edit_file"||y.fnName==="patch_file")&&y.args?.path&&S.includes("old_text not found")){let L=xt.get(y.args.path)||0;xt.set(y.args.path,L+1)}if(!N&&y.fnName==="bash"&&So.size>0){let L=(y.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(L))for(let[W]of So)xt.has(W)||(xt.set(W,1),F(`${p.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${W.split("/").pop()}"${p.reset}`))}if(!N&&(y.fnName==="read_file"||y.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(S)){if(on++,on>=2){F(`${p.yellow} \u26A0 File-not-found streak: ${on} consecutive misses \u2014 forcing search${p.reset}`);let L={role:"user",content:`[SYSTEM] ${on} 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(L),T.push(L)}}else N&&(y.fnName==="read_file"||y.fnName==="edit_file"||y.fnName==="search_files"||y.fnName==="glob_files")&&(on=0);if(N&&y.fnName==="write_file"&&y.args?.path){let L=y.args.path.split("/").pop(),B=y.args.path.includes("/tests/")||y.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(L)&&!B){F(`${p.yellow} \u26A0 Temp file: "${L}" \u2014 delete with bash rm when done to keep the workspace clean${p.reset}`);let z={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(z),T.push(z)}}if(N&&["write_file","edit_file","patch_file"].includes(y.fnName)&&y.args&&y.args.path){xt.delete(y.args.path),R.add(y.args.path);let L=Pn(xe,y.args.path),B=y.args.path.split("/").slice(-2).join("/");if(L===hi){F(`${p.yellow} \u26A0 Loop warning: "${B}" edited ${L}\xD7 \u2014 possible edit loop${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" edited ${L}\xD7. One more edit max, then move on.`};q.push(W),T.push(W)}else if(L>=Wh){F(`${p.red} \u2716 Loop abort: "${B}" edited ${L}\xD7 \u2014 aborting to prevent runaway loop${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,M,R,k,H,{suppressHint:!0}),qe(q);return}}if(N&&y.canExecute&&we&&(an=0),N&&y.canExecute&&!(we&&Pe==="plan")){let L=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(y.fnName)){Bt=0,Ct=!1,Jt=0,At++;let ne=y.args?.path||y.args?.file_path;ne&&($c(rn,ne,1),Vt.delete(ne))}else L.includes(y.fnName)&&(Bt++,Ct&&Jt++);let W=n.postEditCap,z=we&&Pe==="implement"?Math.min(Xc,6):Xc,V=Xe?3:vt?At>0?2:4:At>0?W:z,oe=3;if(!we&&Ct&&(Xe||vt&&At>=1||Jt>=oe)&&L.includes(y.fnName)){let ne=Xe?`root cause already identified (${ct})`:Jt>=oe?`${Bt} consecutive reads without an edit`:`${At} 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:Xe?`BLOCKED: root cause already identified (${ct}). Use edit_file to fix the issue \u2014 do not read more files.`:vt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":Jt>=oe?`BLOCKED: You have read ${Bt} 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: ${At} 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(Bt>=V&&!Ct){if(Ct=!0,F(`${p.yellow} \u26A0 Investigation cap: ${Bt} read-only calls without an edit \u2014 forcing implementation${p.reset}`),we&&Pe==="plan"){let Ue=[...T].reverse().find(Yt=>Yt.role==="assistant"),$t=typeof Ue?.content=="string"?Ue.content:"",dt=mo("implement",$t);dt&&(q.push(dt),T.push(dt),We=0,Nt=Ln("implement"))}let ne;Xe?ne=`[SYSTEM] Root cause was already identified (${ct}). Edit the file now \u2014 do not read more files.`:gt?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 L=y.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),B=Pn(Kc,L);if(B===Uh){F(`${p.yellow} \u26A0 Loop warning: same bash command run ${B}\xD7 \u2014 possible debug loop${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Same bash command ${B}\xD7. Debug loop detected \u2014 try a different approach.`};q.push(W),T.push(W)}else if(B>=Hh){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,M,R,k,H,{suppressHint:!0}),qe(q);return}}if(y.fnName==="ssh_exec"){kt++;{let W=(Ze[$]?.content??"").split(`
|
|
1243
|
+
`).map(z=>z.trim()).find(z=>z.length>0&&!z.startsWith("**")&&(z.startsWith("EXIT")||/^[\w./-]+:\s/.test(z)||z.startsWith("bash:")||z.startsWith("sh:")))??"";if(W){if(W===si?jn++:(si=W,jn=1),jn===3&&!gt){F(`${p.yellow} \u26A0 SSH repeated-error: "${W.slice(0,60)}" returned ${jn}\xD7 \u2014 nudging to change approach${p.reset}`);let z={role:"user",content:`[SYSTEM WARNING] The last ${jn} SSH commands all failed with the same error: "${W}". 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(z),T.push(z)}}else si="",jn=0}if(kt>=am){F(`${p.red} \u2716 SSH storm abort: ${kt} consecutive ssh_exec calls \u2014 aborting${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,M,R,k,H,{suppressHint:!0}),qe(q);return}else if(kt===vs){{let W=et(),{messages:z}=qt(T,W);T=z}gt=!0,Xr++,F(`${p.yellow} \u26A0 SSH storm warning (#${Xr}): ${kt} consecutive ssh_exec calls \u2014 blocking further SSH${p.reset}`);let B={role:"user",content:Xe?`[SYSTEM WARNING] ${kt} consecutive SSH calls. Root cause identified (${ct}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${kt} 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&&(kt=0);if(y.fnName==="bash"&&y.canExecute){let W=(Ze[$]?.content??"").split(`
|
|
1244
|
+
`).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===oi?Dn++:(oi=W,Dn=1),Dn===3){F(`${p.yellow} \u26A0 Bash repeated-error: "${W.slice(0,60)}" returned ${Dn}\xD7 \u2014 nudging to change approach${p.reset}`);let z={role:"user",content:`[SYSTEM WARNING] The last ${Dn} 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),T.push(z)}}else oi="",Dn=0}if(y.fnName==="bash"&&y.canExecute&&!wc&&y.args?.command){let L=Ze[$]?.content??"";if(/git\s+commit\b/.test(y.args.command)&&!L.startsWith("EXIT")&&!L.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(L)||L.includes("files changed")||L.includes("file changed")||L.includes("insertions(+)")||L.includes("create mode"))){wc=!0,ho=0,F(`${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),T.push(z)}}if(wc&&y.fnName==="bash"&&y.args?.command&&/git\s+(status|diff|log|show)\b/.test(y.args.command)&&(ho++,ho>2)){F(`${p.yellow} \u26A0 Post-commit git verification blocked (call ${ho})${p.reset}`);let B={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(ho-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(N&&y.fnName==="grep"&&y.args&&y.args.pattern){let L=`${y.args.pattern}|${y.args.path||""}`,B=Pn(Yh,L);if(B===Gh){F(`${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),T.push(W)}else if(B>=Kh){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,M,R,k,H,{suppressHint:!0}),qe(q);return}if(y.args.path){let W=Pn(mi,y.args.path),z=Ft(Fn,y.args.path)>=1;if(W===(z?1:zh)){let oe=y.args.path.split("/").slice(-2).join("/");F(`${p.yellow} \u26A0 Loop warning: "${oe}" grepped ${W}\xD7 with different patterns \u2014 context flood risk${p.reset}`);let he={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(he),T.push(he)}}}if(N&&(y.fnName==="glob"||y.fnName==="glob_files"||y.fnName==="search_files")&&y.args){let L=y.args.pattern||y.args.query||y.args.path||"",B=Pn(Xh,L);if(B===Vh){F(`${p.yellow} \u26A0 Loop warning: glob pattern "${L.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),T.push(z)}else if(B>=Jh){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,M,R,k,H,{suppressHint:!0}),qe(q);return}let W=L.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 V=z.toLowerCase();vo.has(V)||vo.set(V,new Set);let oe=vo.get(V);if(oe.add(L),oe.size===Qh){F(`${p.red} \u2716 Glob core-term block: ${oe.size} different patterns all searching for "${V}" \u2014 search loop${p.reset}`);let he={role:"user",content:`[SYSTEM WARNING] You have searched for "${V}" 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 "${V}"${p.reset}`);let he={role:"user",content:`[SYSTEM WARNING] ${oe.size} different glob patterns all target "${V}". 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(N&&(y.fnName==="bash"||y.fnName==="ssh_exec")&&D&&ee.includes('"valid":true')){{let B=et();if(Rt(T,B).percentage>=60){let{messages:z,tokensRemoved:V}=qt(T,B);V>0&&(T=z,console.log(`${p.dim} [pre-stop-compress \u2014 ~${V} tokens freed before STOP injection, now ${Math.round(Rt(T,B).percentage)}%]${p.reset}`))}}let L={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(L),T.push(L),console.log(`${p.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${p.reset}`)}if(ee.startsWith("BLOCKED:")){if(ln++,ln>=zc){F(`${p.red} \u2716 Loop abort: ${ln} consecutive blocked calls \u2014 model not heeding BLOCKED messages${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,M,R,k,H,{suppressHint:!0}),qe(q);return}}else ln=0;if(N)cn=0,$i=!0;else if(cn++,cn===sm){F(`${p.yellow} \u26A0 Loop warning: ${cn} consecutive tool errors \u2014 possible stuck loop${p.reset}`);let L={role:"user",content:`[SYSTEM WARNING] ${cn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};q.push(L),T.push(L)}else if(cn>=om){F(`${p.red} \u2716 Loop abort: ${cn} consecutive errors \u2014 aborting stuck loop${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,M,R,k,H,{suppressHint:!0}),qe(q);return}if(N&&y.fnName==="read_file"&&y.args&&y.args.path){k.add(y.args.path);let L=Pn(Fn,y.args.path);{let V=y.args.line_start!=null&&y.args.line_start||1,oe=y.args.line_start!=null?y.args.line_end||V+350:350;Vt.has(y.args.path)||Vt.set(y.args.path,[]),Vt.get(y.args.path).push([V,oe])}if(y._scrollWarn){let{sectionCount:V,path:oe}=y._scrollWarn,he={role:"user",content:`[SYSTEM WARNING] "${oe}" \u2014 you have now read ${V} 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 ${V} 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=we&&Pe==="plan";if(!z&&W&&L===em){{let oe=et();if(Rt(T,oe).percentage>=60){let{messages:ne}=qt(T,oe);T=ne}}F(`${p.yellow} \u26A0 Loop warning: "${B}" read unbounded ${L}\xD7 \u2014 use line_start/line_end${p.reset}`);let V={role:"user",content:`[SYSTEM WARNING] "${y.args.path}" read ${L}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};q.push(V),T.push(V)}else if(!z&&W&&L>=tm){F(`${p.red} \u2716 Loop abort: "${B}" read unbounded ${L}\xD7 \u2014 aborting runaway read loop${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,M,R,k,H,{suppressHint:!0}),qe(q);return}}if(y.fnName==="spawn_agents"){let L=(ee.match(/\bStatus: done\b/g)||[]).length;if((ee.match(/\bStatus: truncated\b/g)||[]).length>0&&L===0){if(un++,un===rm){F(`${p.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${un}\xD7 in a row${p.reset}`);let W={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${un}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};q.push(W),T.push(W)}else if(un>=im){console.log(`${p.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${un}\xD7 \u2014 aborting stuck swarm${p.reset}`),l&&(l.stop(),l=null),c(null),Fe(v,M,R,k,H,{suppressHint:!0}),qe(q);return}}else L>0&&(un=0)}}{let y=Ze.reduce((ee,S)=>ee+(typeof S.content=="string"?S.content.length:0),0);if(y>2e5){let ee=Ze.map((S,N)=>({i:N,len:typeof S.content=="string"?S.content.length:0})).sort((S,N)=>N.len-S.len);for(let{i:S,len:N}of ee){if(y<=2e5)break;let Q=y-2e5,D=Math.max(N-Q,500);D<N&&typeof Ze[S].content=="string"&&(Ze[S]={...Ze[S],content:Ze[S].content.substring(0,D)+`
|
|
1245
|
+
...(truncated ${N-D} chars \u2014 per-message budget)`},y-=N-D)}}}for(let $ of Ze)q.push($),T.push($);if(!Xe)for(let $=0;$<Ze.length;$++){if(!ye[$]||ye[$].fnName!=="ssh_exec")continue;let y=Ze[$];if(!y||typeof y.content!="string")continue;let ee=yc(y.content);if(ee){Xe=!0,ct=ee.slice(0,120),Bt=0,Ct=!1,Jt=0,F(`${p.yellow} \u26A1 Root cause detected: ${ct} \u2014 fix phase (read budget: 3)${p.reset}`);let S={role:"user",content:`[SYSTEM] Root cause identified: ${ct}. 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;$<Ze.length;$++){let y=ye[$];if(!y)continue;let ee=typeof Ze[$]?.content=="string"?Ze[$].content:"";if(y.fnName==="create_task"){let S=ee.match(/Task #(\d+) created/),N=typeof y.args?.subject=="string"?y.args.subject:"";S&&N&&Eo.set(S[1],N)}else if((y.fnName==="write_file"||y.fnName==="edit_file")&&!ee.startsWith("BLOCKED:")&&ee.trim().length>0){let N=(typeof y.args?.path=="string"?y.args.path:typeof y.args?.file_path=="string"?y.args.file_path:"").split("/").pop().toLowerCase(),Q=N.split(/[._\-/]/).filter(D=>D.length>2);for(let[D,le]of Eo){if(To.has(D))continue;let L=le.toLowerCase().split(/\W+/).filter(W=>W.length>3);Q.filter(W=>L.some(z=>z.includes(W)||W.includes(z))).length>=1&&(To.add(D),F(`${p.green} \u2714 Auto-matched task #${D} to ${N}: ${le.slice(0,60)}${p.reset}`))}}}{let $=et();if(Rt(T,$).percentage>=78){let{messages:ee,tokensRemoved:S}=qt(T,$);S>0&&(T=ee,console.log(`${p.dim} [auto-compressed \u2014 ~${S} tokens freed, now ${Math.round(Rt(T,$).percentage)}%]${p.reset}`))}}let sl=Bx();if(sl){let $={role:"user",content:`[User note mid-run]: ${sl}`};q.push($),T.push($),console.log(`${p.cyan} \u270E Context added${p.reset}`)}}if(We>=Nt){if(l&&(l.stop(),l=null),c(null),Fe(v,M,R,k,H),qe(q),lc(q),we&&Pe==="plan"){let Wn=[...q].reverse().find(Je=>Je.role==="assistant"),ut=typeof Wn?.content=="string"?Wn.content:"",Un=mo("implement",ut);if(Un){q.push(Un),T=[{role:"system",content:await Nc()},...q],Nt=Ln("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}=Ke();if(be()==="ollama"&&yi<Vc){if(R.size===0&&!$i){console.log(`${p.yellow} \u26A0 Max iterations reached with no progress. Stopping.${p.reset}`);break e}yi++,Nt=20,console.log(`${p.dim} \u2500\u2500 auto-extending (+20 turns, ext ${yi}/${Vc}) \u2500\u2500${p.reset}`);continue e}if(console.log(`
|
|
1246
|
+
${p.yellow}\u26A0 Max iterations reached.${p.reset}`),await $h(" Continue for 20 more turns?")){Nt=20;continue e}console.log(`${p.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${p.reset}`)}break e}}Eh.exports={processInput:Qx,clearConversation:Yx,getConversationLength:Kx,getConversationMessages:zx,setConversationMessages:Xx,setAbortSignalGetter:xx,setMaxIterations:_x,invalidateSystemPromptCache:Sc,clearToolFilterCache:Ax,getCachedFilteredTools:xh,buildSystemPrompt:Nc,splitSystemPrompt:Hx,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Oc,getProjectContextHash:kh,buildUserContent:bh,detectFrustration:_h,detectAndTruncateLoop:xc,injectMidRunNote:Fx,resetSessionTracking:Sh}});var Ke=re((Jv,Nh)=>{var{OllamaProvider:ek}=Cl(),{OpenAIProvider:tk}=Ml(),{AnthropicProvider:nk}=jl(),{GeminiProvider:sk}=Bl(),{LocalProvider:ok}=Hl(),{checkBudget:rk}=Qo(),Fc={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"}},Dc=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Ch={};for(let[t,e]of Object.entries(Fc))for(let s of Object.values(e))Ch[s]=t;function qc(t,e){let s=Ch[t];return s&&Fc[s][e]||t}var Ve={},lt=null,Be=null,Ro=[];function St(){if(Object.keys(Ve).length>0)return;xs("ollama",new ek),xs("openai",new tk),xs("anthropic",new nk),xs("gemini",new sk),xs("local",new ok);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;Ve[t]?(lt=t,Be=e||Ve[t].defaultModel):(lt="ollama",Be="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(Ro=s.split(",").map(n=>n.trim()).filter(Boolean))}function xs(t,e){Ve[t]=e}function ik(t){return St(),Ve[t]||null}function Bc(){return St(),Ve[lt]||null}function ak(){return St(),lt}function ck(){return St(),Be}function lk(){St();let t=Bc();if(!t)return{id:Be,name:Be,provider:lt};let e=t.getModel(Be);return e?{...e,provider:lt}:{id:Be,name:Be,provider:lt}}function Ah(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(Ve[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function uk(t){St();let{provider:e,model:s}=Ah(t);if(e){let o=Ve[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(lt=e,Be=s,ui(),!0):!1}let n=Bc();if(n&&n.getModel(s))return Be=s,ui(),!0;for(let[o,r]of Object.entries(Ve))if(r.getModel(s))return lt=o,Be=s,ui(),!0;return!1}function ui(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Th();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=jt();t()}catch{}}function dk(){St();let t=new Set;for(let e of Object.values(Ve))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function fk(){return St(),Object.entries(Ve).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===lt&&s.id===Be}))}))}function pk(){St();let t=[];for(let[e,s]of Object.entries(Ve)){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 hk(t){Ro=Array.isArray(t)?t:[]}function mk(){return[...Ro]}function Rh(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 Oh(t){let e=[lt,...Ro.filter(r=>r!==lt)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],a=Ve[i];if(!a||!a.isConfigured())continue;o++;let c=rk(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?qc(Be,i):Be;return l&&u!==Be&&process.stderr.write(` [fallback: ${i}:${u}]
|
|
1247
|
+
`),await t(a,i,u)}catch(l){if(s=l,!Rh(l)||r>=e.length-1)throw l;if(i==="ollama"&&Dc.length>0){let u=isFallback?qc(Be,i):Be;for(let d of Dc)if(d!==u)try{return process.stderr.write(` [ollama fallback: ${d}]
|
|
1248
|
+
`),await t(a,i,d)}catch(f){if(s=f,!Rh(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 gk(t,e,s={}){return St(),Oh((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function yk(t,e,s={}){if(St(),s.provider){let n=Ve[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 Oh(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 $k(){St();let t=[];for(let[e,s]of Object.entries(Ve))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function wk(){for(let t of Object.keys(Ve))delete Ve[t];lt=null,Be=null,Ro=[]}Nh.exports={registerProvider:xs,getProvider:ik,getActiveProvider:Bc,getActiveProviderName:ak,getActiveModelId:ck,getActiveModel:lk,setActiveModel:uk,getModelNames:dk,parseModelSpec:Ah,listProviders:fk,listAllModels:pk,callStream:gk,callChat:yk,getConfiguredProviders:$k,setFallbackChain:hk,getFallbackChain:mk,resolveModelForProvider:qc,MODEL_EQUIVALENTS:Fc,OLLAMA_FALLBACK_MODELS:Dc,_reset:wk}});var{C:U}=Ye(),bk=Ke(),{TOOL_DEFINITIONS:Mh}=ts(),{saveRoutingConfig:_k}=ps(),Hc=[{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}],Lh=[{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)}],pi=[...Hc,...Lh],Wc=["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 xk(){try{let s=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(s))return Wc;let n=JSON.parse(require("fs").readFileSync(s,"utf-8"));return!Array.isArray(n)||n.length===0?Wc: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 Wc}}var Yc=xk(),kk=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],Ph=(()=>{let t=Yc.slice(0,3);return t.length>=3?t:kk})(),vk=14,di={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},Sk="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 Uc(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:Sk},{role:"user",content:t.prompt}],o=Date.now();try{let r=await bk.callChat(n,Mh,{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=Mh.find(f=>f.function?.name===c);if(s.validArgs=!!t.validateArgs(l,d),d){let f=d.function?.parameters||{},m=f.required||[],g=Object.keys(f.properties||{});s.schemaCompliant=m.every(h=>l[h]!==void 0)&&Object.keys(l).every(h=>g.includes(h))}}}}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?di.producedToolCall:0)+(t.correctTool?di.correctTool:0)+(t.validArgs?di.validArgs:0)+(t.schemaCompliant?di.schemaCompliant:0))*100}var Ih={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 Gc(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=>Ih[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 jh(t){let e={};for(let a of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let c=t.filter(h=>h.categoryScores[a]!==void 0&&h.score>=65).sort((h,b)=>b.categoryScores[a]-h.categoryScores[a]);if(c.length===0)continue;let u=(c[0]?.results||[]).filter(h=>Ih[h.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(h=>d.categoryScores[a]-h.categoryScores[a]<=5).sort((h,b)=>h.avgLatency-b.avgLatency)[0];e[a]={model:g.model,score:g.categoryScores[a],avgLatency:g.avgLatency}}return e}function Dh(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(`
|
|
1249
|
+
${U.bold}${s}${U.reset}`),console.log(r);let i=n.map(u=>u.label.padEnd(u.width)).join(" ");if(console.log(`${U.dim}${i}${U.reset}`),console.log(r),t.forEach((u,d)=>{let f=String(d+1).padEnd(n[0].width),m=u.model.slice(0,n[1].width).padEnd(n[1].width),g=String(u.score).padEnd(n[2].width),h=`${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),Y=`${(u.avgLatency/1e3).toFixed(1)}s`.padEnd(n[7].width),A=u.errorCount>0?`${U.red}${u.errorCount}${U.reset}`:`${U.dim}0${U.reset}`,O=u.score>=80?U.green:u.score>=60?U.yellow:U.red,C=d===0?`${U.yellow}${f}${U.reset}`:`${U.dim}${f}${U.reset}`;console.log(`${C} ${O}${m}${U.reset} ${U.bold}${O}${g}${U.reset} ${h} ${b} ${x} ${j} ${U.dim}${Y}${U.reset} ${A}`)}),console.log(r),t.length>0){let u=t[0];if(console.log(`
|
|
1250
|
+
${U.bold}${U.green}Winner: ${u.model}${U.reset} score ${u.score}/100`),t.length>1){let d=(u.score-t[1].score).toFixed(1);console.log(`${U.dim}+${d} pts over ${t[1].model}${U.reset}`)}}let a=t.filter(u=>u.results.some(d=>!d.error&&(!d.correctTool||!d.validArgs)));if(a.length>0){console.log(`${U.bold}Failing tasks:${U.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),m=d.map(g=>{if(!g.correctTool){let h=g.toolCalled||"(none)";return`${U.dim}${g.taskId}${U.reset} ${U.red}\u2192${h}${U.reset}`}return`${U.dim}${g.taskId}${U.reset} ${U.yellow}bad-args${U.reset}`});console.log(` ${U.dim}${f.padEnd(22)}${U.reset} ${m.join(" ")}`)}console.log()}let c=["coding","frontend","sysadmin","data","agentic"];if(t.some(u=>Object.keys(u.categoryScores).length>1)){console.log(`
|
|
1251
|
+
${U.bold}Best model per task type:${U.reset}`);for(let u of c){let d=t.filter(h=>h.categoryScores[u]!==void 0).sort((h,b)=>b.categoryScores[u]-h.categoryScores[u]);if(d.length===0)continue;let f=d[0],m=f.categoryScores[u],g=m>=80?U.green:m>=60?U.yellow:U.red;console.log(` ${U.dim}${u.padEnd(10)}${U.reset} ${g}${f.model}${U.reset} ${U.dim}${m}/100${U.reset}`)}}console.log()}function qh(t){if(!(!t||t.length<2))try{let e=jh(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(m=>m.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&&(_k(o),console.log(`
|
|
1252
|
+
${U.dim} Routing updated: ${r.join(", ")}${U.reset}`),console.log(`
|
|
1253
|
+
${U.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${U.reset}`))}catch{}}async function Ek({models:t,quick:e=!1,onProgress:s,parallelModels:n=1}={}){let o=e?Hc.slice(0,vk):pi,r=t?.length>0?t:e?Ph:Yc,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 Uc(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 m=await Uc(f,d);i[d].push(m),s?.({model:d,task:f.id,done:!0,score:ks(m),error:m.error})}}});await Promise.all(u)}let a=Gc(i);return Dh(a,o.length),qh(a),a}async function Tk({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 pi){s?.({model:i,task:a.id,done:!1});let c=await Uc(a,i);n[i].push(c),s?.({model:i,task:a.id,done:!0,score:ks(c),error:c.error})}}let r=[...Gc(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),Dh(r,pi.length),qh(r),r}var fi=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function Fh(t){let e=require("fs"),n=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(n))return console.log(`${U.yellow}No scenarios configured.${U.reset} Create ${U.dim}.nex/benchmark-config.json${U.reset} to define your benchmark scenarios.
|
|
1213
1254
|
Example:
|
|
1214
1255
|
{
|
|
1215
1256
|
"scenarios": [
|
|
@@ -1222,14 +1263,14 @@ ${G.dim} Routing updated: ${r.join(", ")}${G.reset}`))}catch{}}async function Z
|
|
|
1222
1263
|
}
|
|
1223
1264
|
]
|
|
1224
1265
|
}
|
|
1225
|
-
`),
|
|
1226
|
-
`),
|
|
1227
|
-
`),
|
|
1266
|
+
`),fi;try{let o=JSON.parse(e.readFileSync(n,"utf-8"));return!Array.isArray(o.scenarios)||o.scenarios.length===0?(console.log(`${U.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${U.reset}
|
|
1267
|
+
`),fi):o.scenarios}catch(o){return console.log(`${U.yellow}Failed to parse benchmark-config.json: ${o.message}${U.reset}
|
|
1268
|
+
`),fi}}function Bh(t,e){let{scoreMessages:s,_extractToolCalls:n,_getLastAssistantText:o}=qr(),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 Rk(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,m=!1,g=setTimeout(()=>{m=!0;try{d.kill("SIGTERM")}catch{}},f);d.on("close",h=>{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:h||0,timedOut:m})}),d.stdout.resume(),d.stderr.resume()})}function Ck(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
1269
|
\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(`${
|
|
1270
|
+
`)}function Ak(t=10){let e=require("fs"),n=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(n)){console.log(`${U.yellow}No score history yet. Run a session first.${U.reset}
|
|
1271
|
+
`);return}let o=[];try{o=JSON.parse(e.readFileSync(n,"utf-8"))}catch{o=[]}if(!Array.isArray(o)||o.length===0){console.log(`${U.yellow}Score history is empty.${U.reset}
|
|
1231
1272
|
`);return}let r=o.slice(-t);console.log(`
|
|
1232
|
-
${
|
|
1233
|
-
${
|
|
1234
|
-
`);for(let c of r)console.log(` ${
|
|
1235
|
-
${
|
|
1273
|
+
${U.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${U.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?`${U.yellow}\u26A0 ${i.issues.slice(0,2).map(g=>g.substring(0,30)).join(", ")}${U.reset}`:`${U.green}\u2713${U.reset}`,m=i.score>=8?U.green:i.score>=6?U.yellow:U.red;console.log(` ${U.dim}${a}${U.reset} ${U.dim}v${c}${U.reset} ${U.dim}${l}${U.reset} ${m}${u} ${d}${U.reset} ${f}`)}console.log()}async function Ok({dryRun:t=!1,model:e,cwd:s,onProgress:n}={}){let o=Io(),r=Fh(s);if(t){console.log(`
|
|
1274
|
+
${U.bold}Scenario Benchmark \u2014 Scenarios (dry-run):${U.reset}
|
|
1275
|
+
`);for(let c of r)console.log(` ${U.cyan}${c.id.padEnd(20)}${U.reset} ${U.dim}${c.name}${U.reset} maxTurns=${c.maxTurns}`),console.log(` ${U.dim}${c.prompt.substring(0,80)}${U.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(`
|
|
1276
|
+
${U.dim}Running scenario: ${c.name}...${U.reset}`);let{messages:l,timedOut:u}=await Rk(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=Bh(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:m}=qr();m(d.score,{version:o.version,model:i,sessionName:`bench:${c.id}`,issues:d.issues})}catch{}}return Ck(a,o.version,i),a}module.exports={runBenchmark:Ek,runDiscoverBenchmark:Tk,buildSummary:Gc,buildCategoryWinners:jh,TASKS:Hc,PHASE_TASKS:Lh,ALL_TASKS:pi,scoreResult:ks,DEFAULT_MODELS:Yc,QUICK_MODELS:Ph,runScenarioBenchmark:Ok,showScoreTrend:Ak,loadScenarios:Fh,DEFAULT_SCENARIOS:fi,scoreScenario:Bh};
|