nex-code 0.4.39 → 0.4.41
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 +60 -1
- package/dist/benchmark.js +342 -338
- package/dist/nex-code.js +478 -455
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`),o=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(o){let r=parseInt(o[1].slice(0,2),16),i=parseInt(o[2].slice(0,2),16),c=parseInt(o[3].slice(0,2),16);return .299*r+.587*i+.114*c<128}}catch{}return null}function
|
|
2
|
+
var oe=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Hs=oe((P1,fy)=>{fy.exports={name:"nex-code",version:"0.4.41",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 os=oe((L1,fd)=>{"use strict";var id="\x1B[0m",ad="\x1B[1m",Ks="\x1B[2m";function ne(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function py(){if(!process.stdout.isTTY)return null;try{let{execFileSync:t}=require("child_process"),e=["import sys,os,tty,termios,select","f=open('/dev/tty','r+b',buffering=0)","fd=f.fileno()","s=termios.tcgetattr(fd)","try:"," tty.setraw(fd)"," f.write(bytes([0x1b,0x5d,0x31,0x31,0x3b,0x3f,0x1b,0x5c]))"," r=select.select([fd],[],[],0.1)[0]"," d=b''"," if r:"," while True:"," r2=select.select([fd],[],[],0.05)[0]"," if not r2:break"," c=os.read(fd,1)"," d+=c"," if d[-1:]==bytes([0x07]) or d[-2:]==bytes([0x1b,0x5c]):break"," sys.stdout.buffer.write(d)","finally:"," termios.tcsetattr(fd,termios.TCSADRAIN,s)"," f.close()"].join(`
|
|
3
|
+
`),o=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(o){let r=parseInt(o[1].slice(0,2),16),i=parseInt(o[2].slice(0,2),16),c=parseInt(o[3].slice(0,2),16);return .299*r+.587*i+.114*c<128}}catch{}return null}function cd(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function my(t){try{let n=require("fs").readFileSync(cd(),"utf8"),s=JSON.parse(n);if(s&&typeof s[t]=="boolean")return s[t]}catch{}return null}function hy(t,e){try{let n=require("fs"),s=require("path"),o=cd(),r=s.dirname(o),i={};try{i=JSON.parse(n.readFileSync(o,"utf8"))}catch{}i[t]=e;let c=Object.keys(i);c.length>50&&c.slice(0,c.length-50).forEach(l=>delete i[l]),n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(o,JSON.stringify(i),"utf8")}catch{}}function gy(){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(";"),c=parseInt(i[i.length-1],10);if(!isNaN(c))return c<8}let n=process.env.TERM_SESSION_ID||"default",s=my(n);if(s!==null)return s;let o=py(),r=o!==null?o:!0;return hy(n,r),r}var ld=gy(),ud={reset:id,bold:ad,dim:Ks,primary:ne(80,190,255),secondary:ne(60,170,190),success:ne(80,210,120),warning:ne(245,175,50),error:ne(230,80,80),muted:Ks,subtle:ne(130,130,145),tool_read:ne(80,190,255),tool_write:ne(245,165,55),tool_exec:ne(185,100,235),tool_search:ne(70,185,190),tool_git:ne(90,210,100),tool_web:ne(100,215,250),tool_sysadmin:ne(225,150,75),tool_default:ne(100,205,115),syn_keyword:ne(185,100,235),syn_string:ne(90,210,120),syn_number:ne(245,175,50),syn_comment:Ks,syn_key:ne(80,190,255),diff_add:ne(80,210,120),diff_rem:ne(230,80,80),banner_logo:ne(80,200,255),banner_name:ne(80,200,255),banner_version:Ks,banner_model:Ks,banner_yolo:ne(245,175,50),footer_sep:Ks,footer_model:ne(80,175,235),footer_branch:ne(80,210,100),footer_project:ne(130,130,145),footer_divider:ne(80,80,95),footer_mode:ne(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"},dd={reset:id,bold:ad,dim:ne(110,110,120),primary:ne(0,110,190),secondary:ne(0,125,148),success:ne(0,148,62),warning:ne(168,92,0),error:ne(188,32,32),muted:ne(110,110,120),subtle:ne(155,155,165),tool_read:ne(0,110,190),tool_write:ne(168,92,0),tool_exec:ne(128,42,188),tool_search:ne(0,122,148),tool_git:ne(0,138,62),tool_web:ne(0,112,178),tool_sysadmin:ne(168,82,0),tool_default:ne(0,138,62),syn_keyword:ne(128,42,188),syn_string:ne(0,138,62),syn_number:ne(168,92,0),syn_comment:ne(135,135,148),syn_key:ne(0,110,190),diff_add:ne(0,148,62),diff_rem:ne(188,32,32),banner_logo:ne(0,122,205),banner_name:ne(0,122,205),banner_version:ne(100,100,118),banner_model:ne(100,100,118),banner_yolo:ne(168,62,0),footer_sep:ne(168,168,178),footer_model:ne(0,102,175),footer_branch:ne(0,138,62),footer_project:ne(135,135,148),footer_divider:ne(168,168,178),footer_mode:ne(148,88,0),white:ne(40,40,52),red:ne(188,32,32),green:ne(0,148,62),yellow:ne(168,92,0),blue:ne(0,110,190),magenta:ne(128,42,188),cyan:ne(0,125,148),gray:ne(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:ne(0,158,182),brightMagenta:ne(158,52,208),brightBlue:ne(0,112,208)},$y=ld?ud:dd;fd.exports={T:$y,isDark:ld,DARK:ud,LIGHT:dd}});var Gs=oe((I1,md)=>{var{T:le}=os(),ei=5,Ys=(()=>{let t=[];for(let e=0;e<ei;e++)t.push(e);for(let e=ei-2;e>=1;e--)t.push(e);return t})(),pd=["\u273D","\u2726","\u2727","\u2726"],Va=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Ys[this.frame%Ys.length],n="";for(let o=0;o<ei;o++)n+=o===e?`${le.cyan}\u25CF${le.reset}`:" ";let s="";if(this.startTime){let o=Math.floor((Date.now()-this.startTime)/1e3);if(o>=60){let r=Math.floor(o/60),i=o%60;s=` ${le.dim}${r}m ${String(i).padStart(2,"0")}s${le.reset}`}else o>=1&&(s=` ${le.dim}${o}s${le.reset}`)}process.stderr.write(`\x1B[2K\r${n} ${le.dim}${this.text}${le.reset}${s}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),100))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},Ja=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),s=e%60;return n>0?`${n}m ${String(s).padStart(2,"0")}s`:`${s}s`}_render(){if(this._stopped)return;let e=Ys[this.frame%Ys.length],n=`${le.cyan}\u25CF${le.reset}`,s=this._formatElapsed(),o=s?` ${le.dim}${s}${le.reset}`:"",r=process.stderr.columns||80,i="";for(let c=0;c<this.labels.length;c++){let l,u;switch(this.statuses[c]){case"done":l=`${le.green}\u2713${le.reset}`,u=le.dim;break;case"error":l=`${le.red}\u2717${le.reset}`,u=le.dim;break;case"retry":l=`${le.yellow}\u21BB${le.reset}`,u=le.yellow;break;default:l=c===e?n:" ",u=""}let d=c===this.labels.length-1?o:"",f=r-4-(d?s.length+1:0),p=this.labels[c].length>f?this.labels[c].substring(0,Math.max(10,f-3))+"...":this.labels[c];i+=`\x1B[2K ${l} ${u}${p}${le.reset}${d}
|
|
4
4
|
`}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let n=0;n<this.lineCount;n++)e+=`
|
|
5
5
|
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,n){e>=0&&e<this.statuses.length&&(this.statuses[e]=n)}stop(e={}){if(this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),!e.silent)this._renderFinal();else{let n="";for(let s=0;s<this.lineCount;s++)n+=`\x1B[2K
|
|
6
6
|
`;this.lineCount>0&&(n+=`\x1B[${this.lineCount}A`),process.stderr.write(n)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),n=e?` ${le.dim}${e}${le.reset}`:"",s=process.stderr.columns||80,o="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${le.green}\u2713${le.reset}`;break;case"error":i=`${le.red}\u2717${le.reset}`;break;case"retry":i=`${le.yellow}\u21BB${le.reset}`;break;default:i=`${le.yellow}\u25CB${le.reset}`}let c=r===this.labels.length-1?n:"",l=s-4-(c?e.length+1:0),u=this.labels[r].length>l?this.labels[r].substring(0,Math.max(10,l-3))+"...":this.labels[r];o+=`\x1B[2K ${i} ${le.dim}${u}${le.reset}${c}
|
|
7
|
-
`}process.stderr.write(o)}},
|
|
8
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=
|
|
7
|
+
`}process.stderr.write(o)}},Zr={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Qr={done:le.green,in_progress:le.cyan,pending:le.dim,failed:le.red},qn=null,Za=class{constructor(e,n){this.name=e,this.tasks=n.map(s=>({id:s.id,description:s.description,status:s.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),s=e%60;return n>0?`${n}m ${String(s).padStart(2,"0")}s`:`${s}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=pd[this.frame%pd.length],n=this._formatElapsed(),s=this._formatTokens(),o=[n,s?`\u2193 ${s} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${le.dim}(${o})${le.reset}`:"",i=`\x1B[2K${le.cyan}${e}${le.reset} ${this.name}\u2026${r}
|
|
8
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=Zr[l.status]||Zr.pending,f=Qr[l.status]||Qr.pending,p=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${le.dim}${u}${le.reset} ${f}${d}${le.reset} ${p}
|
|
9
9
|
`}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let n=0;n<this.lineCount;n++)e+=`
|
|
10
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),
|
|
10
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),qn=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,qn===this&&(qn=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let n=0;n<this.lineCount;n++)e+=`\x1B[2K
|
|
11
11
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let n=0;n<this.lineCount;n++)e+=`
|
|
12
12
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,n){let s=this.tasks.find(o=>o.id===e);s&&(s.status=n)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),n=this.tasks.filter(c=>c.status==="done").length,s=this.tasks.filter(c=>c.status==="failed").length,o=this.tasks.length,r=s>0?`${n}/${o} done, ${s} failed`:`${n}/${o} done`,i=`\x1B[2K${le.green}\u2714${le.reset} ${this.name} ${le.dim}(${e} \xB7 ${r})${le.reset}
|
|
13
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=
|
|
14
|
-
`}process.stderr.write(i)}},
|
|
13
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=Zr[l.status]||Zr.pending,f=Qr[l.status]||Qr.pending,p=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${le.dim}${u}${le.reset} ${f}${d}${le.reset} ${le.dim}${p}${le.reset}
|
|
14
|
+
`}process.stderr.write(i)}},Qa=class{constructor(e,n){this.toolName=e,this.message=n||`Running ${e}...`,this.count=0,this.total=null,this.detail="",this.frame=0,this.interval=null,this.startTime=null,this._stopped=!1}_render(){if(this._stopped||!process.stderr.isTTY)return;let e=Ys[this.frame%Ys.length],n="";for(let r=0;r<ei;r++)n+=r===e?`${le.cyan}\u25CF${le.reset}`:" ";let s=this.message;this.count>0&&(s+=` ${le.cyan}${this.count}${le.reset}`,this.total&&(s+=`/${this.total}`),this.detail&&(s+=` ${le.dim}${this.detail}${le.reset}`));let o="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(o=` ${le.dim}${r}s${le.reset}`)}process.stderr.write(`\x1B[2K\r${n} ${le.dim}${s}${le.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 yy(t){qn=t}function wy(){return qn}function by(){qn&&(qn.stop(),qn=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}md.exports={C:le,Spinner:Va,MultiProgress:Ja,TaskProgress:Za,ToolProgress:Qa,setActiveTaskProgress:yy,getActiveTaskProgress:wy,cleanupTerminal:by}});var ec=oe((j1,yd)=>{"use strict";var me={kw:"\x1B[34m",str:"\x1B[32m",cmt:"\x1B[90m",num:"\x1B[33m",type:"\x1B[36m",punct:"\x1B[35m",reset:"\x1B[0m"},hd={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"])},_y={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 gd(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return _y[e]||null}function xy(t){return t.replace(/"([^"\\]|\\.)*"\s*:/g,e=>me.type+e+me.reset).replace(/"([^"\\]|\\.)*"/g,e=>me.str+e+me.reset).replace(/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,e=>me.num+e+me.reset).replace(/\b(true|false|null)\b/g,e=>me.kw+e+me.reset)}function vy(t){return/<!--/.test(t)?t.replace(/<!--[\s\S]*?(?:-->|$)/g,e=>me.cmt+e+me.reset):t.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(e,n,s)=>n+me.type+s+me.reset).replace(/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(e,n)=>" "+me.kw+n+me.reset+"=").replace(/"([^"]*)"/g,e=>me.str+e+me.reset)}function Sy(t){return t.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,e=>me.cmt+e+me.reset).replace(/#[0-9a-fA-F]{3,8}\b/g,e=>me.num+e+me.reset).replace(/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(e,n,s)=>me.num+n+me.reset+s).replace(/([a-z][a-z-]*)(\s*:)/g,(e,n,s)=>me.type+n+me.reset+s).replace(/"[^"]*"|'[^']*'/g,e=>me.str+e+me.reset)}function $d(t,e,n){if(e==="json")return xy(t);if(e==="html"||e==="xml")return vy(t);if(e==="css")return Sy(t);if(e==="md")return t;let s=hd[e]||hd.js,o="",r=0;if(n.inBlockComment){let i=t.indexOf("*/");if(i===-1)return me.cmt+t+me.reset;if(o+=me.cmt+t.slice(0,i+2)+me.reset,n.inBlockComment=!1,r=i+2,r>=t.length)return o}if(n.inString==="`"){let i=t.indexOf("`");if(i===-1)return me.str+t+me.reset;if(o+=me.str+t.slice(0,i+1)+me.reset,n.inString=null,r=i+1,r>=t.length)return o}for(;r<t.length;){let i=t[r];if(!n.inString&&i==="/"&&t[r+1]==="*"){let c=t.indexOf("*/",r+2);if(c===-1)return o+=me.cmt+t.slice(r)+me.reset,n.inBlockComment=!0,o;o+=me.cmt+t.slice(r,c+2)+me.reset,r=c+2;continue}if(!n.inString&&((e==="js"||e==="go"||e==="rs"||e==="java")&&i==="/"&&t[r+1]==="/"||(e==="py"||e==="sh")&&i==="#"))return o+=me.cmt+t.slice(r)+me.reset,o;if(!n.inString&&(i==='"'||i==="'"||i==="`")){n.inString=i,o+=me.str+i,r++;continue}if(n.inString){if(i==="\\"&&r+1<t.length){o+=i+t[r+1],r+=2;continue}if(i===n.inString){o+=i+me.reset,n.inString=null,r++;continue}o+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let c="";for(;r<t.length&&/[0-9a-fA-F_.xXoObBeE+-]/.test(t[r])&&!(c.length>0&&/[eE]/.test(t[r-1])&&/[^+-]/.test(i));)c+=t[r++];o+=me.num+c+me.reset;continue}if(i==="@"&&(e==="js"||e==="java"||e==="py")){let c="@";for(r++;r<t.length&&/[a-zA-Z0-9_$.]/.test(t[r]);)c+=t[r++];o+=me.punct+c+me.reset;continue}if(/[a-zA-Z_$]/.test(i)){let c="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)c+=t[r++];s.has(c)?o+=me.kw+c+me.reset:/^[A-Z][A-Za-z0-9]*$/.test(c)&&e!=="sh"?o+=me.type+c+me.reset:o+=c;continue}o+=i,r++}return n.inString&&n.inString!=="`"&&(o+=me.reset,n.inString=null),o}function ky(t,e){let n=gd(e);if(!n)return t.split(`
|
|
15
15
|
`);let s=t.split(`
|
|
16
|
-
`),o={inString:null,inBlockComment:!1};return s.map(r
|
|
16
|
+
`),o={inString:null,inBlockComment:!1};return s.map(r=>$d(r,n,o))}function Ey(t,e){return e?$d(t,e,{inString:null,inBlockComment:!1}):t}yd.exports={detectLang:gd,highlightLine:Ey,highlightLines:ky}});var _d=oe((D1,bd)=>{var{T:L}=os(),gt=L,Ty={read_file:L.tool_read,list_directory:L.tool_read,write_file:L.tool_write,edit_file:L.tool_write,patch_file:L.tool_write,bash:L.tool_exec,grep:L.tool_search,search_files:L.tool_search,glob:L.tool_search,git_commit:L.tool_git,git_push:L.tool_git,git_pull:L.tool_git,git_status:L.tool_git,git_diff:L.tool_git,git_log:L.tool_git,git_branch:L.tool_git,git_stash:L.tool_git,web_fetch:L.tool_web,web_search:L.tool_web,sysadmin:L.tool_sysadmin,ssh_exec:L.tool_sysadmin,ssh_upload:L.tool_sysadmin,ssh_download:L.tool_sysadmin,deploy:L.tool_sysadmin},tc={read_file:"Read",write_file:"Write",edit_file:"Edit",patch_file:"Edit",list_directory:"List",bash:"Bash",grep:"Grep",search_files:"Search",glob:"Glob",web_fetch:"WebFetch",web_search:"WebSearch",git_status:"Bash",git_diff:"Bash",git_log:"Bash",git_commit:"Bash",git_push:"Bash",git_pull:"Bash",git_branch:"Bash",git_stash:"Bash",task_list:"TaskList",spawn_agents:"Agent",ask_user:"AskUser",switch_model:"SwitchModel",gh_run_list:"Bash",gh_run_view:"Bash",gh_workflow_trigger:"Bash",browser_open:"Browser",browser_screenshot:"Browser",browser_click:"Browser",browser_fill:"Browser",ssh_exec:"Bash",ssh_upload:"Upload",ssh_download:"Download",service_manage:"Bash",service_logs:"Bash",container_list:"Bash",container_logs:"Bash",container_exec:"Bash",brain_write:"Write",deploy:"Bash",frontend_recon:"Search"};function ti(t,e=!1,n=null){if(e)return`${L.error}\u23FA${L.reset}`;let s=Ty[t]||L.tool_default;return n==="blink"?`${s}\x1B[5m\u23FA\x1B[25m${L.reset}`:`${s}${n!==null?n:"\u23FA"}${L.reset}`}function Ry(t,e,n=!1,s=null){let o=(t||[]).filter(l=>l&&l.canExecute!==!1);if(o.length===0)return`${ti("",n,s)} Step ${e}`;if(o.length===1){let l=o[0],u=l.args||{},d=tc[l.fnName]||l.fnName.replace(/_/g," "),f="";u.path?f=u.path:u.command?f=String(u.command).substring(0,80):u.query?f=String(u.query).substring(0,60):u.pattern?f=String(u.pattern).substring(0,60):u.url&&(f=String(u.url).substring(0,60));let p=f?`(${gt.dim}${f}${gt.reset})`:"";return`${ti(l.fnName,n,s)} ${gt.bold}${d}${gt.reset}${p}`}let r=o[0].fnName,i=[...new Set(o.map(l=>tc[l.fnName]||l.fnName.replace(/_/g," ")))],c=i.length<=3?i.join(", "):`${o.length} tools`;return`${ti(r,n,s)} ${gt.bold}${c}${gt.reset}`}function Cy(t,e){let n;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":n=e.path||"";break;case"bash":case"ssh_exec":n=(e.command||"").substring(0,80);break;case"grep":case"search_files":n=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":n=e.pattern||"";break;case"web_fetch":n=(e.url||"").substring(0,60);break;case"web_search":n=(e.query||"").substring(0,50);break;default:n=JSON.stringify(e).substring(0,80)}let s=tc[t]||t.replace(/_/g," "),o=n?`(${gt.dim}${n}${gt.reset})`:"";return`${ti(t)} ${gt.bold}${s}${gt.reset}${o}`}function Ay(t,e=8){let n=t.split(`
|
|
17
17
|
`),s=n.slice(0,e),o=n.length-e,r=`${L.muted} \u23BF ${L.reset}`,i=" ",c=s.map((l,u)=>`${u===0?r:i}${L.success}${l}${L.reset}`).join(`
|
|
18
18
|
`);return o>0&&(c+=`
|
|
19
|
-
${L.subtle} \u2026 +${o} lines${L.reset}`),c}var
|
|
19
|
+
${L.subtle} \u2026 +${o} lines${L.reset}`),c}var ni=["Sampling","Decoding","Attending","Inferring","Generating","Routing","Embedding","Reasoning","Tokenizing","Predicting"],wd=Math.floor(Math.random()*ni.length),nc=null;function Oy(t){nc=t}function Ny(){let t=ni[wd%ni.length];wd++;let e=nc?` \xB7 ${nc}`:"";return`${t}${e}`}function My(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading ${e.path||"file"}`;case"list_directory":return`Listing ${e.path||"."}`;case"search_files":return`Searching ${e.pattern||"..."}`;case"glob":return`Searching ${e.pattern||"..."}`;case"grep":return`Searching ${e.pattern||"..."}`;case"web_fetch":return`Fetching ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Checking git status";case"git_diff":return`Diffing${e.file?` ${e.file}`:""}`;case"git_log":return`Reading git log${e.file?` (${e.file})`:""}`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;case"sysadmin":{let n=e.server&&e.server!=="local"?` [${e.server}]`:"";switch(e.action){case"audit":return`Sysadmin${n}: full audit...`;case"disk_usage":return`Sysadmin${n}: disk usage ${e.path||"/"}...`;case"process_list":return`Sysadmin${n}: top processes (${e.sort_by||"cpu"})...`;case"network_status":return`Sysadmin${n}: network status...`;case"ssl_check":return`Sysadmin${n}: SSL check ${e.domain||e.cert_path||""}...`;case"log_tail":return`Sysadmin${n}: tail ${e.path||"log"}...`;case"find_large":return`Sysadmin${n}: find large files in ${e.path||"/"}...`;case"service":return`Sysadmin${n}: service ${e.service_action||""} ${e.service_name||""}...`;case"kill_process":return`Sysadmin${n}: kill PID ${e.pid||e.process_name||"?"}...`;case"journalctl":return`Sysadmin${n}: journal ${e.unit?`[${e.unit}]`:""}${e.since?` since ${e.since}`:""}...`;case"package":return`Sysadmin${n}: package ${e.package_action||""} ${(e.packages||[]).join(" ")}...`;case"firewall":return`Sysadmin${n}: firewall ${e.firewall_action||""}...`;case"user_manage":return`Sysadmin${n}: user ${e.user_action||""} ${e.user||""}...`;case"cron":return`Sysadmin${n}: cron ${e.cron_action||""}...`;default:return`Sysadmin${n}: ${e.action}...`}}default:return`Running: ${t}`}}function Py(t,e,n,s){let o=String(n||"");if(s){let c=o.split(`
|
|
20
20
|
`)[0];if(c.startsWith("BLOCKED:")){let f=c.replace(/^BLOCKED:\s*/,"").replace(/\s*—.*$/,"").replace(/\s*\(hard cap:.*?\)/,"").trim().substring(0,70);return` ${L.muted}\u23BF blocked: ${f}${L.reset}`}let l=c.replace(/^ERROR:\s*/i,"").substring(0,80),u=o.match(/\nHINT: (.+)/),d=u?`
|
|
21
21
|
${L.muted}${u[1].substring(0,100)}${L.reset}`:"";return` ${L.error}\u23BF ${l}${L.reset}${d}`}let r;switch(t){case"read_file":{let l=o.split(`
|
|
22
22
|
`).filter(Boolean).filter(h=>!/^File:\s/.test(h)&&!/^\[LARGE FILE:/.test(h)),u=l.length,d=l[l.length-1],f=d?parseInt(d.match(/^(\d+):/)?.[1]||"0"):0,p=e.line_start||e.line_end,g=e.path?require("path").basename(e.path):null,m=g?` ${L.muted}from ${g}${L.reset}`:"";p&&f>u?r=`Read lines ${e.line_start||1}\u2013${f}${m}`:r=`Read ${u} line${u!==1?"s":""}${m}`;break}case"write_file":{let l=(e.content||"").split(`
|
|
23
|
-
`).length,u=e.path?require("path").basename(e.path):null,d=u?`Wrote ${u} \xB7 ${l} line${l!==1?"s":""}`:`Wrote ${l} line${l!==1?"s":""}`,{highlightLines:f}=
|
|
23
|
+
`).length,u=e.path?require("path").basename(e.path):null,d=u?`Wrote ${u} \xB7 ${l} line${l!==1?"s":""}`:`Wrote ${l} line${l!==1?"s":""}`,{highlightLines:f}=ec(),p=f(e.content||"",e.path||null),g=40,m=8;if(l<=g){let h=p.map(y=>` ${y}`).join(`
|
|
24
24
|
`);r=`${d}
|
|
25
25
|
${h}`}else{let h=p.slice(0,m).map(y=>` ${y}`).join(`
|
|
26
26
|
`);r=`${d}
|
|
27
27
|
${h}
|
|
28
28
|
${L.subtle}\u2026 +${l-m} lines${L.reset}`}break}case"edit_file":{let c=(e.old_text||"").split(`
|
|
29
29
|
`),l=(e.new_text||"").split(`
|
|
30
|
-
`),u=c.length,d=l.length,f=e.path?require("path").basename(e.path):null,p=f?` ${L.muted}${f}${L.reset}`:"",g=c.find(C=>C.trim()),m=l.find(C=>C.trim()),{highlightLine:h,detectLang:y}=
|
|
31
|
-
`+
|
|
30
|
+
`),u=c.length,d=l.length,f=e.path?require("path").basename(e.path):null,p=f?` ${L.muted}${f}${L.reset}`:"",g=c.find(C=>C.trim()),m=l.find(C=>C.trim()),{highlightLine:h,detectLang:y}=ec(),b=y(e.path||null),S=[];g&&S.push(` ${L.diff_rem}- ${L.reset}${h(g.trimEnd().substring(0,72),b)}${L.reset}`),m&&S.push(` ${L.diff_add}+ ${L.reset}${h(m.trimEnd().substring(0,72),b)}${L.reset}`),r=`${L.diff_rem}\u2212${u}${L.reset} ${L.diff_add}+${d}${L.reset}${p}`+(S.length>0?`
|
|
31
|
+
`+S.join(`
|
|
32
32
|
`):"");break}case"patch_file":{let c=e.patches||[],l=c.reduce((d,f)=>d+(f.old_text||"").split(`
|
|
33
33
|
`).length,0),u=c.reduce((d,f)=>d+(f.new_text||"").split(`
|
|
34
34
|
`).length,0);r=`${L.reset}${c.length} patch${c.length!==1?"es":""} ${L.diff_rem}\u2212${l}${L.reset} ${L.diff_add}+${u}${L.reset}`;break}case"bash":{let l=o.match(/^EXIT (\d+)/),u=o.split(`
|
|
35
|
-
`).filter(p=>p&&!p.startsWith("EXIT ")&&!p.startsWith("HINT:")&&p.trim()),d=l?l[1]==="0"?`${L.success}\u2713${L.reset}`:`${L.error}\u2717 Exit ${l[1]}${L.reset}`:`${L.success}\u2713${L.reset}`,f=o.match(/\nHINT: (.+)/);if(f)r=`${d} ${L.muted}\u2014 ${f[1].substring(0,100)}${L.reset}`;else if(u.length===0)r=d;else{let p=l&&l[1]!=="0",g=p?u.slice(-3):u.slice(0,3),m=u.length-3,h=g.map((y,
|
|
36
|
-
`)}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r=`No matches${e.pattern?` ${L.muted}"${String(e.pattern).substring(0,40)}"${L.reset}`:""}`;else{let m=function(
|
|
37
|
-
`).filter(Boolean),u=l.length,f=new Set(l.map(
|
|
38
|
-
${m(
|
|
35
|
+
`).filter(p=>p&&!p.startsWith("EXIT ")&&!p.startsWith("HINT:")&&p.trim()),d=l?l[1]==="0"?`${L.success}\u2713${L.reset}`:`${L.error}\u2717 Exit ${l[1]}${L.reset}`:`${L.success}\u2713${L.reset}`,f=o.match(/\nHINT: (.+)/);if(f)r=`${d} ${L.muted}\u2014 ${f[1].substring(0,100)}${L.reset}`;else if(u.length===0)r=d;else{let p=l&&l[1]!=="0",g=p?u.slice(-3):u.slice(0,3),m=u.length-3,h=g.map((y,b)=>b===0?`${d} ${L.muted}${y.substring(0,120)}${L.reset}`:` ${L.muted}${y.substring(0,120)}${L.reset}`);if(m>0){let y=p?` ${L.subtle}${m} lines above\u2026${L.reset}`:` ${L.subtle}\u2026 +${m} lines${L.reset}`;p?h.unshift(y):h.push(y)}r=h.join(`
|
|
36
|
+
`)}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r=`No matches${e.pattern?` ${L.muted}"${String(e.pattern).substring(0,40)}"${L.reset}`:""}`;else{let m=function(b){let S=b.indexOf(":");if(S===-1)return`${L.muted}${b.substring(0,90)}${L.reset}`;let C=b.substring(0,S),k=b.substring(S+1),x=k.match(/^(\d+)[:-](.*)/s),E=x?`:${x[1]}`:"",B=(x?x[2]:k).trim(),q=`${L.subtle}${c.basename(C)}${E}${L.reset}`,re=`${L.muted}${B.substring(0,80)}${B.length>80?"\u2026":""}${L.reset}`;return`${q} ${re}`};var i=m;let c=require("path"),l=o.split(`
|
|
37
|
+
`).filter(Boolean),u=l.length,f=new Set(l.map(b=>b.split(":")[0]).filter(Boolean)).size,p=e.pattern?` ${L.muted}"${String(e.pattern).substring(0,40)}"${L.reset}`:"",g=f>1?`${u} match${u!==1?"es":""} in ${f} files${p}`:`${u} match${u!==1?"es":""}${p}`,h=l.slice(0,3).map((b,S)=>S===0?`${g}
|
|
38
|
+
${m(b)}`:` ${m(b)}`),y=l.length-3;y>0&&h.push(` ${L.subtle}\u2026 +${y} lines${L.reset}`),r=h.join(`
|
|
39
39
|
`)}break}case"glob":{let c=e.pattern?` ${L.muted}${String(e.pattern).substring(0,50)}${L.reset}`:"";if(o==="(no matches)")r=`No files found${c}`;else{let l=require("path"),u=o.split(`
|
|
40
40
|
`).filter(Boolean),d=u.length,f=u.slice(0,5).map(m=>l.basename(m)),p=d-f.length,g=f.join(", ")+(p>0?`, +${p} more`:"");r=`${d} file${d!==1?"s":""}${c} \u2014 ${L.muted}${g}${L.reset}`}break}case"list_directory":{if(o==="(empty)")r="0 entries";else{let c=o.split(`
|
|
41
41
|
`).filter(Boolean),l=c.length,u=c.slice(0,6).join(", "),d=l-6;r=d>0?`${l} entries \u2014 ${L.muted}${u}, +${d} more${L.reset}`:`${l} entr${l!==1?"ies":"y"} \u2014 ${L.muted}${u}${L.reset}`}break}case"git_status":{let c=o.match(/Branch:\s*(\S+)/),l=o.split(`
|
|
@@ -47,87 +47,87 @@ ${h}
|
|
|
47
47
|
`)[0].replace(/^\d+\.\s*/,"").trim():null,d=u?` ${L.muted}\u2014 ${u.substring(0,70)}${L.reset}`:"";r=`${l} result${l!==1?"s":""}${d}`;break}case"task_list":r="Done";break;case"spawn_agents":{let c=(o.match(/✓ Agent/g)||[]).length,l=(o.match(/✗ Agent/g)||[]).length;r=l>0?`${c} done, ${l} failed`:`${c} agent${c!==1?"s":""} done`;break}case"switch_model":{let c=o.match(/Switched to (.+)/);r=c?`\u2192 ${c[1]}`:"Done";break}case"ssh_exec":{let l=o.startsWith("EXIT ")||o.startsWith("Command failed"),u=o.split(`
|
|
48
48
|
`).filter(f=>f.trim()&&!f.startsWith("EXIT ")),d=l?`${L.error}\u2717${L.reset}`:`${L.success}\u2713${L.reset}`;if(u.length===0)r=d;else{if(u.length>2&&u.every(h=>/^\[/.test(h.trim()))){r=`${d} ${u.length} log lines`;break}let p=l?u.slice(-3):u.slice(0,3),g=u.length-3,m=p.map((h,y)=>y===0?`${d} ${L.muted}${h.substring(0,120)}${L.reset}`:` ${L.muted}${h.substring(0,120)}${L.reset}`);if(g>0){let h=l?` ${L.subtle}${g} lines above\u2026${L.reset}`:` ${L.subtle}\u2026 +${g} lines${L.reset}`;l?m.unshift(h):m.push(h)}r=m.join(`
|
|
49
49
|
`)}break}default:{let c=o.split(`
|
|
50
|
-
`).filter(l=>l.trim()&&!l.startsWith("EXIT ")&&!l.startsWith("HINT:"));if(c.length>0){let l=c[0].trim().substring(0,90),u=c.length>1?` ${L.subtle}\u2026 +${c.length-1} lines${L.reset}`:"";r=`${L.muted}${l}${L.reset}${u}`}else r="Done"}}return` ${L.muted}\u23BF ${r}${L.reset}`}function
|
|
51
|
-
${L.success}\u25C6${
|
|
50
|
+
`).filter(l=>l.trim()&&!l.startsWith("EXIT ")&&!l.startsWith("HINT:"));if(c.length>0){let l=c[0].trim().substring(0,90),u=c.length>1?` ${L.subtle}\u2026 +${c.length-1} lines${L.reset}`:"";r=`${L.muted}${l}${L.reset}${u}`}else r="Done"}}return` ${L.muted}\u23BF ${r}${L.reset}`}function Ly(t,e,n,s,o,r){let i=Math.round(s/1e3),c=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,l=`
|
|
51
|
+
${L.success}\u25C6${gt.reset} ${gt.bold}${t}${gt.reset}`;return l+=`${gt.dim} \xB7 ${c}`,r.size>0&&(l+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),l+=gt.reset,l}bd.exports={C:gt,formatToolCall:Cy,formatResult:Ay,getToolSpinnerText:My,formatToolSummary:Py,formatSectionHeader:Ry,formatMilestone:Ly,getThinkingVerb:Ny,setActiveModelForSpinner:Oy,THINKING_VERBS:ni}});var Ke=oe((q1,vd)=>{var{T:rs}=os(),sc=rs,xd=["01100110","01111110","01111110","01011010","01111110","00111100"];function Iy(t,e){let n=[];for(let s=0;s<t.length;s+=2){let o="";for(let r=0;r<t[0].length;r++){let i=t[s][r]==="1",c=s+1<t.length&&t[s+1][r]==="1";i&&c?o+=`${e}\u2588\x1B[0m`:i&&!c?o+=`${e}\u2580\x1B[0m`:!i&&c?o+=`${e}\u2584\x1B[0m`:o+=" "}n.push(o)}return n}function jy(t,e,n={}){let s=sc.bold,o=sc.reset,r=Iy(xd,rs.banner_logo),i=n.yolo?` ${s}${rs.banner_yolo}\u26A1 YOLO${o}`:"",c=Hs().version,l=[` ${rs.banner_name}${s}nex-code${o} ${rs.banner_version}v${c}${o}`,` ${rs.banner_model}${t}${o} ${rs.muted}\xB7 /help${o}${i}`,""],u=Math.max(r.length,l.length),d=Math.floor((u-r.length)/2),f=Math.floor((u-l.length)/2),p=xd[0].length,g=[];for(let m=0;m<u;m++){let h=r[m-d]??" ".repeat(p),y=l[m-f]??"";g.push(h+y)}console.log(`
|
|
52
52
|
`+g.join(`
|
|
53
53
|
`)+`
|
|
54
|
-
`)}var{Spinner:
|
|
55
|
-
`){u(o);return}if(p==="\x1B[A"){o=(o-1+n.length)%n.length,c();return}if(p==="\x1B[B"){o=(o+1)%n.length,c();return}let g=p.toLowerCase().trim();if(g==="y"){l(!0);return}if(g==="n"){l(!1);return}if(g==="a"&&e.toolName){
|
|
56
|
-
`);this.buffer=n.pop()||"";for(let s of n){let o=this.parseLine(s);if(o?.done)return o}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},ti=class extends Xs{constructor(e,n={}){super(e,n),this.toolCallsMap={}}parseLine(e){let n=e.trim();if(!n||!n.startsWith("data: "))return{done:!1};let s=n.slice(6);if(s==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(s)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let c=i.index??0;this.toolCallsMap[c]||(this.toolCallsMap[c]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[c].id=i.id),i.function?.name&&(this.toolCallsMap[c].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[c].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}}))}}},ni=class extends zs{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:n,tools:s,maxTokens:o,temperature:r,stream:i}){let c={model:e,messages:n,max_tokens:o,temperature:r};return i&&(c.stream=!0),s&&s.length>0&&(c.tools=s),c}normalizeResponse(e){let n=e.choices?.[0]?.message||{},s=(n.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:n.content||"",tool_calls:s}}createStreamParser(e,n={}){return new ti(e,n)}},si=class extends Xs{constructor(e,n={}){super(e,n),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let n=e.trim();if(!n.startsWith("data: "))return{done:!1};let s=n.slice(6),o;try{o=JSON.parse(s)}catch{return{done:!1}}switch(o.type){case"content_block_start":{let r=o.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=o.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let n={};if(e.inputJson)try{n=JSON.parse(e.inputJson)}catch{n=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:n}}})}}},oi=class extends zs{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:n,tools:s,maxTokens:o,temperature:r,stream:i,extra:c}){let l={model:e,messages:n,max_tokens:o,temperature:r};return i&&(l.stream=!0),c?.system&&(l.system=c.system),s&&s.length>0&&(l.tools=s),l}formatTools(e){return!e||e.length===0?[]:e.map(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let n="",s=[];for(let o of e.content||[])o.type==="text"?n+=o.text:o.type==="tool_use"&&s.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:n,tool_calls:s}}createStreamParser(e,n={}){return new si(e,n)}},ri=class extends Xs{constructor(e,n={}){super(e,n),this.toolCalls=[],this.onThinkingToken=n.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let n;try{n=JSON.parse(e)}catch{return{done:!1}}return n.message?.thinking&&this.onThinkingToken(n.message.thinking),n.message?.content&&(this.onToken(n.message.content),this.content+=n.message.content),n.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(n.message.tool_calls)),n.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,n)=>({id:e.id||`ollama-${Date.now()}-${n}`,function:{name:e.function?.name||e.name||"unknown",arguments:e.function?.arguments||e.arguments||{}}}))}}},ii=class extends zs{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:n,tools:s,maxTokens:o,temperature:r,stream:i,extra:c}){let l={model:e,messages:n,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:c?.repeat_penalty??1.05}};return s&&s.length>0&&(l.tools=s),l}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:(n.tool_calls||[]).map((s,o)=>({id:s.id||`ollama-${Date.now()}-${o}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}}createStreamParser(e,n={}){return new ri(e,n)}},Qy=new ni,ew=new oi,tw=new ii;vd.exports={WireProtocol:zs,StreamParser:Xs,OpenAICompatibleProtocol:ni,AnthropicProtocol:oi,OllamaChatProtocol:ii,OpenAIStreamParser:ti,AnthropicStreamParser:si,OllamaStreamParser:ri,openaiProtocol:Qy,anthropicProtocol:ew,ollamaProtocol:tw}});var Ed=ne((g1,kd)=>{var ai=require("axios"),nw=require("http"),sw=require("https"),{BaseProvider:ow,readStreamErrorBody:rw}=Gs(),{ollamaProtocol:is}=Vs(),ci=new nw.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),li=new sw.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Sd={"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}},ac=class extends ow{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Sd,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){ai.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:ci,httpsAgent:li}).then(e=>{let n=e.data?.models||[];for(let s of n){let o=(s.name||s.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:s.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await ai.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:ci,httpsAgent:li})).data?.models||[];for(let s of n){let o=(s.name||s.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:s.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let s=[],o=[];for(let i of n.content)i.type==="text"?s.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:s.join(`
|
|
57
|
-
`)};return o.length>0&&(r.images=o),r}return n})}async chat(e,n,s={}){await this.discoverModels();let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,c=
|
|
58
|
-
|
|
59
|
-
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){s.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,s);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}s.push(r)}}for(let o=s.length-1;o>0;o--)s[o].role==="user"&&s[o-1].role==="user"&&s.splice(o,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:s,system:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let s=[];if(e.content&&s.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)s.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:s.length>0?s:[{type:"text",text:""}]}}if(e.role==="tool"){let s=n[n.length-1],o={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return s&&s.role==="user"&&Array.isArray(s.content)&&s.content[0]?.type==="tool_result"?(s.content.push(o),null):{role:"user",content:[o]}}if(Array.isArray(e.content)){let s=[];for(let o of e.content)o.type==="text"?s.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&s.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:s}}return{role:"user",content:e.content}}formatTools(e){return Dn.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),c=s.maxTokens||i?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d=this.formatTools(n),f=Dn.buildRequestBody({model:r,messages:l,tools:d,maxTokens:c,temperature:s.temperature??this.temperature,stream:!1,extra:{system:u}}),p;try{p=await Od.post(`${this.baseUrl}${Dn.getEndpoint()}`,f,{timeout:s.timeout||this.timeout,headers:this._getHeaders()})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let m=g.response?.status?` [HTTP ${g.response.status}]`:"",h=g.response?.data?.error?.message||g.response?.data?.error||g.message;throw new Error(`API Error${m}: ${h}`)}return Dn.normalizeResponse(p.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),c=s.maxTokens||i?.maxTokens||8192,l=s.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f=this.formatTools(n),p=Dn.buildRequestBody({model:r,messages:u,tools:f,maxTokens:c,temperature:s.temperature??this.temperature,stream:!0,extra:{system:d}}),g;try{g=await Od.post(`${this.baseUrl}${Dn.getEndpoint()}`,p,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let y=h.response?.status?` [HTTP ${h.response.status}]`:"",w=await lw(h,x=>x?.error?.message||x?.error);throw new Error(`API Error${y}: ${w}`)}let m=Dn.createStreamParser(l);return new Promise((h,y)=>{s.signal&&s.signal.addEventListener("abort",()=>{g.data.destroy(),y(new DOMException("The operation was aborted","AbortError"))},{once:!0}),g.data.on("data",w=>{let{done:x,result:C}=m.feed(w.toString());x&&h(C)}),g.data.on("error",w=>{s.signal?.aborted||y(new Error(`Stream error: ${w.message}`))}),g.data.on("end",()=>{h(m.flush())})})}normalizeResponse(e){return Dn.normalizeResponse(e)}};Md.exports={AnthropicProvider:lc,ANTHROPIC_MODELS:Nd}});var Dd=ne((w1,jd)=>{var Ld=require("axios"),{BaseProvider:dw,readStreamErrorBody:fw}=Gs(),{openaiProtocol:cs}=Vs(),Id={"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}},uc=class extends dw{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Id,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let s of e){if(this._messageFormatCache.has(s)){n.push(this._messageFormatCache.get(s));continue}let o=this._getMessageCacheKey(s);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(s,i),n.push(i);continue}let r=this._formatSingleMessage(s);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(s,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let s of e.content)if(s.type==="text")n.push({type:"text",text:s.text??""});else if(s.type==="image"&&s.data){let o=s.data.startsWith("data:")?s.data:`data:${s.media_type||"image/png"};base64,${s.data}`;n.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l=cs.buildRequestBody({model:o,messages:c,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!1}),u;try{u=await Ld.post(`${this.baseUrl}${cs.getEndpoint()}`,l,{timeout:s.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return cs.normalizeResponse(u.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||8192,c=s.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u=cs.buildRequestBody({model:o,messages:l,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!0}),d;try{d=await Ld.post(`${this.baseUrl}${cs.getEndpoint()}`,u,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let g=p.response?.status?` [HTTP ${p.response.status}]`:"",m=await fw(p,h=>h?.error?.message||h?.error);throw new Error(`API Error${g}: ${m}`)}let f=cs.createStreamParser(c);return new Promise((p,g)=>{s.signal&&s.signal.addEventListener("abort",()=>{d.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",m=>{let{done:h,result:y}=f.feed(m.toString());h&&p(y)}),d.data.on("error",m=>{s.signal?.aborted||g(new Error(`Stream error: ${m.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return cs.normalizeResponse(e)}};jd.exports={GeminiProvider:uc,GEMINI_MODELS:Id}});var Ud=ne((b1,Fd)=>{var ui=require("axios"),{BaseProvider:pw,readStreamErrorBody:mw}=Gs(),{ollamaProtocol:ls}=Vs(),qd="http://localhost:11434",dc=class extends pw{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||qd,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let n=(await ui.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let s of n){let o=s.name||s.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let c=await ui.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=c.data?.model_info||c.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(c.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:s.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let s=[],o=[];for(let i of n.content)i.type==="text"?s.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:s.join(`
|
|
60
|
-
`)};return o.length>0&&(r.images=o),r}return n})}async chat(e,n,s={}){this._modelsLoaded||await this.loadModels();let o=s.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=
|
|
61
|
-
`)}}function
|
|
62
|
-
`)}function
|
|
63
|
-
`),c}catch(c){throw o.stop(),c}}async function
|
|
54
|
+
`)}var{Spinner:Dy,MultiProgress:qy,TaskProgress:Fy,ToolProgress:Uy,setActiveTaskProgress:By,getActiveTaskProgress:Wy,cleanupTerminal:Hy}=Gs(),{formatToolCall:Ky,formatResult:Yy,getToolSpinnerText:Gy,formatToolSummary:zy,formatSectionHeader:Xy,formatMilestone:Vy,getThinkingVerb:Jy,setActiveModelForSpinner:Zy}=_d();vd.exports={C:sc,banner:jy,Spinner:Dy,MultiProgress:qy,TaskProgress:Fy,ToolProgress:Uy,setActiveTaskProgress:By,getActiveTaskProgress:Wy,cleanupTerminal:Hy,formatToolCall:Ky,formatResult:Yy,getToolSpinnerText:Gy,formatToolSummary:zy,formatSectionHeader:Xy,formatMilestone:Vy,getThinkingVerb:Jy,setActiveModelForSpinner:Zy}});var $t=oe((F1,Cd)=>{var Qy=require("readline"),{C:$n}=Ke(),ew=/[\u200B\u200C\u200D\uFEFF\u2060\u00AD]/g,tw=/^=([\w-]+)/;function No(t){return typeof t!="string"?t:t.replace(ew,"").replace(tw,"$1")}var ic=[/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/],Sd=[...ic,/\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 nw(t){for(let e of Sd)if(e.test(t))return e;return null}var kd=[/\.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)/],sw=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,oc=[/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 Ed(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let s=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(s.length===0)return!1;let o=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let c=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return c?c.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>o(u)):oc.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:oc.some(c=>c.test(i))};return s.every(o)}var ac=[/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)/],Td=[/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/],Rd=[...ac,...Td],cc=!1,is=null,rc=null;function ow(t){cc=t}function rw(t){rc=t}function iw(){return cc}function aw(t){is=t}function cw(t){let e=No(t);for(let n of ic)if(n.test(e))return n;return null}function lw(t){let e=No(t);if(/ssh\s/.test(e)&&Ed(e))return!1;for(let n of Rd)if(n.test(e))return!0;return!1}function uw(t){let e=No(t);for(let n of ac)if(n.test(e))return!0;return!1}function dw(t){if(process.env.NEX_UNPROTECT==="1")return null;let e=No(t);if(!sw.test(e))return null;for(let n of kd)if(n.test(e))return n;return null}function fw(t,e={}){if(cc)return Promise.resolve(!0);if(rc)return rc(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return pw(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(s=>{let o=0;is&&is.pause();let r=global._nexRawWrite||(f=>process.stdout.write(f)),i=()=>{let f=process.stdout.rows||24;return Math.max(1,f-n.length-2)},c=()=>{let f=i();global._nexRawWrite&&f>1&&global._nexRawWrite(`\x1B[1;${f-1}r`);let p=`\x1B[${f};1H\x1B[2K${$n.yellow}${t}${$n.reset}`;for(let g=0;g<n.length;g++){let m=g===o,h=m?`${$n.yellow}\u276F${$n.reset}`:" ",y=m?`${$n.yellow}${n[g]}${$n.reset}`:n[g];p+=`\x1B[${f+1+g};1H\x1B[2K ${h} ${y}`}r(p)},l=f=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",d);let p=global._nexRawWrite||(h=>process.stdout.write(h)),g=i(),m="";for(let h=0;h<n.length+1;h++)m+=`\x1B[${g+h};1H\x1B[2K`;p(m),global._nexRawWrite&&global._nexFooter&&global._nexRawWrite(`\x1B[1;${global._nexFooter._scrollEnd}r`),global._nexFooter&&global._nexFooter.drawFooter(),is&&is.resume(),s(f)},u=f=>{if(f===1){l(!1);return}f===2&&e.toolName&&si(e.toolName),l(!0)},d=f=>{if(f[0]===3){l(!1);return}let p=f.toString();if(p==="\r"||p===`
|
|
55
|
+
`){u(o);return}if(p==="\x1B[A"){o=(o-1+n.length)%n.length,c();return}if(p==="\x1B[B"){o=(o+1)%n.length,c();return}let g=p.toLowerCase().trim();if(g==="y"){l(!0);return}if(g==="n"){l(!1);return}if(g==="a"&&e.toolName){si(e.toolName),l(!0);return}};c(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",d)})}function pw(t,e){let n=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(s=>{let o=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(si(e.toolName),s(!0)):s(i!=="n")};if(is)is.question(`${$n.yellow}${t} ${n}${$n.reset}`,o);else{let r=Qy.createInterface({input:process.stdin,output:process.stdout});r.question(`${$n.yellow}${t} ${n}${$n.reset}`,i=>{r.close(),o(i)})}})}var si=()=>{};function mw(t){si=t}Cd.exports={sanitizeBashCommand:No,FORBIDDEN_PATTERNS:ic,SSH_FORBIDDEN_PATTERNS:Sd,BASH_PROTECTED_PATHS:kd,SSH_SAFE_PATTERNS:oc,isSSHReadOnly:Ed,DANGEROUS_BASH:Rd,CRITICAL_BASH:ac,NOTABLE_BASH:Td,isForbidden:cw,isSSHForbidden:nw,isDangerous:lw,isCritical:uw,isBashPathForbidden:dw,confirm:fw,setAutoConfirm:ow,getAutoConfirm:iw,setConfirmHook:rw,setReadlineInterface:aw,setAllowAlwaysHandler:mw}});var zs=oe((U1,Ad)=>{async function hw(t,e){if(!t.response?.data)return t.message;let n=t.response.data;if(typeof n=="object"&&n!==null&&typeof n.pipe!="function")return e(n)||t.message;try{let s=await new Promise((r,i)=>{let c=[];n.on("data",l=>c.push(l)),n.on("end",()=>r(Buffer.concat(c).toString("utf8"))),n.on("error",i)}),o=JSON.parse(s);return e(o)||s||t.message}catch{return t.message}}var lc=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,n,s={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,n,s={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};Ad.exports={BaseProvider:lc,readStreamErrorBody:hw}});var Js=oe((B1,Nd)=>{var Xs=class{buildRequestBody(e){throw new Error("buildRequestBody() not implemented")}getEndpoint(){throw new Error("getEndpoint() not implemented")}formatTools(e){return e}normalizeResponse(e){throw new Error("normalizeResponse() not implemented")}createStreamParser(e,n={}){throw new Error("createStreamParser() not implemented")}},Vs=class{constructor(e,n={}){this.onToken=e,this.callbacks=n,this.content="",this.buffer=""}feed(e){this.buffer+=e;let n=this.buffer.split(`
|
|
56
|
+
`);this.buffer=n.pop()||"";for(let s of n){let o=this.parseLine(s);if(o?.done)return o}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},oi=class extends Vs{constructor(e,n={}){super(e,n),this.toolCallsMap={}}parseLine(e){let n=e.trim();if(!n||!n.startsWith("data: "))return{done:!1};let s=n.slice(6);if(s==="[DONE]")return{done:!0,result:this.getResult()};let o;try{o=JSON.parse(s)}catch{return{done:!1}}let r=o.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let c=i.index??0;this.toolCallsMap[c]||(this.toolCallsMap[c]={id:i.id||"",name:"",arguments:""}),i.id&&(this.toolCallsMap[c].id=i.id),i.function?.name&&(this.toolCallsMap[c].name+=i.function.name),i.function?.arguments&&(this.toolCallsMap[c].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}}))}}},ri=class extends Xs{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:n,tools:s,maxTokens:o,temperature:r,stream:i}){let c={model:e,messages:n,max_tokens:o,temperature:r};return i&&(c.stream=!0),s&&s.length>0&&(c.tools=s),c}normalizeResponse(e){let n=e.choices?.[0]?.message||{},s=(n.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:n.content||"",tool_calls:s}}createStreamParser(e,n={}){return new oi(e,n)}},ii=class extends Vs{constructor(e,n={}){super(e,n),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let n=e.trim();if(!n.startsWith("data: "))return{done:!1};let s=n.slice(6),o;try{o=JSON.parse(s)}catch{return{done:!1}}switch(o.type){case"content_block_start":{let r=o.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=o.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let n={};if(e.inputJson)try{n=JSON.parse(e.inputJson)}catch{n=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:n}}})}}},uc="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->",ai=class extends Xs{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:n,tools:s,maxTokens:o,temperature:r,stream:i,extra:c}){let l={model:e,messages:n,max_tokens:o,temperature:r};if(i&&(l.stream=!0),c?.system){let u=c.system,d=u.indexOf(uc);if(d!==-1){let f=u.slice(0,d).trimEnd(),p=u.slice(d+uc.length).trimStart();l.system=[{type:"text",text:f},{type:"text",text:p,cache_control:{type:"ephemeral"}}]}else l.system=u}return s&&s.length>0&&(l.tools=s),l}formatTools(e){return!e||e.length===0?[]:e.map(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}normalizeResponse(e){let n="",s=[];for(let o of e.content||[])o.type==="text"?n+=o.text:o.type==="tool_use"&&s.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:n,tool_calls:s}}createStreamParser(e,n={}){return new ii(e,n)}};function Od(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 ci=class extends Vs{constructor(e,n={}){super(e,n),this.toolCalls=[],this.onThinkingToken=n.onThinkingToken||(()=>{})}parseLine(e){if(!e.trim())return{done:!1};let n;try{n=JSON.parse(e)}catch{return{done:!1}}return n.message?.thinking&&this.onThinkingToken(n.message.thinking),n.message?.content&&(this.onToken(n.message.content),this.content+=n.message.content),n.message?.tool_calls&&(this.toolCalls=this.toolCalls.concat(n.message.tool_calls)),n.done?{done:!0,result:this.getResult()}:{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolCalls.map((e,n)=>({id:e.id||`ollama-${Date.now()}-${n}`,function:{name:e.function?.name||e.name||"unknown",arguments:Od(e.function?.arguments??e.arguments)}}))}}},li=class extends Xs{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:n,tools:s,maxTokens:o,temperature:r,stream:i,extra:c}){let l={model:e,messages:n,stream:i,options:{temperature:r,num_predict:o,repeat_penalty:c?.repeat_penalty??1.05}};return s&&s.length>0&&(l.tools=s),l}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:(n.tool_calls||[]).map((s,o)=>({id:s.id||`ollama-${Date.now()}-${o}`,function:{name:s.function?.name||s.name||"unknown",arguments:Od(s.function?.arguments??s.arguments)}}))}}createStreamParser(e,n={}){return new ci(e,n)}},gw=new ri,$w=new ai,yw=new li;Nd.exports={ANTHROPIC_CACHE_BOUNDARY:uc,WireProtocol:Xs,StreamParser:Vs,OpenAICompatibleProtocol:ri,AnthropicProtocol:ai,OllamaChatProtocol:li,OpenAIStreamParser:oi,AnthropicStreamParser:ii,OllamaStreamParser:ci,openaiProtocol:gw,anthropicProtocol:$w,ollamaProtocol:yw}});var Ld=oe((W1,Pd)=>{var ui=require("axios"),ww=require("http"),bw=require("https"),{BaseProvider:_w,readStreamErrorBody:xw}=zs(),{ollamaProtocol:as}=Js(),di=new ww.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),fi=new bw.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Md={"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}},dc=class extends _w{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Md,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){ui.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:di,httpsAgent:fi}).then(e=>{let n=e.data?.models||[];for(let s of n){let o=(s.name||s.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:s.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await ui.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:di,httpsAgent:fi})).data?.models||[];for(let s of n){let o=(s.name||s.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:s.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let s=[],o=[];for(let i of n.content)i.type==="text"?s.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:s.join(`
|
|
57
|
+
`)};return o.length>0&&(r.images=o),r}return n})}async chat(e,n,s={}){await this.discoverModels();let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,c=as.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!1,extra:{repeat_penalty:s.repeat_penalty}}),l;try{l=await ui.post(`${this.baseUrl}${as.getEndpoint()}`,c,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),httpAgent:di,httpsAgent:fi})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=u.response?.data?.error||u.message;throw new Error(`API Error${d}: ${f}`)}return as.normalizeResponse(l.data)}async stream(e,n,s={}){await this.discoverModels();let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,c=s.onToken||(()=>{}),l=s.onThinkingToken||(()=>{}),u=as.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!0,extra:{repeat_penalty:s.repeat_penalty}}),d;try{d=await ui.post(`${this.baseUrl}${as.getEndpoint()}`,u,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal,httpAgent:di,httpsAgent:fi})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let g=p.response?.status?` [HTTP ${p.response.status}]`:"",m=await xw(p,y=>y?.error),h=new Error(`API Error${g}: ${m}`);throw h.code=p.code||(p.response?.status?`HTTP_${p.response.status}`:void 0),h}let f=as.createStreamParser(c,{onThinkingToken:l});return new Promise((p,g)=>{s.signal&&s.signal.addEventListener("abort",()=>{d.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",m=>{let{done:h,result:y}=f.feed(m.toString());h&&p(y)}),d.data.on("error",m=>{if(s.signal?.aborted)return;let h=new Error(`Stream error: ${m.message}`);h.code=m.code||m.name,g(h)}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return as.normalizeResponse(e)}};Pd.exports={OllamaProvider:dc,OLLAMA_MODELS:Md}});var qd=oe((H1,Dd)=>{var Id=require("axios"),{BaseProvider:vw,readStreamErrorBody:Sw}=zs(),{openaiProtocol:cs}=Js(),jd={"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}},fc=class extends vw{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||jd,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let s of e){if(this._messageFormatCache.has(s)){n.push(this._messageFormatCache.get(s));continue}let o=this._getMessageCacheKey(s);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(s,i),n.push(i);continue}let r=this._formatSingleMessage(s);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(s,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let s of e.content)if(s.type==="text")n.push({type:"text",text:s.text??""});else if(s.type==="image"&&s.data){let o=s.data.startsWith("data:")?s.data:`data:${s.media_type||"image/png"};base64,${s.data}`;n.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,{messages:c}=this.formatMessages(e),l=cs.buildRequestBody({model:o,messages:c,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!1}),u;try{u=await Id.post(`${this.baseUrl}${cs.getEndpoint()}`,l,{timeout:s.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return cs.normalizeResponse(u.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||16384,c=s.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u=cs.buildRequestBody({model:o,messages:l,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!0}),d;try{d=await Id.post(`${this.baseUrl}${cs.getEndpoint()}`,u,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let g=p.response?.status?` [HTTP ${p.response.status}]`:"",m=await Sw(p,h=>h?.error?.message||h?.error);throw new Error(`API Error${g}: ${m}`)}let f=cs.createStreamParser(c);return new Promise((p,g)=>{s.signal&&s.signal.addEventListener("abort",()=>{d.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",m=>{let{done:h,result:y}=f.feed(m.toString());h&&p(y)}),d.data.on("error",m=>{s.signal?.aborted||g(new Error(`Stream error: ${m.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return cs.normalizeResponse(e)}};Dd.exports={OpenAIProvider:fc,OPENAI_MODELS:jd}});var Wd=oe((K1,Bd)=>{var Fd=require("axios"),{BaseProvider:kw,readStreamErrorBody:Ew}=zs(),{anthropicProtocol:Fn}=Js(),Ud={"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}},Tw="2023-06-01",pc=class extends kw{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Ud,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Tw}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n="",s=[];for(let o of e){if(o.role==="system"){n+=(n?`
|
|
58
|
+
|
|
59
|
+
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){s.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,s);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(o);this._messageStringCache.set(i,r),this._messageFormatCache.set(o,r)}s.push(r)}}for(let o=s.length-1;o>0;o--)s[o].role==="user"&&s[o-1].role==="user"&&s.splice(o,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:s,system:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let s=[];if(e.content&&s.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)s.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:s.length>0?s:[{type:"text",text:""}]}}if(e.role==="tool"){let s=n[n.length-1],o={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return s&&s.role==="user"&&Array.isArray(s.content)&&s.content[0]?.type==="tool_result"?(s.content.push(o),null):{role:"user",content:[o]}}if(Array.isArray(e.content)){let s=[];for(let o of e.content)o.type==="text"?s.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&s.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:s}}return{role:"user",content:e.content}}formatTools(e){return Fn.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),c=s.maxTokens||i?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d=this.formatTools(n),f=Fn.buildRequestBody({model:r,messages:l,tools:d,maxTokens:c,temperature:s.temperature??this.temperature,stream:!1,extra:{system:u}}),p;try{p=await Fd.post(`${this.baseUrl}${Fn.getEndpoint()}`,f,{timeout:s.timeout||this.timeout,headers:this._getHeaders()})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let m=g.response?.status?` [HTTP ${g.response.status}]`:"",h=g.response?.data?.error?.message||g.response?.data?.error||g.message;throw new Error(`API Error${m}: ${h}`)}return Fn.normalizeResponse(p.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this._resolveModelId(o),i=this.getModel(o),c=s.maxTokens||i?.maxTokens||8192,l=s.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f=this.formatTools(n),p=Fn.buildRequestBody({model:r,messages:u,tools:f,maxTokens:c,temperature:s.temperature??this.temperature,stream:!0,extra:{system:d}}),g;try{g=await Fd.post(`${this.baseUrl}${Fn.getEndpoint()}`,p,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let y=h.response?.status?` [HTTP ${h.response.status}]`:"",b=await Ew(h,S=>S?.error?.message||S?.error);throw new Error(`API Error${y}: ${b}`)}let m=Fn.createStreamParser(l);return new Promise((h,y)=>{s.signal&&s.signal.addEventListener("abort",()=>{g.data.destroy(),y(new DOMException("The operation was aborted","AbortError"))},{once:!0}),g.data.on("data",b=>{let{done:S,result:C}=m.feed(b.toString());S&&h(C)}),g.data.on("error",b=>{s.signal?.aborted||y(new Error(`Stream error: ${b.message}`))}),g.data.on("end",()=>{h(m.flush())})})}normalizeResponse(e){return Fn.normalizeResponse(e)}};Bd.exports={AnthropicProvider:pc,ANTHROPIC_MODELS:Ud}});var Gd=oe((Y1,Yd)=>{var Hd=require("axios"),{BaseProvider:Rw,readStreamErrorBody:Cw}=zs(),{openaiProtocol:ls}=Js(),Kd={"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}},mc=class extends Rw{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Kd,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let s of e){if(this._messageFormatCache.has(s)){n.push(this._messageFormatCache.get(s));continue}let o=this._getMessageCacheKey(s);if(this._messageStringCache.has(o)){let i=this._messageStringCache.get(o);this._messageFormatCache.set(s,i),n.push(i);continue}let r=this._formatSingleMessage(s);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(s,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",s=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${n}:${s.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let s of e.content)if(s.type==="text")n.push({type:"text",text:s.text??""});else if(s.type==="image"&&s.data){let o=s.data.startsWith("data:")?s.data:`data:${s.media_type||"image/png"};base64,${s.data}`;n.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l=ls.buildRequestBody({model:o,messages:c,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!1}),u;try{u=await Hd.post(`${this.baseUrl}${ls.getEndpoint()}`,l,{timeout:s.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return ls.normalizeResponse(u.data)}async stream(e,n,s={}){let o=s.model||this.defaultModel,r=this.getModel(o),i=s.maxTokens||r?.maxTokens||8192,c=s.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u=ls.buildRequestBody({model:o,messages:l,tools:n,maxTokens:i,temperature:s.temperature??this.temperature,stream:!0}),d;try{d=await Hd.post(`${this.baseUrl}${ls.getEndpoint()}`,u,{timeout:s.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:s.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let g=p.response?.status?` [HTTP ${p.response.status}]`:"",m=await Cw(p,h=>h?.error?.message||h?.error);throw new Error(`API Error${g}: ${m}`)}let f=ls.createStreamParser(c);return new Promise((p,g)=>{s.signal&&s.signal.addEventListener("abort",()=>{d.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",m=>{let{done:h,result:y}=f.feed(m.toString());h&&p(y)}),d.data.on("error",m=>{s.signal?.aborted||g(new Error(`Stream error: ${m.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return ls.normalizeResponse(e)}};Yd.exports={GeminiProvider:mc,GEMINI_MODELS:Kd}});var Vd=oe((G1,Xd)=>{var pi=require("axios"),{BaseProvider:Aw,readStreamErrorBody:Ow}=zs(),{ollamaProtocol:us}=Js(),zd="http://localhost:11434",hc=class extends Aw{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||zd,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let n=(await pi.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let s of n){let o=s.name||s.model;if(!o)continue;let r=o.replace(/:latest$/,""),i=32768;try{let c=await pi.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=c.data?.model_info||c.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(c.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:s.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let s=[],o=[];for(let i of n.content)i.type==="text"?s.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:s.join(`
|
|
60
|
+
`)};return o.length>0&&(r.images=o),r}return n})}async chat(e,n,s={}){this._modelsLoaded||await this.loadModels();let o=s.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=us.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:s.maxTokens||8192,temperature:s.temperature??this.temperature,stream:!1}),i;try{i=await pi.post(`${this.baseUrl}${us.getEndpoint()}`,r,{timeout:s.timeout||this.timeout})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let l=c.response?.status?` [HTTP ${c.response.status}]`:"",u=c.response?.data?.error||c.message;throw new Error(`API Error${l}: ${u}`)}return us.normalizeResponse(i.data)}async stream(e,n,s={}){this._modelsLoaded||await this.loadModels();let o=s.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=s.onToken||(()=>{}),i=us.buildRequestBody({model:o,messages:this._formatMessages(e),tools:n,maxTokens:s.maxTokens||8192,temperature:s.temperature??this.temperature,stream:!0}),c;try{c=await pi.post(`${this.baseUrl}${us.getEndpoint()}`,i,{timeout:s.timeout||this.timeout,responseType:"stream",signal:s.signal})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=await Ow(u,p=>p?.error);throw new Error(`API Error${d}: ${f}`)}let l=us.createStreamParser(r);return new Promise((u,d)=>{s.signal&&s.signal.addEventListener("abort",()=>{c.data.destroy(),d(new DOMException("The operation was aborted","AbortError"))},{once:!0}),c.data.on("data",f=>{let{done:p,result:g}=l.feed(f.toString());p&&u(g)}),c.data.on("error",f=>{s.signal?.aborted||d(new Error(`Stream error: ${f.message}`))}),c.data.on("end",()=>{u(l.flush())})})}normalizeResponse(e){return us.normalizeResponse(e)}_parseContextFromModelfile(e){if(!e)return null;let n=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return n?parseInt(n[1],10):null}};Xd.exports={LocalProvider:hc,DEFAULT_LOCAL_URL:zd}});var Tn=oe((z1,Zd)=>{"use strict";var Pt=require("fs"),Jd=require("path");function Nw(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Mw(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function Pw(t,e){let n=Jd.dirname(t),s=Jd.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{Pt.existsSync(n)||Pt.mkdirSync(n,{recursive:!0}),Pt.writeFileSync(s,e,"utf-8"),Pt.renameSync(s,t)}catch(o){try{Pt.unlinkSync(s)}catch{}throw o}}function Lw(t,e,{timeout:n=5e3,retryMs:s=50}={}){let o=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=Pt.openSync(o,"wx"),Pt.writeSync(i,Buffer.from(String(process.pid))),Pt.closeSync(i),i=-1;try{return e()}finally{try{Pt.unlinkSync(o)}catch{}}}catch(c){if(i!==-1)try{Pt.closeSync(i)}catch{}if(c.code!=="EEXIST")throw c;try{let l=Pt.readFileSync(o,"utf-8").trim(),u=parseInt(l,10);if(!Nw(u)){try{Pt.unlinkSync(o)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{Pt.unlinkSync(o)}catch{}return e()}Mw(s)}}}Zd.exports={atomicWrite:Pw,withFileLockSync:Lw}});var Qs=oe((X1,rf)=>{var Zs=require("fs"),gc=require("path"),{atomicWrite:Iw,withFileLockSync:jw}=Tn(),Qd={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:{}},mi=[],Un={};function Dw(t,e,n,s){if(mi.push({provider:t,model:e,input:n,output:s}),Un[t]!==void 0){let o=sf(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
|
|
61
|
+
`)}}function $c(t,e){let n=Qd[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function ef(t){let e=$c(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function tf(){let t={};for(let r of mi){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:ef(r)})),n=e.reduce((r,i)=>r+i.cost,0),s=e.reduce((r,i)=>r+i.input,0),o=e.reduce((r,i)=>r+i.output,0);return{totalCost:n,totalInput:s,totalOutput:o,breakdown:e}}function qw(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:s}=tf();if(s.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of s){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";o.push(` ${r.provider}:${r.model}`),o.push(` Input: ${r.input.toLocaleString()} tokens`),o.push(` Output: ${r.output.toLocaleString()} tokens`),o.push(` Cost: ${i}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${n.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
|
|
62
|
+
`)}function Fw(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function Uw(t,e,n,s){let o=$c(t,e),r=(n*o.input+s*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Bw(){mi=[]}function Ww(t,e){Un[t]=e}function Hw(t){delete Un[t]}function Kw(){return{...Un}}function nf(t){let e=0;for(let n of mi)n.provider===t&&(e+=ef(n));return e}function sf(t){let e=nf(t),n=Un[t];if(n===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let s=Math.max(0,n-e);return{allowed:e<n,spent:e,limit:n,remaining:s}}function of(){let t=gc.join(process.cwd(),".nex","config.json");if(Zs.existsSync(t))try{let e=JSON.parse(Zs.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Un={...e.costLimits})}catch{}}function Yw(){let t=gc.join(process.cwd(),".nex"),e=gc.join(t,"config.json");Zs.existsSync(t)||Zs.mkdirSync(t,{recursive:!0}),jw(e,()=>{let n={};if(Zs.existsSync(e))try{n=JSON.parse(Zs.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=Un,Iw(e,JSON.stringify(n,null,2))})}function Gw(){Un={}}of();rf.exports={PRICING:Qd,trackUsage:Dw,getSessionCosts:tf,formatCosts:qw,formatCostHint:Uw,resetCosts:Bw,getPricing:$c,setCostLimit:Ww,removeCostLimit:Hw,getCostLimits:Kw,getProviderSpend:nf,checkBudget:sf,loadCostLimits:of,saveCostLimits:Yw,resetCostLimits:Gw,estimateTokens:Fw}});var hi=oe((V1,af)=>{function yc(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var zw=yc();function Xw(...t){yc()&&console.log(...t)}function Vw(...t){yc()&&console.warn(...t)}af.exports={DEBUG:zw,debugLog:Xw,warnLog:Vw}});var uf=oe((J1,lf)=>{"use strict";var Jw=new Set(["read_file","grep","glob","search_files","list_directory"]),Zw=new Set(["write_file","edit_file","patch_file"]),Qw=new Set(["bash"]),e0=new Set(["web_search","web_fetch","perplexity_search"]);function cf(t,e){let n=0,s=0,o=0,r=0,i=0;for(let[c,l]of t)i+=l,Jw.has(c)&&(n+=l),Zw.has(c)&&(s+=l),Qw.has(c)&&(o+=l),e0.has(c)&&(r+=l);return i===0?`Phase ${e}`:r/i>.5?"Research":n/i>.5?"Exploration":s/i>.3?"Implementation":o/i>.3&&s/i<.15?"Verification":`Phase ${e}`}var wc=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,n,s,o){if(this._disabled)return null;this._stepsThisPhase++;for(let i of n)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:cf(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(s),filesModified:new Set(o)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};lf.exports={MilestoneTracker:wc,_phaseName:cf}});var eo=oe((Z1,df)=>{var Mo=Be(),t0={"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 n0(){return Mo.getActiveModel()}function s0(t){return Mo.setActiveModel(t)}function o0(){return Mo.getModelNames()}function r0(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let s=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(s)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let s=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(s)}catch{}let n=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)try{return JSON.parse(n[1].trim())}catch{}return null}async function i0(t,e){let{C:n}=Ke(),{Spinner:s}=Ke(),o=new s("Thinking...");o.start();let r=!0,i="";try{let c=await Mo.callStream(t,e,{onToken:l=>{r&&(o.stop(),process.stdout.write(`${n.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?o.stop():process.stdout.write(`${n.reset}
|
|
63
|
+
`),c}catch(c){throw o.stop(),c}}async function a0(t,e){return Mo.callChat(t,e)}df.exports={MODELS:t0,getActiveModel:n0,setActiveModel:s0,getModelNames:o0,callOllamaStream:i0,callOllama:a0,parseToolArgs:r0}});var mf=oe((eR,pf)=>{var gi=require("path"),{C:U}=Ke(),{T:bc,isDark:Q1}=os(),{confirm:c0,getAutoConfirm:l0}=$t(),ff=2e3;function Po(t,e){let n=t.split(`
|
|
64
64
|
`),s=e.split(`
|
|
65
|
-
`),o=[],r=n.length,i=s.length;if(r>
|
|
66
|
-
${U.bold}${U.cyan} Diff: ${t}${U.reset}`);let o=
|
|
67
|
-
${U.bold}${U.cyan} File exists \u2014 showing changes: ${t}${U.reset}`);let s=
|
|
65
|
+
`),o=[],r=n.length,i=s.length;if(r>ff||i>ff){for(let f of n)o.push({type:"remove",line:f});for(let f of s)o.push({type:"add",line:f});return o}let c=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let f=1;f<=r;f++)for(let p=1;p<=i;p++)n[f-1]===s[p-1]?c[f][p]=c[f-1][p-1]+1:c[f][p]=Math.max(c[f-1][p],c[f][p-1]);let l=r,u=i,d=[];for(;l>0||u>0;)l>0&&u>0&&n[l-1]===s[u-1]?(d.unshift({type:"same",line:n[l-1]}),l--,u--):u>0&&(l===0||c[l][u-1]>=c[l-1][u])?(d.unshift({type:"add",line:s[u-1]}),u--):(d.unshift({type:"remove",line:n[l-1]}),l--);return d}function u0(t,e,n,s=3){console.log(`
|
|
66
|
+
${U.bold}${U.cyan} Diff: ${t}${U.reset}`);let o=Po(e,n),r=[];if(o.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${U.gray} (no changes)${U.reset}`);return}let i=Math.max(0,r[0]-s),c=Math.min(o.length,r[r.length-1]+s+1);i>0&&console.log(`${U.gray} ...${U.reset}`);for(let l=i;l<c;l++){let u=o[l];switch(u.type){case"remove":console.log(`${U.red} - ${u.line}${U.reset}`);break;case"add":console.log(`${U.green} + ${u.line}${U.reset}`);break;default:console.log(`${U.gray} ${u.line}${U.reset}`)}}c<o.length&&console.log(`${U.gray} ...${U.reset}`),console.log()}function d0(t,e,n){console.log(`
|
|
67
|
+
${U.bold}${U.cyan} File exists \u2014 showing changes: ${t}${U.reset}`);let s=Po(e,n),o=0;for(let i of s)i.type!=="same"&&o++;if(o===0){console.log(`${U.gray} (identical content)${U.reset}`);return}let r=0;for(let i of s){if(r>=30){console.log(`${U.gray} ...(${o-r} more changes)${U.reset}`);break}switch(i.type){case"remove":console.log(`${U.red} - ${i.line}${U.reset}`),r++;break;case"add":console.log(`${U.green} + ${i.line}${U.reset}`),r++;break;default:r>0&&console.log(`${U.gray} ${i.line}${U.reset}`)}}console.log()}function f0(t,e){console.log(`
|
|
68
68
|
${U.bold}${U.cyan} New file: ${t}${U.reset}`);let n=e.split(`
|
|
69
|
-
`),s=n.slice(0,20);for(let o of s)console.log(`${U.green} + ${o}${U.reset}`);n.length>20&&console.log(`${U.gray} ...+${n.length-20} more lines${U.reset}`),console.log()}async function
|
|
70
|
-
${U.bold}${U.cyan} Side-by-side: ${t}${U.reset}`),console.log(` ${U.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${U.reset}`);let i=
|
|
71
|
-
`)}function
|
|
69
|
+
`),s=n.slice(0,20);for(let o of s)console.log(`${U.green} + ${o}${U.reset}`);n.length>20&&console.log(`${U.gray} ...+${n.length-20} more lines${U.reset}`),console.log()}async function p0(t){return l0()?!0:c0(` ${t}?`)}function m0(t,e,n,s){let o=s||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
|
|
70
|
+
${U.bold}${U.cyan} Side-by-side: ${t}${U.reset}`),console.log(` ${U.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${U.reset}`);let i=Po(e,n),c=[],l=0;for(;l<i.length;)if(i[l].type==="same")c.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let g=[];for(;l<i.length&&i[l].type==="remove";)g.push(i[l].line),l++;let m=[];for(;l<i.length&&i[l].type==="add";)m.push(i[l].line),l++;let h=Math.max(g.length,m.length);for(let y=0;y<h;y++)c.push({left:y<g.length?g[y]:"",right:y<m.length?m[y]:"",type:"changed"})}else i[l].type==="add"&&(c.push({left:"",right:i[l].line,type:"changed"}),l++);let u=c.map((g,m)=>g.type!=="same"?m:-1).filter(g=>g>=0);if(u.length===0){console.log(` ${U.gray}(no changes)${U.reset}`);return}let d=Math.max(0,u[0]-2),f=Math.min(c.length,u[u.length-1]+3),p=(g,m)=>{let h=g.replace(/\x1b\[[0-9;]*m/g,"");return h.length>=m?g.substring(0,m):g+" ".repeat(m-h.length)};d>0&&console.log(` ${U.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${U.reset}`);for(let g=d;g<f;g++){let m=c[g];if(m.type==="same")console.log(` ${U.gray}${p(m.left,r)}${U.reset}\u2502${U.gray}${p(m.right,r)}${U.reset}`);else{let h=m.left?`${U.red}${p(m.left,r)}${U.reset}`:`${p("",r)}`,y=m.right?`${U.green}${p(m.right,r)}${U.reset}`:`${p("",r)}`;console.log(` ${h}\u2502${y}`)}}f<c.length&&console.log(` ${U.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${U.reset}`),console.log(` ${U.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${U.reset}
|
|
71
|
+
`)}function h0(t,e,n,s={}){let o=s.label||"Update",r=s.context||3,i=s.annotations||[],c=gi.isAbsolute(t)?gi.relative(process.cwd(),t):t,l=Po(e,n),u=1,d=1;for(let E of l)E.type==="same"?(E.oldLine=u++,E.newLine=d++):E.type==="remove"?(E.oldLine=u++,E.newLine=null):(E.oldLine=null,E.newLine=d++);let f=0,p=0;for(let E of l)E.type==="add"?f++:E.type==="remove"&&p++;if(console.log(`
|
|
72
72
|
${U.green}\u23FA${U.reset} ${U.bold}${o}(${c})${U.reset}`),f===0&&p===0){console.log(` ${U.dim}\u23BF (no changes)${U.reset}
|
|
73
|
-
`);return}let g=[];if(f>0&&g.push(`Added ${f} line${f!==1?"s":""}`),p>0&&g.push(`removed ${p} line${p!==1?"s":""}`),i.length>0){let
|
|
73
|
+
`);return}let g=[];if(f>0&&g.push(`Added ${f} line${f!==1?"s":""}`),p>0&&g.push(`removed ${p} line${p!==1?"s":""}`),i.length>0){let E=i.filter(ie=>ie.severity==="error").length,B=i.filter(ie=>ie.severity==="warn").length,q=i.filter(ie=>ie.severity==="info").length,re=[];E>0&&re.push(`${U.red}${E} error${E!==1?"s":""}${U.dim}`),B>0&&re.push(`${U.yellow}${B} warning${B!==1?"s":""}${U.dim}`),q>0&&re.push(`${U.cyan}${q} info${q!==1?"s":""}${U.dim}`),g.push(`found ${re.join(", ")}`)}console.log(` ${U.dim}\u23BF ${g.join(", ")}${U.reset}`);let h=[];l.forEach((E,B)=>{E.type!=="same"&&h.push(B)});let y=[],b=null,S=null;for(let E of h){let B=Math.max(0,E-r),q=Math.min(l.length-1,E+r);b===null?(b=B,S=q):(B<=S+1||(y.push([b,S]),b=B),S=q)}b!==null&&y.push([b,S]);let C=" ",k=process.stdout.columns||120;function x(E,B,q){let re=q.replace(/\x1b\[[0-9;]*m/g,""),ie=q+" ".repeat(Math.max(0,k-re.length));return`${E}${B}${ie}${U.reset}`}for(let E=0;E<y.length;E++){E>0&&console.log(`${C}${U.dim}\xB7\xB7\xB7${U.reset}`);let[B,q]=y[E];for(let re=B;re<=q;re++){let ie=l[re],Q=ie.newLine!=null?ie.newLine:ie.oldLine,O=String(Q).padStart(4),Te=ie.type!=="remove"?i.filter(X=>X.line===ie.newLine):[];ie.type==="remove"?console.log(x(bc.diff_rem_bg,U.red,`${C}${O} - ${ie.line}`)):ie.type==="add"?console.log(x(bc.diff_add_bg,U.green,`${C}${O} + ${ie.line}`)):console.log(`${C}${U.dim}${O} ${U.reset}${ie.line}`);for(let X of Te){let V=U.cyan,fe="\u2139";X.severity==="error"?(V=U.red,fe="\u2716"):X.severity==="warn"&&(V=U.yellow,fe="\u26A0"),console.log(`${C} ${V}${fe} ${X.message}${U.reset}`)}}}console.log()}function g0(t,e,n={}){let s=gi.isAbsolute(t)?gi.relative(process.cwd(),t):t,o=e.split(`
|
|
74
74
|
`),r=n.annotations||[];console.log(`
|
|
75
|
-
${U.green}\u23FA${U.reset} ${U.bold}Create(${s})${U.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let f=r.filter(h=>h.severity==="error").length,p=r.filter(h=>h.severity==="warn").length,g=r.filter(h=>h.severity==="info").length,m=[];f>0&&m.push(`${U.red}${f} error${f!==1?"s":""}${U.dim}`),p>0&&m.push(`${U.yellow}${p} warning${p!==1?"s":""}${U.dim}`),g>0&&m.push(`${U.cyan}${g} info${g!==1?"s":""}${U.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${U.dim}\u23BF ${i.join(", ")}${U.reset}`);let l=" ",u=process.stdout.columns||120,d=Math.min(o.length,20);for(let f=0;f<d;f++){let p=String(f+1).padStart(4),g=f+1,m=r.filter(
|
|
76
|
-
`).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),s=e.substring(3);return{status:n,file:s}})}catch{return[]}}async function
|
|
77
|
-
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&r++}else o=t.length;let i="chore",c=t.join(" ").toLowerCase();c.includes("test")?i="test":c.includes("readme")||c.includes("doc")?i="docs":o>r*2?i="feat":r>o?i="refactor":i="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function
|
|
75
|
+
${U.green}\u23FA${U.reset} ${U.bold}Create(${s})${U.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let f=r.filter(h=>h.severity==="error").length,p=r.filter(h=>h.severity==="warn").length,g=r.filter(h=>h.severity==="info").length,m=[];f>0&&m.push(`${U.red}${f} error${f!==1?"s":""}${U.dim}`),p>0&&m.push(`${U.yellow}${p} warning${p!==1?"s":""}${U.dim}`),g>0&&m.push(`${U.cyan}${g} info${g!==1?"s":""}${U.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${U.dim}\u23BF ${i.join(", ")}${U.reset}`);let l=" ",u=process.stdout.columns||120,d=Math.min(o.length,20);for(let f=0;f<d;f++){let p=String(f+1).padStart(4),g=f+1,m=r.filter(S=>S.line===g),h=`${l}${p} + ${o[f]}`,y=h.replace(/\x1b\[[0-9;]*m/g,""),b=h+" ".repeat(Math.max(0,u-y.length));console.log(`${bc.diff_add_bg}${U.green}${b}${U.reset}`);for(let S of m){let C=U.cyan,k="\u2139";S.severity==="error"?(C=U.red,k="\u2716"):S.severity==="warn"&&(C=U.yellow,k="\u26A0"),console.log(`${l} ${C}${k} ${S.message}${U.reset}`)}}o.length>20&&console.log(`${l}${U.dim} ...+${o.length-20} more lines${U.reset}`),console.log()}pf.exports={diffLines:Po,showEditDiff:u0,showWriteDiff:d0,showNewFilePreview:f0,confirmFileChange:p0,showSideBySideDiff:m0,showDiff:h0,showNewFile:g0}});var Bn=oe((tR,$f)=>{var hf=require("util").promisify(require("child_process").exec),$0=require("util").promisify(require("child_process").execFile),{C:Ze}=Ke();async function _c(t){try{let{stdout:e}=await hf(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function $i(...t){try{let{stdout:e}=await $0("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function y0(){return await _c("git rev-parse --is-inside-work-tree")==="true"}async function w0(){return await _c("git branch --show-current")}async function xc(){try{let{stdout:t}=await hf("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
76
|
+
`).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),s=e.substring(3);return{status:n,file:s}})}catch{return[]}}async function yi(t=!1){return await _c(`git diff ${t?"--cached":""}`)||""}async function vc(){return(await xc()).map(e=>e.file)}async function gf(){let t=await vc();if(t.length===0)return null;let e=await yi(),s=await yi(!0)||e,o=0,r=0;if(s){let d=s.split(`
|
|
77
|
+
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&r++}else o=t.length;let i="chore",c=t.join(" ").toLowerCase();c.includes("test")?i="test":c.includes("readme")||c.includes("doc")?i="docs":o>r*2?i="feat":r>o?i="refactor":i="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function b0(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await $i("checkout","-b",n)!==null?n:null}async function _0(t){return await $i("add","-A"),await $i("commit","-m",t)?await $i("rev-parse","--short","HEAD"):null}async function x0(){let t=await gf();if(!t)return`${Ze.dim}No changes${Ze.reset}`;let e=[];e.push(`
|
|
78
78
|
${Ze.bold}${Ze.cyan}Git Diff Summary:${Ze.reset}`),e.push(` ${Ze.green}+${t.stats.additions}${Ze.reset} ${Ze.red}-${t.stats.deletions}${Ze.reset} in ${t.files.length} file(s)`),e.push(`
|
|
79
79
|
${Ze.bold}${Ze.cyan}Files:${Ze.reset}`);for(let n of t.files.slice(0,20))e.push(` ${Ze.dim}${n}${Ze.reset}`);return t.files.length>20&&e.push(` ${Ze.dim}...+${t.files.length-20} more${Ze.reset}`),e.push(`
|
|
80
80
|
${Ze.bold}${Ze.cyan}Suggested message:${Ze.reset}`),e.push(` ${Ze.cyan}${t.summary}${Ze.reset}
|
|
81
81
|
`),e.join(`
|
|
82
|
-
`)}async function
|
|
82
|
+
`)}async function v0(){return(await xc()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function S0(){let t=await vc();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let s of t.slice(0,10))e.push(` ${s}`);let n=await yi();if(n){let s=n.length>5e3?n.substring(0,5e3)+`
|
|
83
83
|
...(truncated)`:n;e.push(`
|
|
84
84
|
DIFF:
|
|
85
85
|
${s}`)}return e.join(`
|
|
86
|
-
`)}
|
|
87
|
-
`).map(n=>{let s=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!s)return null;let o=s[2].trim();return o.startsWith(
|
|
88
|
-
`)){let c=i.trim();if(/^trigger:\s*$/i.test(c)){r=!0;continue}r&&c.startsWith("- ")?o.push(c.slice(2).trim().replace(/^["']|["']$/g,"")):r&&c&&!c.startsWith("#")&&(r=!1)}return{triggers:o,body:s}}function
|
|
86
|
+
`)}$f.exports={isGitRepo:y0,getCurrentBranch:w0,getStatus:xc,getDiff:yi,getChangedFiles:vc,analyzeDiff:gf,createBranch:b0,commit:_0,formatDiffSummary:x0,getDiffContext:S0,getMergeConflicts:v0}});var Rn=oe((sR,vf)=>{var lt=require("fs").promises,nR=require("fs"),Yt=require("path"),k0=require("crypto"),{execSync:Lo}=require("child_process"),E0=100*1024,bf=50,Et=[],to=[];function T0(t,e,n,s){for(Et.push({tool:t,filePath:e,oldContent:n,newContent:s,timestamp:Date.now()});Et.length>bf;)Et.shift();to.length=0,_f(Et[Et.length-1]).catch(()=>{})}async function R0(){if(Et.length===0)return null;let t=Et.pop();if(t.oldContent===null)try{await lt.unlink(t.filePath)}catch{}else await lt.writeFile(t.filePath,t.oldContent,"utf-8");return to.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function C0(){if(to.length===0)return null;let t=to.pop();return await lt.writeFile(t.filePath,t.newContent,"utf-8"),Et.push(t),{tool:t.tool,filePath:t.filePath}}function A0(t=10){return Et.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function O0(){return Et.length}function N0(){return to.length}function M0({diskToo:t=!0}={}){if(Et.length=0,to.length=0,t){let e=bi();lt.readdir(e).then(n=>{for(let s of n)s.endsWith(".json")&<.unlink(Yt.join(e,s)).catch(()=>{})}).catch(()=>{})}}function bi(){return Yt.join(process.cwd(),".nex","history")}async function yf(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=E0)return{inline:!0,content:t};let n=k0.createHash("sha256").update(t,"utf-8").digest("hex"),s=Yt.join(e,"blobs");return await lt.mkdir(s,{recursive:!0}),await lt.writeFile(Yt.join(s,n),t,"utf-8"),{inline:!1,hash:n}}async function _f(t){let e=bi();await lt.mkdir(e,{recursive:!0});let n=Yt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),s=`${t.timestamp}-${n}.json`,o=await yf(t.oldContent,e),r=await yf(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 lt.writeFile(Yt.join(e,s),JSON.stringify(i),"utf-8")}async function wf(t,e){if(!t)return null;if(t.inline)return t.content;let n=Yt.join(e,"blobs",t.hash);return lt.readFile(n,"utf-8")}async function P0(){let t=bi(),e;try{e=await lt.readdir(t)}catch{return 0}let n=e.filter(o=>o.endsWith(".json")).sort(),s=0;for(let o of n)try{let r=await lt.readFile(Yt.join(t,o),"utf-8"),i=JSON.parse(r),c=await wf(i.oldContent,t),l=await wf(i.newContent,t);Et.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:c,newContent:l}),s++}catch{}for(;Et.length>bf;)Et.shift();return s}async function L0(t=7){let e=bi(),n;try{n=await lt.readdir(e)}catch{return 0}let s=Date.now()-t*24*60*60*1e3,o=n.filter(u=>u.endsWith(".json")),r=0,i=new Set,c=[];for(let u of o)try{let d=await lt.readFile(Yt.join(e,u),"utf-8"),f=JSON.parse(d);f.timestamp<s?(c.push(u),r++):(f.oldContent&&!f.oldContent.inline&&f.oldContent.hash&&i.add(f.oldContent.hash),f.newContent&&!f.newContent.inline&&f.newContent.hash&&i.add(f.newContent.hash))}catch{}for(let u of c)try{await lt.unlink(Yt.join(e,u))}catch{}let l=Yt.join(e,"blobs");try{let u=await lt.readdir(l);for(let d of u)if(!i.has(d))try{await lt.unlink(Yt.join(l,d))}catch{}}catch{}return r}var wi="nex-snapshot";function I0(t,e=process.cwd()){let n=t?`${wi}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${wi}-${Date.now()}`;try{return Lo("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(Lo(`git stash push -u -m "${n}"`,{cwd:e,timeout:15e3}),Lo("git stash pop",{cwd:e,timeout:1e4}),{name:n,label:n,ok:!0}):{name:n,label:n,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(s){return{name:n,label:n,ok:!1,error:s.message}}}function xf(t=process.cwd()){try{let e=Lo("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
|
|
87
|
+
`).map(n=>{let s=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!s)return null;let o=s[2].trim();return o.startsWith(wi)?{index:parseInt(s[1],10),label:o,shortName:o.replace(`${wi}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function j0(t,e=process.cwd()){try{let n=xf(e);if(n.length===0)return{ok:!1,error:"No snapshots found"};let s;return t===void 0||t==="last"?s=n[0]:typeof t=="number"?s=n.find(o=>o.index===t):s=n.find(o=>o.label===t||o.shortName===t||o.shortName.includes(String(t))),s?(Lo(`git stash apply stash@{${s.index}}`,{cwd:e,timeout:15e3}),{ok:!0,label:s.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(n){return{ok:!1,error:n.message}}}vf.exports={recordChange:T0,undo:R0,redo:C0,getHistory:A0,getUndoCount:O0,getRedoCount:N0,clearHistory:M0,persistEntry:_f,loadPersistedHistory:P0,pruneHistory:L0,createSnapshot:I0,listSnapshots:xf,restoreSnapshot:j0}});var Cn=oe((oR,Cf)=>{var Ye=require("fs"),Tt=require("path"),{atomicWrite:D0,withFileLockSync:q0}=Tn(),_t=[];function Io(){return Tt.join(process.cwd(),".nex","skills")}function Sf(){return Tt.join(process.cwd(),".nex","config.json")}function kf(){let t=Io();return Ye.existsSync(t)||Ye.mkdirSync(t,{recursive:!0}),t}function Ec(){let t=Sf();if(!Ye.existsSync(t))return[];try{let e=JSON.parse(Ye.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Ef(t){let e=Sf(),n=Tt.dirname(e);Ye.existsSync(n)||Ye.mkdirSync(n,{recursive:!0}),q0(e,()=>{let s={};if(Ye.existsSync(e))try{s=JSON.parse(Ye.readFileSync(e,"utf-8"))}catch{s={}}s.skills||(s.skills={}),s.skills.disabled=t,D0(e,JSON.stringify(s,null,2))})}function Tf(t,e){let n=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&n.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&n.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&n.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))n.push("commands must be an array");else for(let s=0;s<t.commands.length;s++){let o=t.commands[s];(!o.cmd||typeof o.cmd!="string")&&n.push(`commands[${s}].cmd must be a non-empty string`),o.handler!==void 0&&typeof o.handler!="function"&&n.push(`commands[${s}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))n.push("tools must be an array");else for(let s=0;s<t.tools.length;s++){let o=t.tools[s];(!o.function||!o.function.name||typeof o.function.name!="string")&&n.push(`tools[${s}].function.name must be a non-empty string`),o.execute!==void 0&&typeof o.execute!="function"&&n.push(`tools[${s}].execute must be a function`)}return{valid:n.length===0,errors:n}}function Rf(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let n=e[1],s=e[2].trim(),o=[],r=!1;for(let i of n.split(`
|
|
88
|
+
`)){let c=i.trim();if(/^trigger:\s*$/i.test(c)){r=!0;continue}r&&c.startsWith("- ")?o.push(c.slice(2).trim().replace(/^["']|["']$/g,"")):r&&c&&!c.startsWith("#")&&(r=!1)}return{triggers:o,body:s}}function Sc(t){try{let e=Ye.readFileSync(t,"utf-8").trim();if(!e)return null;let n=Tt.basename(t,".md"),{triggers:s,body:o}=Rf(e);return{name:n,type:"prompt",filePath:t,instructions:o||e,triggers:s,commands:[],tools:[]}}catch{return null}}function kc(t){try{let e=require(t),{valid:n,errors:s}=Tf(e,t);return n?{name:e.name||Tt.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(r=>({cmd:r.cmd.startsWith("/")?r.cmd:`/${r.cmd}`,desc:r.desc||r.description||"",handler:r.handler||null})),tools:(e.tools||[]).map(r=>({type:r.type||"function",function:{name:r.function.name,description:r.function.description||"",parameters:r.function.parameters||{type:"object",properties:{}}},execute:r.execute||null}))}:(console.error(`Skill validation failed: ${t}
|
|
89
89
|
${s.join(`
|
|
90
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
90
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Tc(){_t=[];let t=Ec(),e=Io(),n=[];if(Ye.existsSync(e))try{n=Ye.readdirSync(e)}catch{n=[]}for(let o of n){let r=Tt.join(e,o),i;try{i=Ye.statSync(r)}catch{continue}if(!i.isFile())continue;let c=null;o.endsWith(".md")?c=Sc(r):o.endsWith(".js")&&(c=kc(r)),c&&(c.enabled=!t.includes(c.name),_t.push(c))}let s=Tt.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Ye.existsSync(s)){let o;try{o=Ye.readdirSync(s).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{o=[]}for(let r of o){let i=Tt.join(s,r),c=Tt.basename(r,Tt.extname(r));if(_t.some(d=>d.name===c))continue;let l;try{l=Ye.statSync(i)}catch{continue}if(!l.isFile())continue;let u=r.endsWith(".md")?Sc(i):kc(i);u&&(u._builtin=!0,u.enabled=!t.includes(u.name),_t.push(u))}}return _t}function F0(){let t=[];for(let e of _t)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
91
91
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
92
92
|
${t.join(`
|
|
93
93
|
|
|
94
|
-
`)}`}function
|
|
94
|
+
`)}`}function U0(){let t=[];for(let e of _t)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function B0(){let t=[];for(let e of _t)if(e.enabled)for(let n of e.tools)t.push({type:"function",function:{name:`skill_${n.function.name}`,description:`[Skill:${e.name}] ${n.function.description}`,parameters:n.function.parameters}});return t}async function W0(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let s of _t)if(s.enabled){for(let o of s.tools)if(o.function.name===n&&o.execute)try{let r=await o.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${n}' failed: ${r.message}`}}return`ERROR: Skill tool '${n}' not found`}function H0(t){let[e,...n]=t.split(/\s+/),s=n.join(" ").trim();for(let o of _t)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(s);if(typeof i=="string"&&i.length>0)return{handled:!0,agentPrompt:i}}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return{handled:!0}}}return!1}function K0(){return _t.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 Y0(t){let e=_t.find(s=>s.name===t);if(!e)return!1;e.enabled=!0;let n=Ec().filter(s=>s!==t);return Ef(n),!0}function G0(t){let e=_t.find(s=>s.name===t);if(!e)return!1;e.enabled=!1;let n=Ec();return n.includes(t)||(n.push(t),Ef(n)),!0}function z0(){return _t}async function X0(t,e={}){let{execSync:n}=require("child_process"),s=kf(),o=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(o=`https://github.com/${t}.git`);let r=e.name||Tt.basename(o,".git").replace(/^nex-skill-/,""),i=Tt.join(s,r);if(Ye.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 d=i.replace(/'/g,"'\\''");n(`git clone --depth 1 '${o}' '${d}'`,{timeout:3e4,stdio:"pipe"})}catch(d){return{ok:!1,name:r,error:`Git clone failed: ${d.stderr?.toString().trim()||d.message}`}}let c=Tt.join(i,"skill.json"),l=Ye.existsSync(c),u=Ye.readdirSync(i).some(d=>(d.endsWith(".md")||d.endsWith(".js"))&&!d.startsWith("."));if(!l&&!u){try{Ye.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(l)try{let d=JSON.parse(Ye.readFileSync(c,"utf-8"));d.name||(d.name=r)}catch{try{Ye.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return Tc(),{ok:!0,name:r}}async function V0(t){let e=require("axios");try{let n=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(o=>({name:o.name.replace(/^nex-skill-/,""),description:o.description||"(no description)",url:o.clone_url,stars:o.stargazers_count,owner:o.owner.login}))}catch(n){return[{name:"error",description:`Search failed: ${n.message}`,url:"",stars:0,owner:""}]}}function J0(t){let e=Tt.join(Io(),t);if(!Ye.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${Io()}`};try{return Ye.rmSync(e,{recursive:!0,force:!0}),Tc(),{ok:!0}}catch(n){return{ok:!1,error:n.message}}}function Z0(t){if(!t)return[];let e=t.toLowerCase(),n=[];for(let s of _t){if(!s.enabled||!s.triggers||s.triggers.length===0)continue;if(s.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(s.instructions||"").split(`
|
|
95
95
|
`).slice(0,3).join(`
|
|
96
|
-
`);n.push({name:s.name,instructions:r})}}return n}
|
|
96
|
+
`);n.push({name:s.name,instructions:r})}}return n}Cf.exports={initSkillsDir:kf,loadAllSkills:Tc,getSkillInstructions:F0,getSkillCommands:U0,getSkillToolDefinitions:B0,routeSkillCall:W0,handleSkillCommand:H0,listSkills:K0,enableSkill:Y0,disableSkill:G0,getLoadedSkills:z0,installSkill:X0,searchSkills:V0,removeSkill:J0,matchSkillTriggers:Z0,_getSkillsDir:Io,_validateScriptSkill:Tf,_loadMarkdownSkill:Sc,_loadScriptSkill:kc,_parseFrontmatter:Rf}});var xi=oe((rR,Lf)=>{var{spawn:Q0}=require("child_process"),eb=require("path"),Af=require("fs"),An=new Map;function tb(){return eb.join(process.cwd(),".nex","config.json")}function Rc(){let t=tb();if(!Af.existsSync(t))return{};try{return JSON.parse(Af.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function _i(t,e,n={},s=1e4){return new Promise((o,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:n})+`
|
|
97
97
|
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},s);function d(p){l+=p.toString();let g=l.split(`
|
|
98
|
-
`);for(let m of g)if(m.trim())try{let h=JSON.parse(m);if(h.id===i){f(),h.error?r(new Error(`MCP error: ${h.error.message||JSON.stringify(h.error)}`)):o(h.result);return}}catch{}l=g[g.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(p){f(),r(new Error(`MCP write failed: ${p.message}`))}})}async function
|
|
99
|
-
`):JSON.stringify(o)}function
|
|
100
|
-
Available tools: ${f.join(", ")}`}}if(!n||!n.properties)return{valid:!0};let s=n.required||[],o=Object.keys(n.properties),r=Object.keys(e),i=[],c={...e},l=!1;for(let d of s)if(!(d in e)||e[d]===void 0||e[d]===null){let f=
|
|
98
|
+
`);for(let m of g)if(m.trim())try{let h=JSON.parse(m);if(h.id===i){f(),h.error?r(new Error(`MCP error: ${h.error.message||JSON.stringify(h.error)}`)):o(h.result);return}}catch{}l=g[g.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(p){f(),r(new Error(`MCP write failed: ${p.message}`))}})}async function Of(t,e){if(An.has(t))return An.get(t);let n=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],s={};for(let i of n)process.env[i]&&(s[i]=process.env[i]);let o=Q0(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...s,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await _i(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await _i(o,"tools/list",{});return r.tools=i&&i.tools||[],An.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Nf(t){let e=An.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return An.delete(t),!0}function nb(){for(let[t]of An)Nf(t)}async function Mf(t,e,n={}){let s=An.get(t);if(!s)throw new Error(`MCP server not connected: ${t}`);let o=await _i(s.proc,"tools/call",{name:e,arguments:n});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
99
|
+
`):JSON.stringify(o)}function Pf(){let t=[];for(let[e,n]of An)for(let s of n.tools)t.push({server:e,name:s.name,description:s.description||"",inputSchema:s.inputSchema||{type:"object",properties:{}}});return t}function sb(){return Pf().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function ob(t,e){if(!t.startsWith("mcp_"))return null;let n=t.substring(4).split("_");if(n.length<2)return null;let s=n[0],o=n.slice(1).join("_");return Mf(s,o,e)}function rb(){let t=Rc();return Object.entries(t).map(([e,n])=>{let s=An.get(e);return{name:e,command:n.command,connected:!!s,toolCount:s?s.tools.length:0}})}async function ib(){let t=Rc(),e=[];for(let[n,s]of Object.entries(t))try{let o=await Of(n,s);e.push({name:n,tools:o.tools.length})}catch(o){e.push({name:n,tools:0,error:o.message})}return e}Lf.exports={loadMCPConfig:Rc,sendRequest:_i,connectServer:Of,disconnectServer:Nf,disconnectAll:nb,callTool:Mf,getAllTools:Pf,getMCPToolDefinitions:sb,routeMCPCall:ob,listServers:rb,connectAll:ib}});var Si=oe((iR,qf)=>{var If=require("fs"),Cc=require("path"),vi=[],jo=[],ds={},Do=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function jf(t,e){if(!t||!t.function||!t.function.name)return{ok:!1,error:"Tool definition must have function.name"};if(typeof e!="function")return{ok:!1,error:"Handler must be a function"};let n=t.function.name;return jo.some(s=>s.definition.function.name===n)?{ok:!1,error:`Tool "${n}" is already registered`}:(jo.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function Df(t,e){return Do.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(ds[t]||(ds[t]=[]),ds[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${Do.join(", ")}`}}async function Ac(t,e){let n=ds[t]||[],s=e;for(let o of n)try{let r=await o(s);r!==void 0&&(s=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return s}function ab(){let t=Cc.join(process.cwd(),".nex","plugins"),e=[];if(!If.existsSync(t))return{loaded:0,errors:[]};let n=If.readdirSync(t).filter(o=>o.endsWith(".js")),s={registerTool:jf,registerHook:Df,EVENTS:Do};for(let o of n){let r=Cc.join(t,o);try{let i=require(r);if(typeof i=="function")i(s);else if(typeof i.setup=="function")i.setup(s);else{e.push(`${o}: Plugin must export a function or { setup: function }`);continue}vi.push({name:i.name||Cc.basename(o,".js"),filePath:r})}catch(i){e.push(`${o}: ${i.message}`)}}return{loaded:vi.length,errors:e}}function cb(){return jo.map(t=>t.definition)}async function lb(t,e,n={}){let s=jo.find(c=>c.definition.function.name===t);if(!s)return null;let o=await Ac("beforeToolExec",{name:t,args:e,options:n}),r=await s.handler(o.args||e,n);return(await Ac("afterToolExec",{name:t,args:e,result:r})).result||r}function ub(){return[...vi]}function db(){let t={};for(let e of Do)t[e]=(ds[e]||[]).length;return t}function fb(){vi.length=0,jo.length=0;for(let t of Object.keys(ds))delete ds[t]}qf.exports={registerTool:jf,registerHook:Df,emit:Ac,loadPlugins:ab,getPluginToolDefinitions:cb,executePluginTool:lb,getLoadedPlugins:ub,getHookCounts:db,clearPlugins:fb,EVENTS:Do}});var Oc=oe((aR,Wf)=>{var{getSkillToolDefinitions:pb}=Cn(),{getMCPToolDefinitions:mb}=xi(),{getPluginToolDefinitions:hb}=Si(),ki=new Map;function Ff(){let{TOOL_DEFINITIONS:t}=en();return[...t,...pb(),...mb(),...hb()]}function Uf(t){if(ki.has(t))return ki.get(t);let n=Ff().find(o=>o.function.name===t);if(!n)return null;let s=n.function.parameters;return ki.set(t,s),s}function gb(){ki.clear()}function Ei(t,e){if(!t||e.length===0)return null;let n=null,s=1/0;for(let o of e){let r=Bf(t.toLowerCase(),o.toLowerCase());r<s&&(s=r,n=o)}return s<=Math.ceil(t.length/2)?n:null}function Bf(t,e){let n=t.length,s=e.length,o=Array.from({length:n+1},()=>Array(s+1).fill(0));for(let r=0;r<=n;r++)o[r][0]=r;for(let r=0;r<=s;r++)o[0][r]=r;for(let r=1;r<=n;r++)for(let i=1;i<=s;i++)o[r][i]=t[r-1]===e[i-1]?o[r-1][i-1]:1+Math.min(o[r-1][i],o[r][i-1],o[r-1][i-1]);return o[n][s]}function $b(t,e){let n=Uf(t);if(n===null){let f=Ff().map(g=>g.function.name),p=Ei(t,f);return{valid:!1,error:`Unknown tool "${t}".${p?` Did you mean "${p}"?`:""}
|
|
100
|
+
Available tools: ${f.join(", ")}`}}if(!n||!n.properties)return{valid:!0};let s=n.required||[],o=Object.keys(n.properties),r=Object.keys(e),i=[],c={...e},l=!1;for(let d of s)if(!(d in e)||e[d]===void 0||e[d]===null){let f=Ei(d,r);f&&!o.includes(f)?(c[d]=e[f],delete c[f],l=!0):i.push(`Missing required parameter "${d}" (${n.properties[d]?.description||n.properties[d]?.type||"unknown"})`)}new Set(["grep","grep_search","search_files"]).has(t)&&(("-n"in c||"n"in c)&&!o.includes("-n")&&(delete c["-n"],delete c.n,l=!0),("-i"in c||"--ignore-case"in c)&&"ignore_case"in(n.properties||{})&&(c.ignore_case=!0,delete c["-i"],delete c["--ignore-case"],l=!0),("-r"in c||"--recursive"in c)&&(delete c["-r"],delete c["--recursive"],l=!0)),t==="read_file"&&("offset"in c&&!("line_start"in c)&&(c.line_start=c.offset,delete c.offset,l=!0),"start_line"in c&&!("line_start"in c)&&(c.line_start=c.start_line,delete c.start_line,l=!0),"end_line"in c&&!("line_end"in c)&&(c.line_end=c.end_line,delete c.end_line,l=!0));for(let d of Object.keys(c))if(!o.includes(d)){let f=Ei(d,o);if(f&&!(f in c))c[f]=c[d],delete c[d],l=!0;else if(!l){let p=f?` Did you mean "${f}"?`:"";i.push(`Unknown parameter "${d}".${p}`)}}for(let d of Object.keys(c)){if(!n.properties[d])continue;let f=n.properties[d].type,p=typeof c[d];f==="string"&&p==="number"?(c[d]=String(c[d]),l=!0):f==="number"&&p==="string"&&!isNaN(c[d])?(c[d]=Number(c[d]),l=!0):f==="boolean"&&p==="string"&&(c[d]=c[d]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
|
|
101
101
|
`+i.map(d=>` - ${d}`).join(`
|
|
102
102
|
`)+`
|
|
103
103
|
|
|
104
|
-
Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}function
|
|
104
|
+
Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}function yb(t,e){let n=[],s={...t};if(!s.function&&!s.name)return n.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:s,errors:n};if(!s.function&&s.name&&(s.function={name:s.name,arguments:s.arguments||s.args||{}},delete s.name,delete s.args),s.function&&s.function.args!==void 0&&s.function.arguments===void 0&&(s.function.arguments=s.function.args,delete s.function.args),s.function&&(s.function.arguments===void 0||s.function.arguments===null)&&(s.function.arguments={}),s.function&&typeof s.function.arguments=="string"){let o=s.function.arguments;if(o.trim()==="")s.function.arguments={};else try{s.function.arguments=JSON.parse(o)}catch(r){return n.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:s,errors:n}}}return s.function&&typeof s.function.arguments!="object"?(n.push(`Arguments must be an object, got ${typeof s.function.arguments}`),{valid:!1,normalized:s,errors:n}):!s.function.name||typeof s.function.name!="string"?(n.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:s,errors:n}):{valid:n.length===0,normalized:s,errors:n}}Wf.exports={validateToolArgs:$b,validateToolCallFormat:yb,closestMatch:Ei,levenshtein:Bf,getCachedSchema:Uf,clearSchemaCache:gb}});var Gf=oe((cR,Yf)=>{var{levenshtein:Ti}=Oc(),wb=200,bb=.3,_b=2;function Nc(t){return t.replace(/\r\n/g,`
|
|
105
105
|
`).replace(/\r/g,`
|
|
106
|
-
`).replace(/\t/g," ".repeat(
|
|
106
|
+
`).replace(/\t/g," ".repeat(_b)).split(`
|
|
107
107
|
`).map(e=>{let n=e.replace(/\s+$/,""),s=n.match(/^(\s*)(.*)/);if(!s)return n;let[,o,r]=s;return o+r.replace(/ {2,}/g," ")}).join(`
|
|
108
|
-
`)}function
|
|
108
|
+
`)}function xb(t,e){if(t.includes(e))return e;if(e.length<10)return null;let n=Nc(t),s=Nc(e);if(!n.includes(s))return null;let o=t.split(`
|
|
109
109
|
`),r=n.split(`
|
|
110
110
|
`),i=s.split(`
|
|
111
111
|
`),c=i[0],l=i[i.length-1];for(let u=0;u<=r.length-i.length;u++){let d=!0;for(let f=0;f<i.length;f++)if(r[u+f]!==i[f]){d=!1;break}if(d)return o.slice(u,u+i.length).join(`
|
|
112
|
-
`)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(s)!==-1)return o[u]}return null}function
|
|
112
|
+
`)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(s)!==-1)return o[u]}return null}function vb(t,e){if(!t||!e)return null;let n=t.split(`
|
|
113
113
|
`),o=e.split(`
|
|
114
|
-
`).length;return n.length===0||o===0?null:o===1?
|
|
115
|
-
`),u=
|
|
116
|
-
`),g=
|
|
117
|
-
`),s=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],c=r+1;for(let l of
|
|
118
|
-
`).filter(Boolean),
|
|
119
|
-
`);for(let o=0;o<s.length;o++){let r=s[o],i=o+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let c=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);c&&n.push({type:"function",name:c[1],line:i});let l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let u=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);u&&n.push({type:"function",name:u[1],line:i});let d=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(d){let p=d[1].split(",").map(g=>g.trim().split(":")[0].trim()).filter(Boolean);for(let g of p)/^\w+$/.test(g)&&n.push({type:"export",name:g,line:i})}let f=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(f){let p=f[1]||f[2];n.push({type:"import",name:p,line:i})}}if(e===".py"){let c=r.match(/^(?:async\s+)?def\s+(\w+)/);c&&n.push({type:"function",name:c[1],line:i});let l=r.match(/^class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let u=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);u&&n.push({type:"import",name:u[1]||u[2],line:i})}if(e===".go"){let c=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);c&&n.push({type:"function",name:c[1],line:i});let l=r.match(/^type\s+(\w+)\s+struct/);l&&n.push({type:"class",name:l[1],line:i})}}return n}async function
|
|
114
|
+
`).length;return n.length===0||o===0?null:o===1?Sb(n,e):Eb(n,e,o)}function Hf(t){return Math.max(1,Math.floor(t/wb))}function Kf(t,e){return t<=Math.ceil(e*bb)}function Sb(t,e){let n=e.trim(),s=Hf(t.length),o=null,r=1/0;for(let i=0;i<t.length;i+=s){let c=t[i];if(!c.trim())continue;let l=Ti(c.trim(),n);l<r&&(r=l,o={text:c,distance:l,line:i+1})}return o&&s>1&&(o=kb(t,n,o,s)||o,r=o.distance),Kf(r,e.length)?o:null}function kb(t,e,n,s){let o=n.line-1,r=Math.max(0,o-s),i=Math.min(t.length-1,o+s),c=n.distance,l=null;for(let u=r;u<=i;u++){let d=t[u];if(!d.trim())continue;let f=Ti(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function Eb(t,e,n){let s=t.length-n+1;if(s<=0)return null;let o=Hf(s),r=null,i=1/0;for(let c=0;c<s;c+=o){let l=t.slice(c,c+n).join(`
|
|
115
|
+
`),u=Ti(l,e);u<i&&(i=u,r={text:l,distance:u,line:c+1})}return r&&o>1&&(r=Tb(t,e,r,o,n,s)||r,i=r.distance),Kf(i,e.length)?r:null}function Tb(t,e,n,s,o,r){let i=n.line-1,c=Math.max(0,i-s),l=Math.min(r-1,i+s),u=n.distance,d=null;for(let f=c;f<=l;f++){let p=t.slice(f,f+o).join(`
|
|
116
|
+
`),g=Ti(p,e);g<u&&(u=g,d={text:p,distance:g,line:f+1})}return d}Yf.exports={normalizeWhitespace:Nc,fuzzyFindText:xb,findMostSimilar:vb}});var Xf=oe((uR,zf)=>{var{C:lR}=Ke(),Rb=[{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}],Cb=[{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 Ab(t,e){let n=e.split(`
|
|
117
|
+
`),s=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],c=r+1;for(let l of Rb)l.regex.test(i)&&s.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of Cb)l.ext&&!l.ext.includes(o)||l.regex.test(i)&&s.push({line:c,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return n.length>500&&s.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),s}function Ob(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}zf.exports={runDiagnostics:Ab,getMemoryUsage:Ob}});var jc=oe((dR,tp)=>{var no=require("fs").promises,so=require("path"),{exec:Nb}=require("util").promisify(require("child_process").exec),oo=[],Ic=null,Ri=!1,Pc=0,Mb=6e4;function Jf(t){return!(oo.length===0||Ic!==t||Date.now()-Pc>Mb)}async function Zf(t){if(!Ri&&!Jf(t)){Ri=!0,Ic=t;try{try{let{stdout:s}=await Nb("rg --files",{cwd:t,timeout:5e3});oo=s.split(`
|
|
118
|
+
`).filter(Boolean),Pc=Date.now(),Ri=!1;return}catch{}let e=[],n=async(s,o)=>{let r;try{r=await no.readdir(s,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let c=o?`${o}/${i.name}`:i.name;i.isDirectory()?await n(so.join(s,i.name),c):e.push(c)}};await n(t,""),oo=e,Pc=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Ri=!1}}}function Lc(){return oo}function Pb(){return Ic}function Lb(t){return oo.filter(e=>so.basename(e)===t)}function Ib(t){let e=t.toLowerCase();return oo.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}var Mc=null,Vf=0,jb=12e4,Db=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function Qf(t,e){let n=[],s=t.split(`
|
|
119
|
+
`);for(let o=0;o<s.length;o++){let r=s[o],i=o+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let c=r.match(/(?:export\s+)?(?:async\s+)?function\s+(\w+)/);c&&n.push({type:"function",name:c[1],line:i});let l=r.match(/(?:export\s+)?class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let u=r.match(/(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s+)?(?:\([^)]*\)|[\w$]+)\s*=>/);u&&n.push({type:"function",name:u[1],line:i});let d=r.match(/module\.exports\s*=\s*\{([^}]+)\}/);if(d){let p=d[1].split(",").map(g=>g.trim().split(":")[0].trim()).filter(Boolean);for(let g of p)/^\w+$/.test(g)&&n.push({type:"export",name:g,line:i})}let f=r.match(/(?:require\(['"]([^'"]+)['"]\)|from\s+['"]([^'"]+)['"])/);if(f){let p=f[1]||f[2];n.push({type:"import",name:p,line:i})}}if(e===".py"){let c=r.match(/^(?:async\s+)?def\s+(\w+)/);c&&n.push({type:"function",name:c[1],line:i});let l=r.match(/^class\s+(\w+)/);l&&n.push({type:"class",name:l[1],line:i});let u=r.match(/^(?:from\s+(\S+)\s+)?import\s+(\S+)/);u&&n.push({type:"import",name:u[1]||u[2],line:i})}if(e===".go"){let c=r.match(/^func\s+(?:\([^)]+\)\s+)?(\w+)/);c&&n.push({type:"function",name:c[1],line:i});let l=r.match(/^type\s+(\w+)\s+struct/);l&&n.push({type:"class",name:l[1],line:i})}}return n}async function ep(t){t=t||process.cwd();let e=so.join(t,".nex","index","content-index.json"),n={};if(Mc&&Date.now()-Vf<jb)return Mc;try{let i=await no.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}Lc().length===0&&await Zf(t);let o={files:{}},r=!1;for(let i of Lc()){let c=so.extname(i);if(!Db.has(c))continue;let l=so.join(t,i);try{let d=(await no.stat(l)).mtimeMs;if(n.files[i]&&n.files[i].mtime===d){o.files[i]=n.files[i];continue}let f=await no.readFile(l,"utf-8"),p=Qf(f,c);o.files[i]={defs:p,mtime:d},r=!0}catch{}}if(r){let i=so.join(t,".nex","index");await no.mkdir(i,{recursive:!0}),await no.writeFile(e,JSON.stringify(o),"utf-8")}return Mc=o,Vf=Date.now(),o}async function qb(t,e){let n=await ep(),s=[],o=t.toLowerCase();for(let[r,i]of Object.entries(n.files))for(let c of i.defs)e&&c.type!==e||c.name.toLowerCase().includes(o)&&s.push({file:r,type:c.type,name:c.name,line:c.line});return s.sort((r,i)=>{let c=r.name.toLowerCase()===o?0:1,l=i.name.toLowerCase()===o?0:1;if(c!==l)return c-l;let u=r.name.toLowerCase().startsWith(o)?0:1,d=i.name.toLowerCase().startsWith(o)?0:1;return u-d}),s.slice(0,50)}tp.exports={refreshIndex:Zf,getFileIndex:Lc,getIndexedCwd:Pb,findFileInIndex:Lb,searchIndex:Ib,isIndexValid:Jf,buildContentIndex:ep,searchContentIndex:qb,extractDefinitions:Qf}});var ro=oe((fR,rp)=>{var Ci=require("fs"),Oi=require("path"),Ni=require("os"),{execFile:Fb}=require("child_process"),{promisify:Ub}=require("util"),Dc=Ub(Fb),Bb=Oi.join(Ni.homedir(),".nex","servers.json"),Ai=Oi.join(Ni.tmpdir(),"nex-ssh-sockets");function Wb(){return Oi.join(process.cwd(),".nex","servers.json")}function np(){let t=s=>{if(!Ci.existsSync(s))return{};try{return JSON.parse(Ci.readFileSync(s,"utf-8"))}catch{return{}}},e=t(Bb),n=t(Wb());return{...e,...n}}function Hb(t){let e=np();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:o}}let n=Object.keys(e),s=n.length?`Available profiles: ${n.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${s}`)}function Kb(){Ci.existsSync(Ai)||Ci.mkdirSync(Ai,{recursive:!0})}function sp(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Ni.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),Kb();let n=t.user?`${t.user}@${t.host}`:t.host,s=Oi.join(Ai,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${s}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function op(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,Ni.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Yb(t,e,{timeout:n=3e4,sudo:s=!1}={}){let{args:o}=sp(t),r=s&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:c}=await Dc("ssh",[...o,r],{timeout:n,maxBuffer:4194304});return{stdout:i||"",stderr:c||"",exitCode:0}}catch(i){let c=typeof i.code=="number"?i.code:1,l=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:l,exitCode:c,error:Mi(l,t)}}}async function Gb(t,e,n,{timeout:s=12e4}={}){let o=op(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${n}`);try{let{stdout:i,stderr:c}=await Dc("scp",o,{timeout:s,maxBuffer:1048576});return i||c||`Uploaded ${e} \u2192 ${r}:${n}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(Mi(c,t)||c)}}async function zb(t,e,n,{timeout:s=12e4}={}){let o=op(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,n);try{let{stdout:i,stderr:c}=await Dc("scp",o,{timeout:s,maxBuffer:1048576});return i||c||`Downloaded ${r}:${e} \u2192 ${n}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(Mi(c,t)||c)}}function Mi(t,e){if(!t)return"";if(/connection refused/i.test(t)){let n=e.port||22;return`${t}
|
|
120
120
|
HINT: Connection refused on ${e.host}:${n}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${n} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let n=e.key?`key: ${e.key}`:"SSH agent";return`${t}
|
|
121
121
|
HINT: Auth failed using ${n} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
|
|
122
122
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
123
123
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
124
124
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
125
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function
|
|
126
|
-
`,"utf-8")}
|
|
125
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function Xb(t,e){let n=e.user?`${e.user}@${e.host}`:e.host,s=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${n}${s}${o}${r}${i}`}rp.exports={loadServerProfiles:np,resolveProfile:Hb,buildSSHArgs:sp,sshExec:Yb,scpUpload:Gb,scpDownload:zb,enrichSSHError:Mi,formatProfile:Xb,SSH_SOCKET_DIR:Ai}});var Uc=oe((pR,ap)=>{var qo=require("fs"),qc=require("path"),Vb=qc.join(".nex","deploy.json");function Fc(){return qc.join(process.cwd(),Vb)}function ip(){let t=Fc();if(!qo.existsSync(t))return{};try{return JSON.parse(qo.readFileSync(t,"utf-8"))}catch{return{}}}function Jb(t){let e=ip();if(e[t])return{...e[t],_name:t};let n=Object.keys(e),s=n.length?`Available: ${n.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${s}`)}function Zb(t){let e=qc.join(process.cwd(),".nex");qo.existsSync(e)||qo.mkdirSync(e,{recursive:!0}),qo.writeFileSync(Fc(),JSON.stringify(t,null,2)+`
|
|
126
|
+
`,"utf-8")}ap.exports={loadDeployConfigs:ip,resolveDeployConfig:Jb,saveDeployConfigs:Zb,getDeployConfigPath:Fc}});var Wo=oe((mR,up)=>{var{getActiveModel:Qb,getActiveProviderName:e_}=Be(),Fo={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},Uo={"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"},Bo={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},yn={};function lp(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(yn=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{yn={}}}lp();function Bc(){let e=Qb()?.id,n=e_();return e&&yn[e]?yn[e]:n&&yn[`${n}:*`]?yn[`${n}:*`]:e&&Uo[e]?Uo[e]:n&&Bo[n]?Bo[n]:"full"}var t_=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"]),cp={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function n_(t,e){return t&&(t_.has(t)||t.startsWith("claude-"))?"strict":e&&cp[e]?cp[e]:"fuzzy"}function s_(t,e){return t&&yn[t]?yn[t]:e&&yn[`${e}:*`]?yn[`${e}:*`]:t&&Uo[t]?Uo[t]:e&&Bo[e]?Bo[e]:"full"}function o_(t,e){let n=e||Bc();if(n==="full"||!Fo[n])return t;let s=new Set(Fo[n]);return t.filter(o=>s.has(o.function.name))}function r_(){let t=Bc(),e=Fo[t]?Fo[t].length:"all";return{tier:t,toolCount:e}}up.exports={filterToolsForModel:o_,getActiveTier:Bc,getModelTier:s_,getEditMode:n_,getTierInfo:r_,TIERS:Fo,MODEL_TIERS:Uo,PROVIDER_DEFAULT_TIER:Bo,loadConfigOverrides:lp}});var Ko=oe((hR,pp)=>{var Wc=null,On=null,Ho=null,dp=`Playwright is not installed. Install with:
|
|
127
127
|
npm install playwright && npx playwright install chromium
|
|
128
|
-
Then restart nex-code.`;function
|
|
129
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function
|
|
130
|
-
`)}function
|
|
128
|
+
Then restart nex-code.`;function fp(){if(Ho!==null)return Ho;try{require("playwright"),Ho=!0}catch{Ho=!1}return Ho}async function Pi(){if(!fp())throw new Error(dp);return Wc||(Wc=require("playwright")),(!On||!On.isConnected())&&(On=await Wc.chromium.launch({headless:!0})),On}async function i_(){if(On){try{await On.close()}catch{}On=null}}process.on("exit",()=>{if(On)try{On.close()}catch{}});async function a_(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let o=await(await Pi()).newPage();try{await o.goto(t,{waitUntil:n,timeout:e});let r=await o.title(),i=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),c=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:o.url(),text:i.substring(0,8e3)+(i.length>8e3?`
|
|
129
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function c_(t,{width:e=1280,height:n=800,fullPage:s=!1,timeout:o=3e4}={}){let i=await(await Pi()).newPage();try{await i.setViewportSize({width:e,height:n}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let c=await i.screenshot({type:"png",fullPage:s}),l=require("os"),u=require("path"),d=require("fs"),f=u.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(f,c),{path:f,base64:c.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function l_(t,{selector:e,text:n,timeout:s=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await Pi()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:s}),n?await r.getByText(n,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function u_(t,{selector:e,value:n,submit:s=!1,timeout:o=3e4}={}){if(!e||n===void 0)throw new Error("selector and value are required");let i=await(await Pi()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(n)),s&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${s?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}pp.exports={isPlaywrightAvailable:fp,browserNavigate:a_,browserScreenshot:c_,browserClick:l_,browserFill:u_,closeBrowser:i_,INSTALL_MSG:dp}});var Li=oe((gR,mp)=>{var{C:Ge}=Ke(),Go="",xt=[],Yo=0,fs=null;function d_(t){fs=t}function f_(t,e){Go=t,xt=[],Yo=0;for(let s of e){Yo++;let o=`t${Yo}`;xt.push({id:o,description:s.description||s.title||s.name||s.task||`Task ${Yo}`,status:"pending",dependsOn:s.depends_on||[],result:null})}let n=xt.map(s=>({...s}));return fs&&fs("create",{name:t,tasks:n}),n}function p_(t,e,n){let s=xt.find(o=>o.id===t);return s?(s.status=e,n!==void 0&&(s.result=n),fs&&fs("update",{id:t,status:e,result:n}),{...s}):null}function m_(){return{name:Go,tasks:xt.map(t=>({...t}))}}function h_(){Go="",xt=[],Yo=0,fs&&fs("clear",{})}function g_(){return xt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=xt.find(s=>s.id===e);return n&&n.status==="done"}))}function $_(){if(xt.length===0)return`${Ge.dim}No active tasks${Ge.reset}`;let t=[];Go&&(t.push(` ${Ge.bold}${Ge.cyan}Tasks: ${Go}${Ge.reset}`),t.push(` ${Ge.dim}${"\u2500".repeat(40)}${Ge.reset}`));for(let o of xt){let r,i;switch(o.status){case"done":r="\u2713",i=Ge.green;break;case"in_progress":r="\u2192",i=Ge.cyan;break;case"failed":r="\u2717",i=Ge.red;break;default:r="\xB7",i=Ge.dim}let c=o.dependsOn.length>0?` ${Ge.dim}(after: ${o.dependsOn.join(", ")})${Ge.reset}`:"",l=`[${o.status}]`,u=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${Ge.reset} ${Ge.bold}${o.id}${Ge.reset} ${u.padEnd(40)} ${i}${l}${Ge.reset}${c}`),o.result&&o.status==="done"){let d=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Ge.dim}\u2192 ${d}${Ge.reset}`)}}let e=xt.filter(o=>o.status==="done").length,n=xt.filter(o=>o.status==="failed").length,s=xt.length;return t.push(` ${Ge.dim}${"\u2500".repeat(40)}${Ge.reset}`),t.push(` ${Ge.dim}${e}/${s} done${n>0?`, ${n} failed`:""}${Ge.reset}`),t.join(`
|
|
130
|
+
`)}function y_(){return xt.length>0&&xt.some(t=>t.status==="pending"||t.status==="in_progress")}mp.exports={createTasks:f_,updateTask:p_,getTaskList:m_,clearTasks:h_,getReadyTasks:g_,renderTaskList:$_,setOnChange:d_,hasActiveTasks:y_}});var Ii=oe(($R,gp)=>{var zo={"devstral-2":{staleWarn:3e4,staleAbort:9e4,investigationCap:12,postEditCap:10,briefing:`You are devstral-2, a strong coding model optimized for agentic tasks.
|
|
131
131
|
Use tools confidently and without hesitation \u2014 tool use is the expected workflow.
|
|
132
132
|
You excel at sysadmin, frontend, and multi-step coding tasks.
|
|
133
133
|
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.
|
|
@@ -140,7 +140,7 @@ Focus on correctness over speed.`},"ministral-3":{staleWarn:2e4,staleAbort:6e4,i
|
|
|
140
140
|
Prioritize decisive, targeted edits. Read only what you need, then fix.
|
|
141
141
|
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.
|
|
142
142
|
Trust your reasoning. Use tools thoroughly when the task demands it.
|
|
143
|
-
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},
|
|
143
|
+
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},hp={staleWarn:6e4,staleAbort:12e4,investigationCap:12,postEditCap:10};function w_(t){let e=(t||"").toLowerCase(),n=null,s=0;for(let r of Object.keys(zo))e.startsWith(r)&&r.length>s&&(n=r,s=r.length);let o=n?{...zo[n]}:{...hp};for(let[r,i]of[["NEX_STALE_WARN_MS","staleWarn"],["NEX_STALE_ABORT_MS","staleAbort"]])if(process.env[r]){let c=parseInt(process.env[r],10);Number.isInteger(c)&&c>=1e3&&c<=3e5&&(o[i]=c)}return o}function b_(t){let e=(t||"").toLowerCase(),n=null,s=0;for(let o of Object.keys(zo))e.startsWith(o)&&o.length>s&&(n=o,s=o.length);return n&&zo[n].briefing||""}gp.exports={getModelProfile:w_,getModelBriefing:b_,PROFILES:zo,DEFAULTS:hp}});var Kc=oe((yR,xp)=>{var{callChat:__}=Be(),{estimateTokens:Hc}=Lt(),$p=process.env.NEX_COMPACTION!=="false",yp=6,wp=2e3,bp=3,x_=`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.
|
|
144
144
|
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.
|
|
145
145
|
|
|
146
146
|
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:
|
|
@@ -172,30 +172,30 @@ Format your output as:
|
|
|
172
172
|
|
|
173
173
|
<summary>
|
|
174
174
|
[Sections 1-9 above]
|
|
175
|
-
</summary>`,
|
|
176
|
-
${s}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return
|
|
175
|
+
</summary>`,ps=0;async function v_(t){if(!$p||t.length<yp||ps>=bp)return null;let e=[{role:"system",content:x_},{role:"user",content:_p(t)}];try{let s=((await __(e,[],{temperature:0,maxTokens:wp})).content||"").trim();if(!s)return ps++,null;let o=s.match(/<summary>([\s\S]*?)<\/summary>/);if(o?s=o[1].trim():s=s.replace(/<analysis>[\s\S]*?<\/analysis>/g,"").trim(),!s)return ps++,null;let r=t.reduce((c,l)=>c+Hc(l.content||"")+(l.tool_calls?Hc(JSON.stringify(l.tool_calls)):0),0),i=Hc(s);return i>=r*.8?(ps++,null):(ps=0,{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
176
|
+
${s}`,_compacted:!0,_originalCount:t.length},tokensRemoved:r-i})}catch{return ps++,null}}function S_(){ps=0}function _p(t){return t.map(e=>{let n=e.role==="tool"?"tool_result":e.role,s=(e.content||"").substring(0,500);if(e.tool_calls){let o=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${n}] ${s}
|
|
177
177
|
tools: ${o}`}return`[${n}] ${s}`}).join(`
|
|
178
178
|
|
|
179
|
-
`)}
|
|
180
|
-
`);if(o.length<=10){let m=Math.floor(s*.6),h=Math.floor(s*.4),y=t.substring(0,m),
|
|
179
|
+
`)}xp.exports={compactMessages:v_,formatMessagesForSummary:_p,resetCompactionFailures:S_,COMPACTION_ENABLED:$p,COMPACTION_MIN_MESSAGES:yp,COMPACTION_SUMMARY_BUDGET:wp,MAX_CONSECUTIVE_FAILURES:bp}});var Lt=oe((wR,Np)=>{var k_=require("path");function Sp(){return Be().getActiveModel()}var E_={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},T_={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},ms=new Map,vp=1e3,Yc=new WeakMap,hs=null;function R_(){if(hs!==null)return hs;try{let t=Sp(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[s,o]of Object.entries(T_))if(n.startsWith(s))return hs=o,hs;return hs=E_[e]||4,hs}catch{return 4}}function C_(){hs=null}function gs(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=120?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length>>1,(t.length>>1)+30)}:${t.substring(t.length-30)}`,n=ms.get(e);if(n!==void 0)return ms.delete(e),ms.set(e,n),n;let s=Math.ceil(t.length/R_());if(ms.size>=vp){let o=vp>>1,r=ms.keys();for(let i=0;i<o;i++)ms.delete(r.next().value)}return ms.set(e,s),s}function A_(t){if(Yc.has(t))return Yc.get(t);let e=JSON.stringify(t);return Yc.set(t,e),e}function co(t){let n=4;if(t.content&&(n+=gs(t.content)),t.tool_calls)for(let s of t.tool_calls){n+=4,n+=gs(s.function?.name||"");let o=s.function?.arguments;typeof o=="string"?n+=gs(o):o&&(n+=gs(JSON.stringify(o)))}return n}function Gt(t){let e=0;for(let n of t)e+=co(n);return e}function O_(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let n=t?t.length:0,s=e.length,o=0;for(let r=n;r<s;r++)o+=co(e[r]);return o}function ji(t){return!t||t.length===0?0:gs(JSON.stringify(t))}function Di(){return Sp()?.contextWindow||32768}function N_(t,e){let n=Gt(t),s=ji(e),o=n+s,r=Di(),i=r>0?o/r*100:0,c=0,l=0,u=0;for(let d of t){let f=co(d);d.role==="system"?c+=f:d.role==="tool"?u+=f:l+=f}return{used:o,limit:r,percentage:Math.round(i*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:s},messageCount:t.length}}var Xo=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,kp=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,Ep=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Tp={essential:.6,standard:.65,full:Math.min(Xo,.68)};function Rp(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Xo;try{let{getActiveTier:t}=Wo(),e=t();return Tp[e]??Xo}catch{return Xo}}var M_=200,P_=1e3;function Cp(t,e){if(!t||t.length<=e)return t;let s=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=s)return t;let o=t.split(`
|
|
180
|
+
`);if(o.length<=10){let m=Math.floor(s*.6),h=Math.floor(s*.4),y=t.substring(0,m),b=t.substring(t.length-h);return y+`
|
|
181
181
|
...(${t.length} chars total)...
|
|
182
|
-
`+
|
|
182
|
+
`+b}let r=Math.floor(o.length*.4),i=Math.floor(o.length*.4),c=[],l=0,u=Math.floor(s*.4);for(let m=0;m<r&&l<u;m++)if(l+o[m].length+1>u&&o[m].trim().startsWith("```")){c.push(o[m]),l+=o[m].length+1;let h=m+1;for(;h<o.length&&l<u*1.5&&!o[h].trim().startsWith("```");)c.push(o[h]),l+=o[h].length+1,h++;h<o.length&&o[h].trim().startsWith("```")&&(c.push(o[h]),l+=o[h].length+1),m=h}else c.push(o[m]),l+=o[m].length+1;let d=[],f=0,p=Math.floor(s*.4);for(let m=o.length-1;m>=o.length-i&&f<p;m--)if(f+o[m].length+1>p&&o[m].trim().startsWith("```")){d.push(o[m]),f+=o[m].length+1;let h=m-1;for(;h>=0&&f<p*1.5&&!o[h].trim().startsWith("```");)d.push(o[h]),f+=o[h].length+1,h--;h>=0&&o[h].trim().startsWith("```")&&(d.push(o[h]),f+=o[h].length+1),m=h}else d.push(o[m]),f+=o[m].length+1;d.reverse();let g=o.length-c.length-d.length;return c.join(`
|
|
183
183
|
`)+`
|
|
184
184
|
...(${g} lines omitted, ${o.length} total)...
|
|
185
185
|
`+d.join(`
|
|
186
|
-
`)}function
|
|
187
|
-
...(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
|
|
186
|
+
`)}function ao(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:P_,s=e==="aggressive"?50:e==="medium"?100:M_;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>s?{...t,content:Cp(o,s)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>n&&(o.content=o.content.substring(0,n)+`
|
|
187
|
+
...(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 Ap(t,e,n,s){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=n>1?e/(n-1):1;if(o+=Math.round(r*30),s&&s.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),c=0;for(let l of s)(i.includes(l)||i.includes(k_.basename(l)))&&c++;o+=Math.min(30,c*10)}return Math.min(100,o)}function Op(t,e=10){let n=new Set,s=t.slice(-e),o=/(?:\/[\w.-]+)+\.\w+/g;for(let r of s){let c=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(o);c&&c.forEach(l=>n.add(l))}return n}function L_(t,{filesModified:e=new Set,currentPhase:n=null}={}){let s=[];if(e.size>0){let r=[...e].map(i=>i.split("/").slice(-2).join("/")).join(", ");s.push(`Files already modified: ${r} \u2014 do NOT rewrite these, use edit_file for additions only.`)}n&&s.push(`Current phase: ${n}`);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&&s.push(`Recent progress:
|
|
188
188
|
`+o.map(r=>`- ${r}`).join(`
|
|
189
189
|
`)),s.length===0?null:{role:"system",content:`## Progress State (preserved through compression)
|
|
190
190
|
${s.join(`
|
|
191
|
-
`)}`,_pinned:!0,_progressSnapshot:!0}}var
|
|
191
|
+
`)}`,_pinned:!0,_progressSnapshot:!0}}var io={msgCount:-1,lastMsgRef:null,result:null};function I_(){io={msgCount:-1,lastMsgRef:null,result:null}}async function j_(t,e,n={}){let s=t.length>0?t[t.length-1]:null;if(!n.force&&io.result&&t.length===io.msgCount&&s===io.lastMsgRef)return io.result;let o=n.threshold??Rp(),r=n.safetyMargin??kp,i=n.keepRecent??Ep,c=Di(),l=ji(e),u=Math.floor(c*(o-r)),d=u-l,f=Gt(t),p=f+l;if(p<=u){let Q={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return io={msgCount:t.length,lastMsgRef:s,result:Q},Q}let g=f,m=null,h=0;t.length>0&&t[0].role==="system"&&(m=t[0],h=1);let y=Math.max(h,t.length-i),b=t.slice(h,y),S=t.slice(y),C=b.filter(Q=>Q._pinned),k=b.filter(Q=>!Q._compacted&&!Q._pinned);if(k.length>=6)try{let{compactMessages:Q}=Kc(),O=await Q(k);if(O){let Te=b.filter(he=>he._compacted&&!he._pinned),X=[...C,...Te,O.message],V=Wn(m,X,S),fe=Gt(V);if(fe+l<=u)return{messages:V,compressed:!0,compacted:!0,tokensRemoved:g-fe};b=X}}catch(Q){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",Q.message)}let x=(p-u)/u,E=b.map(Q=>ao(Q,"light")),B=Wn(m,E,S),q=Gt(B);if(q+l<=u)return{messages:B,compressed:!0,compacted:!1,tokensRemoved:g-q};if(E=b.map(Q=>ao(Q,"medium")),B=Wn(m,E,S),q=Gt(B),q+l<=u)return{messages:B,compressed:!0,compacted:!1,tokensRemoved:g-q};if(E=b.map(Q=>ao(Q,"aggressive")),B=Wn(m,E,S),q=Gt(B),q+l<=u)return{messages:B,compressed:!0,compacted:!1,tokensRemoved:g-q};let re=Op([...E,...S]),ie=E.map((Q,O)=>({msg:Q,score:Q._pinned?1/0:Ap(Q,O,E.length,re),tokens:co(Q)}));for(;ie.length>0&&q>d;){let Q=-1;for(let O=0;O<ie.length;O++)ie[O].score!==1/0&&(Q===-1||ie[O].score<ie[Q].score)&&(Q=O);if(Q===-1)break;q-=ie[Q].tokens,ie.splice(Q,1)}return E=ie.map(Q=>Q.msg),B=Wn(m,E,S),q=Gt(B),{messages:B,compressed:!0,compacted:!1,tokensRemoved:g-q}}function Wn(t,e,n){let s=[];return t&&s.push(t),s.push(...e,...n),s}function D_(t,e){if(!t)return"";if(gs(t)<=e)return t;let s=e*4,o=t.split(`
|
|
192
192
|
`),r=Math.floor(s*.6),i=Math.floor(s*.4),c="",l=0;for(let g of o){if(c.length+g.length+1>r)break;c+=(c?`
|
|
193
193
|
`:"")+g,l++}let u="",d=0;for(let g=o.length-1;g>=l;g--){let m=o[g]+(u?`
|
|
194
194
|
`:"")+u;if(m.length>i)break;u=m,d++}let p=`
|
|
195
195
|
|
|
196
196
|
... (${o.length-l-d} lines omitted, ${o.length} total) ...
|
|
197
197
|
|
|
198
|
-
`;return c+p+u}var
|
|
198
|
+
`;return c+p+u}var q_=6;function F_(t,e,n=!1){let s=Di(),o=ji(e),r=Math.floor(s*(n?.35:.5))-o,i=Gt(t),c=Math.floor(i*(n?.5:.8));r>c&&(r=c);let l=null,u=0;t.length>0&&t[0].role==="system"&&(l=t[0],u=1);let d=n?2:q_,f=Math.max(u,t.length-d),p=t.slice(u,f),g=t.slice(f),m=p.map(x=>ao(x,"aggressive"));n&&(g=g.map(x=>ao(x,"aggressive")));let h=Wn(l,m,g),y=Gt(h);for(;m.length>0&&y>r;){let x=m.shift();y-=co(x)}n&&y>r&&(g=g.filter(E=>E.role==="user").slice(-1),h=Wn(l,[],g),y=Gt(h)),h=Wn(l,m,g);let b=t.filter(x=>x.role==="user"),S=x=>{let E=typeof x.content=="string"?x.content:"";return E.startsWith("[SYSTEM WARNING]")||E.startsWith("[SYSTEM:")||E.startsWith("BLOCKED:")},C=b.find(x=>!S(x)),k=[...b].reverse().find(x=>!S(x));if(C&&!h.find(x=>x===C)){let x=h.findIndex(B=>B.role==="system"),E=x>=0?x+1:0;h.splice(E,0,C)}return k&&k!==C&&!h.find(x=>x===k)&&h.push(k),{messages:h,tokensRemoved:i-Gt(h)}}Np.exports={estimateTokens:gs,estimateMessageTokens:co,estimateMessagesTokens:Gt,estimateDeltaTokens:O_,estimateToolsTokens:ji,serializeMessage:A_,getContextWindow:Di,getUsage:N_,compressMessage:ao,compressToolResult:Cp,scoreMessageRelevance:Ap,extractActiveFiles:Op,buildProgressSnapshot:L_,fitToContext:j_,forceCompress:F_,truncateFileContent:D_,invalidateTokenRatioCache:C_,invalidateFitToContextCache:I_,getEffectiveCompressionThreshold:Rp,COMPRESSION_THRESHOLD:Xo,TIER_COMPRESSION_THRESHOLDS:Tp,SAFETY_MARGIN:kp,KEEP_RECENT:Ep}});var Bi=oe((_R,em)=>{var{callStream:U_,getActiveProviderName:Fi,getActiveModelId:Mp,getConfiguredProviders:B_,getProvider:Pp,getActiveProvider:Lp,parseModelSpec:Ip}=Be(),{parseToolArgs:jp}=eo(),{filterToolsForModel:W_,getModelTier:qi}=Wo(),{getModelBriefing:H_}=Ii(),{trackUsage:Dp,estimateTokens:qp}=Qs(),{MultiProgress:K_,C:bR}=Ke();function Fp(t){return!t||typeof t!="string"?0:typeof qp=="function"?qp(t):Math.ceil(t.length/4)}var Wp=15,Y_=parseInt(process.env.NEX_MAX_PARALLEL||"5",10),Up=parseInt(process.env.NEX_MAX_CHAT_RETRIES||"3",10),Hp=8,G_=2,Ui=new Map,Kp=600*1e3;function z_(t,e){let n=Ui.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<Kp?!1:(Ui.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Vo(t){Ui.delete(t)}function Gc(){Ui.clear()}function zc(t){let e=(t.message||"").toLowerCase(),n=t.code||"";return e.includes("429")||e.includes("rate limit")?"rate_limit":e.includes("401")||e.includes("403")||e.includes("unauthorized")||e.includes("forbidden")?"auth":e.includes("context")&&(e.includes("too long")||e.includes("overflow")||e.includes("maximum"))||e.includes("400")&&(e.includes("content")||e.includes("length"))?"context_overflow":e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")?"server":e.includes("timed out")||e.includes("timeout")?"timeout":n==="ECONNRESET"||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ENOTFOUND"||e.includes("socket disconnected")||e.includes("tls")||e.includes("econnreset")||e.includes("fetch failed")||e.includes("etimedout")||e.includes("enotfound")?"network":"unknown"}function Yp(t){let e=zc(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function Gp(t,e,n){let s;for(let o=0;o<=Up;o++)try{return await U_(t,e,n)}catch(r){s=r;let i=zc(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(o<Up&&Yp(r)){let l=i==="rate_limit"?Math.min(2e3*Math.pow(2,o),15e3):Math.min(500*Math.pow(2,o),4e3);await new Promise(u=>setTimeout(u,l).unref());continue}throw r}throw s}var Bp=new Set(["ask_user","task_list"]);function zp(t){return t>=2?new Set([...Bp,"spawn_agents"]):Bp}var X_=new Set(["write_file","edit_file","patch_file"]),Xp={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:""}},V_=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,J_=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function Vp(t){return J_.test(t)?"full":V_.test(t)?"essential":t.length>300?"full":"standard"}function Jp(t){let e=B_(),n=Fi(),s=[...e].sort((o,r)=>(o.name===n?-1:1)-(r.name===n?-1:1));for(let o of s)for(let r of o.models)if(qi(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Z_={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Xc(t){if(t.model){let{provider:o,model:r}=Ip(t.model),i=o?Pp(o):Lp(),c=o||Fi();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=qi(r,c);return{provider:c,model:r,tier:l}}}let e=Vp(t.task),n=Z_[e];if(n){let{provider:o,model:r}=Ip(n),i=o?Pp(o):Lp(),c=o||Fi();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=qi(r,c);return{provider:c,model:r,tier:l}}}let s=Jp(e);if(s){let o=qi(s.model,s.provider);return{provider:s.provider,model:s.model,tier:o}}return{provider:null,model:null,tier:null}}async function Zp(t,e={},n=0){let s=n===0?Wp:Hp,o=Math.min(t.max_iterations||10,s),r=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,i=[],c={input:0,output:0},l=new Set,u=new Map,d=t._systemPrompt||`You are a focused sub-agent. Complete this specific task efficiently.
|
|
199
199
|
|
|
200
200
|
TASK: ${t.task}
|
|
201
201
|
${t.context?`
|
|
@@ -217,25 +217,25 @@ TOOL STRATEGY:
|
|
|
217
217
|
ERROR RECOVERY:
|
|
218
218
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
219
219
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
220
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`,f=t.type&&
|
|
220
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`,f=t.type&&Xp[t.type],p=f&&f.systemSuffix?`
|
|
221
221
|
|
|
222
|
-
${f.systemSuffix}`:"",g=
|
|
223
|
-
${
|
|
222
|
+
${f.systemSuffix}`:"",g=Xc(t),m=g.provider,h=g.model,y=g.tier,b=H_(h||Mp()),C=[{role:"system",content:(b?`## Model Briefing
|
|
223
|
+
${b}
|
|
224
224
|
|
|
225
225
|
---
|
|
226
226
|
|
|
227
|
-
`:"")+d+p}];C.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:k,executeTool:
|
|
228
|
-
`)}let q={};m&&(q.provider=m),h&&(q.model=h);try{for(let ie=0;ie<o;ie++){let Q=await
|
|
229
|
-
...(truncated)`:I,tool_call_id:
|
|
230
|
-
`)}catch(d){return u.stop(),
|
|
231
|
-
`);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let c=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[c]=l.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[c]=l}n=s[2]}return{frontmatter:e,body:n}}function
|
|
232
|
-
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of
|
|
227
|
+
`:"")+d+p}];C.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:k,executeTool:x}=en(),E=zp(n),B=W_(k.filter(re=>!E.has(re.function.name)),y);if(f&&f.allowedTools&&(B=B.filter(re=>f.allowedTools.has(re.function.name))),h&&!t._skipLog){let re=y?` (${y})`:"";process.stderr.write(` [sub-agent: ${m}:${h}${re}]
|
|
228
|
+
`)}let q={};m&&(q.provider=m),h&&(q.model=h);try{for(let ie=0;ie<o;ie++){let Q=await Gp(C,B,q);if(!Q||typeof Q!="object")throw new Error("Empty or invalid response from provider");{let he=m||Fi(),be=h||Mp();if(Q.usage){let ye=Q.usage.prompt_tokens||0,Re=Q.usage.completion_tokens||0;c.input+=ye,c.output+=Re,Dp(he,be,ye,Re)}else{let ye=Q.content||"",Re=C.map(A=>typeof A.content=="string"?A.content:Array.isArray(A.content)?A.content.map(I=>typeof I=="string"?I:I.text||"").join(""):"").join(" "),v=Fp(Re),j=Fp(ye);c.input+=v,c.output+=j,c._estimated=!0,Dp(he,be,v,j)}}let O=Q.content||"",Te=Q.tool_calls,X={role:"assistant",content:O||""};if(Te&&Te.length>0&&(X.tool_calls=Te),C.push(X),!Te||Te.length===0){for(let he of l)Vo(he);return{task:t.task,status:"done",result:O||"(no response)",toolsUsed:i,tokensUsed:c,modelSpec:m&&h?`${m}:${h}`:null}}let V=Te.map(he=>{let be=he.function.name,ye=jp(he.function.arguments),Re=he.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!ye)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${be}`,tool_call_id:Re});let v=null;if(X_.has(be)&&ye.path){let A=require("path"),I=A.isAbsolute(ye.path)?ye.path:A.resolve(process.cwd(),ye.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let M=A.relative(process.cwd(),I);if(t._readOnlyFiles.some(T=>M===T||M.startsWith(T+"/")||I===T||I.startsWith(T+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${ye.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:Re})}if(l.has(I)||!z_(I,r))return Promise.resolve({role:"tool",content:`ERROR: File '${ye.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:Re});l.add(I),v=I}return i.push(be),e.onUpdate&&e.onUpdate({type:"tool_call",tool:be,agentId:r}),(be==="spawn_agents"?Qp(ye,n+1):x(be,ye,{autoConfirm:!0,silent:!0})).then(A=>{v&&(Vo(v),l.delete(v));let I=String(A??"");return{role:"tool",content:I.length>2e4?I.substring(0,2e4)+`
|
|
229
|
+
...(truncated)`:I,tool_call_id:Re}}).catch(A=>(v&&(Vo(v),l.delete(v)),{role:"tool",content:`ERROR: ${A.message}`,tool_call_id:Re}))}),fe=await Promise.all(V);if(C.push(...fe),ie>=7&&C.length>12)try{let{compressMessage:he}=Lt(),be=C.length-6;for(let ye=1;ye<be;ye++)C[ye]._subAgentCompressed||(C[ye]={...he(C[ye],"light"),_subAgentCompressed:!0})}catch{}for(let he=0;he<Te.length;he++){let be=Te[he];if(be.function.name==="bash_exec"){let ye=jp(be.function.arguments);if((fe[he]?.content||"").startsWith("ERROR")&&ye&&ye.command){let v=ye.command.replace(/\s+/g," ").trim().slice(0,100);u.set(v,(u.get(v)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${ie+1}/${o}`)}for(let ie of l)Vo(ie);let re=[...u.entries()].filter(([,ie])=>ie>=3).sort((ie,Q)=>Q[1]-ie[1]).slice(0,3).map(([ie,Q])=>`"${ie}" (failed ${Q}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:re,result:C[C.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:c,modelSpec:m&&h?`${m}:${h}`:null}}catch(re){for(let ie of l)Vo(ie);return{task:t.task,status:"failed",result:`Error: ${re.message}`,toolsUsed:i,tokensUsed:c,modelSpec:m&&h?`${m}:${h}`:null}}}async function Qp(t,e=0){if(e>=2)return"ERROR: max agent nesting depth (2) reached \u2014 reviewer agents cannot spawn further agents.";let n=e===0?Y_:G_,s=e===0?Wp:Hp,o=(t.agents||[]).slice(0,n);if(o.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,c=o.map(d=>Xc(d)),l=o.map((d,f)=>{let p=c[f],g=p.model?` [${p.model}]`:"",m=d.task.substring(0,i-g.length);return`${r}Agent ${f+1}${g}: ${m}${d.task.length>m.length?"...":""}`}),u=new K_(l);u.start();try{let d=o.map((h,y)=>{let b=c[y],S=Math.min(h.max_iterations||s,s),C=b.model?{...h,model:`${b.provider}:${b.model}`,_skipLog:!0,max_iterations:S}:{...h,_skipLog:!0,max_iterations:S};return Zp(C,{onUpdate:()=>{}},e).then(k=>(u.update(y,k.status==="failed"?"error":"done"),k)).catch(k=>(u.update(y,"error"),{task:h.task,status:"failed",result:`Error: ${k.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),f=await Promise.all(d);u.stop(),Gc();let p=["Sub-agent results:",""],g=0,m=0;for(let h=0;h<f.length;h++){let y=f[h],b=y.status==="done"?"\u2713":y.status==="truncated"?"\u26A0":"\u2717",S=y.modelSpec?` [${y.modelSpec}]`:"";p.push(`${b} Agent ${h+1}${S}: ${y.task}`),p.push(` Status: ${y.status}`),p.push(` Tools used: ${y.toolsUsed.length>0?y.toolsUsed.join(", "):"none"}`),p.push(` Result: ${y.result}`),y.repeatedFailures&&y.repeatedFailures.length>0&&p.push(` Repeated failures: ${y.repeatedFailures.join("; ")}`),p.push(""),g+=y.tokensUsed.input,m+=y.tokensUsed.output}return p.push(`Total sub-agent tokens: ${g} input + ${m} output`),p.join(`
|
|
230
|
+
`)}catch(d){return u.stop(),Gc(),`ERROR: Sub-agent execution failed: ${d.message}`}}em.exports={runSubAgent:Zp,executeSpawnAgents:Qp,clearAllLocks:Gc,classifyTask:Vp,pickModelForTier:Jp,resolveSubAgentModel:Xc,classifyError:zc,isRetryableError:Yp,callWithRetry:Gp,getExcludedTools:zp,LOCK_TIMEOUT_MS:Kp,SUB_AGENT_TYPES:Xp}});var Qo=oe((xR,mm)=>{var Qe=require("fs"),Nn=require("path"),{atomicWrite:tm,withFileLockSync:nm}=Tn(),Q_=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 uo(){let t=Nn.join(process.cwd(),".nex","brain");return Qe.existsSync(t)||Qe.mkdirSync(t,{recursive:!0}),t}function Hi(){return Nn.join(uo(),".brain-index.json")}function Zc(){return Nn.join(uo(),".embeddings.json")}function Jo(){let t=Nn.join(process.cwd(),".nex","brain");if(!Qe.existsSync(t))return[];try{return Qe.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let n=Nn.join(t,e),s=Qe.statSync(n);return{name:e.replace(/\.md$/,""),path:n,size:s.size,modified:new Date(s.mtimeMs)}}).sort((e,n)=>n.modified-e.modified)}catch{return[]}}function Zo(t){let e={},n=t,s=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(s){let o=s[1].split(`
|
|
231
|
+
`);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let c=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[c]=l.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[c]=l}n=s[2]}return{frontmatter:e,body:n}}function sm(t){let e=Nn.join(uo(),`${t}.md`);if(!Qe.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=Qe.readFileSync(e,"utf-8"),{frontmatter:s,body:o}=Zo(n);return{name:t,content:n,body:o,frontmatter:s}}function ex(t,e){let n=Nn.join(uo(),`${t}.md`);tm(n,e),sx(t,e),tx()}function tx(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Zc();Qe.existsSync(t)&&setImmediate(async()=>{try{await um()}catch{}})}function nx(t){let e=Nn.join(uo(),`${t}.md`);return Qe.existsSync(e)?(Qe.unlinkSync(e),ox(t),!0):!1}function Wi(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Q_.has(e))}function Qc(t){let e={},{frontmatter:n,body:s}=Zo(t),o=Array.isArray(n.tags)?n.tags:[];for(let i of o){let c=i.toLowerCase().replace(/[^a-z0-9-]/g,"");c.length>1&&(e[c]=(e[c]||0)+5)}let r=(s||t).split(`
|
|
232
|
+
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of Wi(c))e[l]=(e[l]||0)+3}for(let i of Wi(s||t))e[i]=(e[i]||0)+1;return e}function el(){let t=Hi();if(!Qe.existsSync(t))return{documents:{}};try{return JSON.parse(Qe.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function tl(t){tm(Hi(),JSON.stringify(t,null,2))}function sx(t,e){nm(Hi(),()=>{let n=el(),{frontmatter:s}=Zo(e),o=Array.isArray(s.tags)?s.tags:[];n.documents[t]={keywords:Qc(e),tags:o,modified:new Date().toISOString()},tl(n)})}function ox(t){nm(Hi(),()=>{let e=el();delete e.documents[t],tl(e)})}function Jc(){let t=Jo(),e={documents:{}};for(let n of t){let s=Qe.readFileSync(n.path,"utf-8"),{frontmatter:o}=Zo(s),r=Array.isArray(o.tags)?o.tags:[];e.documents[n.name]={keywords:Qc(s),tags:r,modified:n.modified.toISOString()}}return tl(e),e}function om(){let t=el(),e=Jo();for(let n of e){let s=t.documents[n.name];if(!s||new Date(s.modified)<n.modified)return Jc()}for(let n of Object.keys(t.documents))if(!e.some(s=>s.name===n))return Jc();return t}function rm(t,e={}){let{topK:n=3,minScore:s=.1}=e,o=Wi(t);if(o.length===0)return[];let r=om(),i=[];for(let[c,l]of Object.entries(r.documents)){let u=0;for(let d of o){l.keywords[d]&&(u+=l.keywords[d]);for(let[f,p]of Object.entries(l.keywords))f!==d&&f.length>3&&d.length>3&&(f.includes(d)||d.includes(f))&&(u+=p*.3)}u>=s&&i.push({name:c,score:u})}return i.sort((c,l)=>l.score-c.score),i.slice(0,n)}var im=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Vc=400,rx=50;async function am(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),n=require("https"),s=new URL(`${t}/api/tags`),o=s.protocol==="https:"?n:e;return((await new Promise((c,l)=>{let u=o.get(s.toString(),{timeout:2e3},d=>{let f="";d.on("data",p=>f+=p),d.on("end",()=>{try{c(JSON.parse(f))}catch{l(new Error("bad json"))}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("timeout"))})})).models||[]).map(c=>c.name).some(c=>c.startsWith(im.split(":")[0]))}catch{return!1}}async function nl(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",n=require("http"),s=require("https"),o=new URL(`${e}/api/embeddings`),r=o.protocol==="https:"?s:n,i=JSON.stringify({model:im,prompt:t});return new Promise((c,l)=>{let u=r.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},d=>{let f="";d.on("data",p=>f+=p),d.on("end",()=>{try{c(JSON.parse(f).embedding||[])}catch(p){l(p)}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("embedding timeout"))}),u.write(i),u.end()})}function cm(t,e){if(!t||!e||t.length!==e.length)return 0;let n=0,s=0,o=0;for(let i=0;i<t.length;i++)n+=t[i]*e[i],s+=t[i]*t[i],o+=e[i]*e[i];let r=Math.sqrt(s)*Math.sqrt(o);return r===0?0:n/r}function lm(t){let e=t.split(/\s+/),n=[],s=0;for(;s<e.length;){let o=e.slice(s,s+Vc).join(" ");if(n.push({text:o,offset:s}),s+Vc>=e.length)break;s+=Vc-rx}return n}async function um(){let t=Jo(),e={documents:{}},n=Zc();if(Qe.existsSync(n))try{e=JSON.parse(Qe.readFileSync(n,"utf-8"))}catch{}for(let s of t){let o=e.documents[s.name];if(o&&new Date(o.modified)>=s.modified)continue;let r=Qe.readFileSync(s.path,"utf-8"),i=lm(r),c=[];for(let l of i){let u=await nl(l.text);c.push({text:l.text,embedding:u,offset:l.offset})}e.documents[s.name]={chunks:c,modified:s.modified.toISOString()}}for(let s of Object.keys(e.documents))t.some(o=>o.name===s)||delete e.documents[s];return Qe.writeFileSync(n,JSON.stringify(e),"utf-8"),e}async function dm(t,e={}){let{topK:n=3,minSimilarity:s=.3}=e,o=Zc();if(!Qe.existsSync(o))return[];let r;try{r=JSON.parse(Qe.readFileSync(o,"utf-8"))}catch{return[]}let i=await nl(t),c=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,f="";for(let p of u.chunks||[]){let g=cm(i,p.embedding);g>d&&(d=g,f=p.text)}d>=s&&c.push({name:l,score:d,bestChunk:f})}return c.sort((l,u)=>u.score-l.score),c.slice(0,n)}function fm(t,e,n={}){let{k:s=60,topK:o=3}=n,r={};return t.forEach((i,c)=>{r[i.name]=(r[i.name]||0)+1/(s+c+1)}),e.forEach((i,c)=>{r[i.name]=(r[i.name]||0)+1/(s+c+1)}),Object.entries(r).map(([i,c])=>({name:i,score:c})).sort((i,c)=>c.score-i.score).slice(0,o)}async function pm(t,e={}){let{topK:n=3,minScore:s=.1}=e,o=rm(t,{topK:n,minScore:s}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await am()){let c=await dm(t,{topK:n});r=fm(o,c,{topK:n})}}catch{}return r.map(i=>{let c=sm(i.name),l=(c.body||c.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:c.content,excerpt:l}})}var lo={queryKey:null,result:null,ts:0},ix=3e5;async function ax(t){if(!t||!t.trim())return"";let e=Nn.join(process.cwd(),".nex","brain");if(!Qe.existsSync(e)||Jo().length===0)return"";let s=t.trim().toLowerCase().slice(0,200);if(lo.result!==null&&lo.queryKey===s&&Date.now()-lo.ts<ix)return lo.result;let o;try{o=await pm(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let r;try{r=Lt().estimateTokens}catch{r=d=>Math.ceil(d.length/4)}let i=25e3,c=[],l=0;for(let d of o){let f=d.content||"",p=r(f);if(l+p>i){let m=i-l;if(m<100)break;let h=m/p;f=f.slice(0,Math.floor(f.length*h))+`
|
|
233
233
|
...(truncated)`}let g=typeof d.score=="number"?d.score.toFixed(2):String(d.score);if(c.push(`--- ${d.name} (relevance: ${g}) ---
|
|
234
|
-
${f}`),l+=r(f),l>=i)break}if(c.length===0)return
|
|
234
|
+
${f}`),l+=r(f),l>=i)break}if(c.length===0)return lo={queryKey:s,result:"",ts:Date.now()},"";let u=`KNOWLEDGE BASE (auto-selected):
|
|
235
235
|
|
|
236
236
|
${c.join(`
|
|
237
237
|
|
|
238
|
-
`)}`;return
|
|
238
|
+
`)}`;return lo={queryKey:s,result:u,ts:Date.now()},u}mm.exports={getBrainDir:uo,listDocuments:Jo,readDocument:sm,writeDocument:ex,removeDocument:nx,buildIndex:Jc,getIndex:om,query:pm,getBrainContext:ax,isEmbeddingAvailable:am,generateEmbedding:nl,buildEmbeddingIndex:um,semanticQuery:dm,cosineSimilarity:cm,_keywordQuery:rm,_extractKeywords:Qc,_chunkText:lm,parseFrontmatter:Zo,tokenize:Wi,_fuseResults:fm}});var tn=oe((vR,Em)=>{var Ve=require("fs"),It=require("path"),cx=require("os"),{atomicWrite:Ki,withFileLockSync:hm}=Tn(),er=["user","feedback","project","reference"],lx=50;function $s(){return It.join(process.cwd(),".nex","memory")}function fo(){return It.join($s(),"memory.json")}function gm(){return It.join($s(),"MEMORY.md")}function ux(){return It.join(process.cwd(),"NEX.md")}function $m(){return It.join(cx.homedir(),".nex","NEX.md")}function Yi(){let t=$s();Ve.existsSync(t)||Ve.mkdirSync(t,{recursive:!0})}function ym(t){let e=It.join($s(),t);return Ve.existsSync(e)||Ve.mkdirSync(e,{recursive:!0}),e}function tr(){let t=fo();if(!Ve.existsSync(t))return{};try{return JSON.parse(Ve.readFileSync(t,"utf-8"))}catch{return{}}}function wm(t){Yi(),Ki(fo(),JSON.stringify(t,null,2))}function bm(){let t=fo();if(!Ve.existsSync(t))return;let e=tr(),n=Object.keys(e);if(n.length===0){try{Ve.renameSync(t,t+".bak")}catch{}return}for(let s of n){let o=e[s],r=o.value||String(o),i=s.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let c=ym("project"),l=It.join(c,`${i}.md`),u=r.split(`
|
|
239
239
|
`)[0].slice(0,100),d=`---
|
|
240
240
|
name: ${s}
|
|
241
241
|
description: ${u}
|
|
@@ -243,7 +243,7 @@ type: project
|
|
|
243
243
|
---
|
|
244
244
|
|
|
245
245
|
${r}
|
|
246
|
-
`;
|
|
246
|
+
`;Ki(l,d)}Gi();try{Ve.renameSync(t,t+".bak")}catch{}}function dx(t,e,n,s){if(!er.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${er.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!n||typeof n!="string"||n.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let o=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!o)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=ym(t),i=It.join(r,`${o}.md`);if(Ve.existsSync(i))try{if(sl(Ve.readFileSync(i,"utf-8")).body.slice(0,200)===n.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let c=s||n.split(`
|
|
247
247
|
`)[0].slice(0,100),l=`---
|
|
248
248
|
name: ${e}
|
|
249
249
|
description: ${c}
|
|
@@ -251,11 +251,11 @@ type: ${t}
|
|
|
251
251
|
---
|
|
252
252
|
|
|
253
253
|
${n}
|
|
254
|
-
`;return
|
|
254
|
+
`;return Ki(i,l),Gi(),{ok:!0,path:i,updated:!0}}function fx(t,e){if(!er.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),s=It.join($s(),t,`${n}.md`);if(!Ve.existsSync(s))return!1;try{return Ve.unlinkSync(s),Gi(),!0}catch{return!1}}function sl(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let n=e[1],s=(e[2]||"").trim(),o=r=>{let i=n.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:o("name"),description:o("description"),type:o("type"),body:s}}function _m(){let t=[],e=$s();for(let n of er){let s=It.join(e,n);if(!Ve.existsSync(s))continue;let o;try{o=Ve.readdirSync(s).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of o){let i=It.join(s,r);try{let c=Ve.readFileSync(i,"utf-8"),l=sl(c);t.push({type:n,name:l.name||It.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function Gi(){let t=_m(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=lx+2)break;let s=`${n.type}/${It.basename(n.filePath)}`;e.push(`- [${n.name}](${s}) \u2014 ${n.description||"(no description)"}`)}Yi(),Ki(gm(),e.join(`
|
|
255
255
|
`)+`
|
|
256
|
-
`)}function
|
|
257
|
-
${e}`);let n=
|
|
258
|
-
${n}`);let s="",o=
|
|
256
|
+
`)}function xm(){let t=gm();if(!Ve.existsSync(t))return"";try{return Ve.readFileSync(t,"utf-8").trim()}catch{return""}}function px(t,e){Yi(),hm(fo(),()=>{let n=tr();n[t]={value:e,updatedAt:new Date().toISOString()},wm(n)})}function mx(t){let e=tr();return e[t]?e[t].value:null}function hx(t){return Yi(),hm(fo(),()=>{let e=tr();return t in e?(delete e[t],wm(e),!0):!1})}function vm(){let t=tr();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function Sm(){let t=$m();if(!Ve.existsSync(t))return"";try{return Ve.readFileSync(t,"utf-8").trim()}catch{return""}}function km(){let t=ux();if(!Ve.existsSync(t))return"";try{return Ve.readFileSync(t,"utf-8").trim()}catch{return""}}function gx(){bm();let t=[],e=Sm();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
257
|
+
${e}`);let n=km();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
258
|
+
${n}`);let s="",o=xm();if(o)s=o;else{let f=vm();f.length>0&&(s=`PROJECT MEMORY:
|
|
259
259
|
${f.map(g=>` ${g.key}: ${g.value}`).join(`
|
|
260
260
|
`)}`)}let r=t.join(`
|
|
261
261
|
|
|
@@ -264,149 +264,149 @@ ${f.map(g=>` ${g.key}: ${g.value}`).join(`
|
|
|
264
264
|
`}s=p.trimEnd()+`
|
|
265
265
|
[Memory index truncated \u2014 use delete_memory to prune old entries]`}else s.length>u&&(s="");let d=[...t];return s&&d.push(s),d.length>0&&d.push(i),d.join(`
|
|
266
266
|
|
|
267
|
-
`)}
|
|
268
|
-
`;
|
|
269
|
-
`).filter(l=>l.trim());for(let l of c)try{let u=JSON.parse(l);if(t.tool&&u.tool!==t.tool)continue;s.push(u)}catch{}if(t.date)break}return s}function
|
|
267
|
+
`)}Em.exports={saveMemory:dx,deleteMemory:fx,scanMemories:_m,rebuildIndex:Gi,loadMemoryIndex:xm,remember:px,recall:mx,forget:hx,listMemories:vm,loadGlobalInstructions:Sm,loadProjectInstructions:km,getMemoryContext:gx,_getMemoryDir:$s,_getMemoryFile:fo,_getGlobalNexMdPath:$m,_parseMemoryFile:sl,_migrateIfNeeded:bm,VALID_TYPES:er}});var il=oe((SR,Om)=>{var nr=require("fs"),ol=require("path"),rl=process.env.NEX_AUDIT!=="false",ys=null;function Tm(){return ys||(ys=ol.join(process.cwd(),".nex","audit"),nr.existsSync(ys)||nr.mkdirSync(ys,{recursive:!0}),ys)}function Rm(){let t=new Date().toISOString().split("T")[0];return ol.join(Tm(),`${t}.jsonl`)}function $x(t){if(rl)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Cm(t.args),resultLength:typeof t.result=="string"?t.result.length:0,resultPreview:typeof t.result=="string"?t.result.substring(0,200):"",duration:t.duration||0,success:t.success!==!1,model:t.model||null,provider:t.provider||null},n=JSON.stringify(e)+`
|
|
268
|
+
`;nr.appendFileSync(Rm(),n,"utf-8")}catch{}}function Cm(t){if(!t||typeof t!="object")return{};let e={};for(let[n,s]of Object.entries(t))/key|token|password|secret|credential/i.test(n)?e[n]="***":typeof s=="string"&&s.length>500?e[n]=s.substring(0,500)+`... (${s.length} chars)`:e[n]=s;return e}function Am(t={}){let e=Tm(),n=t.days||1,s=[];for(let o=0;o<n;o++){let r=t.date||new Date(Date.now()-o*864e5).toISOString().split("T")[0],i=ol.join(e,`${r}.jsonl`);if(!nr.existsSync(i))continue;let c=nr.readFileSync(i,"utf-8").split(`
|
|
269
|
+
`).filter(l=>l.trim());for(let l of c)try{let u=JSON.parse(l);if(t.tool&&u.tool!==t.tool)continue;s.push(u)}catch{}if(t.date)break}return s}function yx(t=1){let e=Am({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let n={},s=0,o=0;for(let r of e)n[r.tool]=(n[r.tool]||0)+1,s+=r.duration||0,r.success&&o++;return{totalCalls:e.length,byTool:n,avgDuration:Math.round(s/e.length),successRate:o/e.length}}function wx(t){rl=t}function bx(){return rl}function _x(){ys=null}Om.exports={logToolExecution:$x,sanitizeArgs:Cm,readAuditLog:Am,getAuditSummary:yx,setAuditEnabled:wx,isAuditEnabled:bx,getAuditLogPath:Rm,_reset:_x}});var Bm=oe((TR,Um)=>{var et=require("fs").promises,Nm=require("fs"),Fe=require("path"),We=require("util").promisify(require("child_process").exec),al=require("util").promisify(require("child_process").execFile),{spawnSync:xx}=require("child_process"),cl=require("axios"),{isForbidden:vx,isSSHForbidden:Sx,isDangerous:kx,isCritical:Mm,isBashPathForbidden:Ex,confirm:nn}=$t(),{showDiff:zi,showNewFile:Tx,showEditDiff:kR,confirmFileChange:sr}=mf(),{C:$e,Spinner:Rx,getToolSpinnerText:Cx}=Ke(),{isGitRepo:ll,getCurrentBranch:Pm,getStatus:Ax,getDiff:Ox}=Bn(),{recordChange:Xi}=Rn(),{fuzzyFindText:Lm,findMostSimilar:ir}=Gf(),{runDiagnostics:or}=Xf(),{findFileInIndex:Nx,getFileIndex:ER}=jc(),{resolveProfile:zt,sshExec:Rt,scpUpload:Mx,scpDownload:Px}=ro(),{resolveDeployConfig:Lx,loadDeployConfigs:Ix}=Uc(),{getEditMode:Im}=Wo(),jx=/^(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/,Dx=/^ssh\s/,qx=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function jt(t){return et.access(t).then(()=>!0).catch(()=>!1)}async function Vi(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=Ct(e);if(n&&await jt(n))return{fixedPath:n,message:`(auto-fixed path: ${t} \u2192 ${e})`};let s=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=Fe.extname(t);if(!o)for(let i of s){let c=Ct(t+i);if(c&&await jt(c))return{fixedPath:c,message:`(auto-fixed: added ${i} extension)`}}if(o){let i=t.replace(/\.[^.]+$/,"");for(let c of s){if(c===o)continue;let l=Ct(i+c);if(l&&await jt(l))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${c})`}}}let r=Fe.basename(t);if(r&&r.length>2)try{let i=Nx(r).map(c=>Ct(c));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${Fe.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
270
270
|
${i.map(l=>Fe.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
271
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
271
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function Fx(t){return/\bprintenv\b/.test(t)?"printenv exposes all secrets. Use `echo $VAR_NAME` for a single variable, or `env | grep PATTERN` for filtered output.":/cat\s+.*\.env\b/.test(t)?'Reading .env directly is blocked. Use `grep -v "KEY=" .env` to inspect non-secret entries, or ask the user to share specific values.':/cat\s+.*credentials/i.test(t)?"Credentials files are blocked. Reference the variable name from the application config instead.":/python3?\s+-c\s/.test(t)?"Inline python -c is blocked. Write a temporary script file and run it with `python3 script.py` instead.":/node\s+-e\s/.test(t)?"Inline node -e is blocked. Write a temporary script file and run it with `node script.js` instead.":/curl.*-X\s*POST|curl.*--data/.test(t)?"curl POST is blocked to prevent data exfiltration. Use the application's own API client or ask the user to run the request.":/base64.*\|.*bash/.test(t)?"Piping base64-decoded content to bash is blocked. Decode the content first, inspect it, then run explicitly.":/\beval\s*\(/.test(t)?"eval is blocked. Execute the command directly without eval.":/(?:^|[;&|]\s*)history(?:\s|$)/.test(t)?"Shell history is blocked. Look at git log or project files for context instead.":/\bsed\s+-n\s+['"]?\d+,\d+p/.test(t)?'sed -n line-range scrolling floods context with irrelevant lines. Use targeted grep instead: grep -n "ERROR\\|pattern" <logfile> | tail -20':""}function qm(t,e){let n=[];if(/command not found|: not found|not recognized/i.test(t)){let s=e.match(/^(\S+)/),o=s?s[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?n.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?n.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):n.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let s=t.match(/Cannot find module '([^']+)'/),o=s?s[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?n.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):n.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&n.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let s=t.match(/port (\d+)|:(\d+)/),o=s?s[1]||s[2]:"";n.push(`HINT: Port ${o||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&n.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&n.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&n.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&n.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let s=t.match(/curl:\s*\((\d+)\)/),o=s?parseInt(s[1],10):null;o===6||/Could not resolve host/i.test(t)?n.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?n.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?n.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?n.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===35||/SSL.*error/i.test(t))&&n.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let s=t.match(/port (\d+)/),o=s?s[1]:"";n.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&n.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&n.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&n.push("HINT: The working directory was deleted during this session \u2014 bash cannot execute commands in a non-existent cwd. Previous rm/delete commands succeeded. Use list_directory or glob to verify the state instead of retrying bash."),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&n.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),n.length===0?t:t+`
|
|
272
272
|
|
|
273
273
|
`+n.join(`
|
|
274
|
-
`)}function Om(t,e,n){let s=or(t,e);if(!s)return null;let o=Math.max(2,Math.ceil(e.length*.03));return s.distance>o?null:{autoFixed:!0,matchText:s.text,content:t.split(s.text).join(n),distance:s.distance,line:s.line}}var Rm=!1,ys=null;function Sx(){ys&&(ys(),ys=null)}var al=null;function kx(t){al=t}async function il(){if(!Rm){Rm=!0;try{let{stdout:t}=await We("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await We('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await We("git stash pop",{cwd:process.cwd(),timeout:1e4}),await We("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Ex=[/\.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=Fe.isAbsolute(t)?Fe.resolve(t):Fe.resolve(process.cwd(),t);for(let n of Ex)if(n.test(e))return null;return e}var Tx=[{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 sr(t,{server:e,context:n}={}){let s=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,s){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${s} "${i}"`}return r}async function Cm(t,e,n={}){switch(t){case"bash":{let s=e.command,o=ix(s);if(o){let f=vx(s);return`BLOCKED: Command matches forbidden pattern: ${o}${f?`
|
|
275
|
-
HINT: ${f}`:""}`}let r=
|
|
276
|
-
HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(n.autoConfirm?
|
|
277
|
-
${g}`}}case"read_file":{let s=
|
|
278
|
-
`+
|
|
279
|
-
`),d=await et.stat(s),f=u.length,p=350,g=!e.line_start&&!e.line_end,m=g&&f>p,h=(e.line_start||1)-1,y=m?p:e.line_end||u.length,
|
|
280
|
-
`),
|
|
274
|
+
`)}function Fm(t,e,n){let s=ir(t,e);if(!s)return null;let o=Math.max(2,Math.ceil(e.length*.03));return s.distance>o?null:{autoFixed:!0,matchText:s.text,content:t.split(s.text).join(n),distance:s.distance,line:s.line}}var jm=!1,ws=null;function Ux(){ws&&(ws(),ws=null)}var dl=null;function Bx(t){dl=t}async function ul(){if(!jm){jm=!0;try{let{stdout:t}=await We("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await We('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await We("git stash pop",{cwd:process.cwd(),timeout:1e4}),await We("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Wx=[/\.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 Ct(t){let e=Fe.isAbsolute(t)?Fe.resolve(t):Fe.resolve(process.cwd(),t);for(let n of Wx)if(n.test(e))return null;return e}var Hx=[{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 rr(t,{server:e,context:n}={}){let s=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,s){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${s} "${i}"`}return r}async function Dm(t,e,n={}){switch(t){case"bash":{let s=e.command,o=vx(s);if(o){let f=Fx(s);return`BLOCKED: Command matches forbidden pattern: ${o}${f?`
|
|
275
|
+
HINT: ${f}`:""}`}let r=Ex(s);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
|
|
276
|
+
HINT: Protected files (.env, credentials, venv, .ssh, etc.) cannot be deleted or moved via bash. Override with NEX_UNPROTECT=1 if intentional.`;if(n.autoConfirm?Mm(s):kx(s)){let f=Mm(s)?"\u26D4":"\u26A0";if(!await nn(` ${f} bash: \`${s}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let c;try{c=process.cwd(),Nm.accessSync(c)}catch{c=require("os").homedir(),n.silent||console.log(`${$e.yellow} \u26A0 Working directory no longer exists \u2014 running in ${c}${$e.reset}`)}let l=Dx.test(s.trim())&&!qx.test(s.trim());if(jx.test(s.trim())||l){n.silent||console.log(`${$e.dim} \u25B6 interactive: ${s}${$e.reset}`);let f=xx("sh",["-c",s],{stdio:"inherit",cwd:c});return f.error?`ERROR: ${f.error.message}`:f.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${f.status})`}let{ToolProgress:u}=Gs(),d=n.silent?null:new u("bash",s.substring(0,40));d&&d.start();try{let{stdout:f,stderr:p}=await We(s,{cwd:c,timeout:9e4,maxBuffer:5242880});return d&&d.stop(),f||p||"(no output)"}catch(f){d&&d.stop();let p=(f.stderr||f.stdout||f.message||"").toString().substring(0,5e3),g=qm(p,s);return`EXIT ${f.code||1}
|
|
277
|
+
${g}`}}case"read_file":{let s=Ct(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await jt(s)){let E=await Vi(e.path);if(E.fixedPath)s=E.fixedPath,console.log(`${$e.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Fe.relative(process.cwd(),s)}${$e.reset}`);else return`ERROR: File not found: ${e.path}${E.message?`
|
|
278
|
+
`+E.message:""}`}let r=Buffer.alloc(8192),i=await Nm.promises.open(s,"r"),{bytesRead:c}=await i.read(r,0,8192,0);await i.close();for(let E=0;E<c;E++)if(r[E]===0)return`ERROR: ${s} is a binary file (not readable as text)`;let l=await et.readFile(s,"utf-8");if(!l&&(await et.stat(s)).size>0)return`WARNING: ${s} is empty or unreadable`;let u=l.split(`
|
|
279
|
+
`),d=await et.stat(s),f=u.length,p=350,g=!e.line_start&&!e.line_end,m=g&&f>p,h=(e.line_start||1)-1,y=m?p:e.line_end||u.length,b=Fe.relative(process.cwd(),s),S=m?`showing lines 1-${p} of ${f}`:e.line_start||e.line_end?`lines ${h+1}-${y} of ${f}`:`${f} lines`,C=`File: ${b} (${S}, ${d.size} bytes)`,k=u.slice(h,y).map((E,B)=>`${h+B+1}: ${E}`).join(`
|
|
280
|
+
`),x=m?`
|
|
281
281
|
|
|
282
282
|
[File truncated: showing lines 1-${p} of ${f} total. Use line_start/line_end to read other sections, e.g. line_start=${p+1} line_end=${Math.min(p*2,f)}]`:!g&&f>p?`
|
|
283
283
|
[Large file (${f} lines total) \u2014 use line_start/line_end for other sections]`:"";return`${C}
|
|
284
|
-
${k}${
|
|
285
|
-
`+d.message:""}`}let r=await et.readFile(s,"utf-8"),i=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let{getActiveModelId:d,getActiveProviderName:f}=Be();if(
|
|
284
|
+
${k}${x}`}case"write_file":{await ul();let s=Ct(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await jt(s),r=null;if(n.autoConfirm)o&&(r=await et.readFile(s,"utf-8"));else if(o){r=await et.readFile(s,"utf-8");let d=await or(s,e.content);if(zi(s,r,e.content,{annotations:d}),!await sr("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let d=await or(s,e.content);if(Tx(s,e.content,{annotations:d}),!await sr("Create"))return"CANCELLED: User declined to create file."}let i=Fe.dirname(s);await jt(i)||await et.mkdir(i,{recursive:!0}),await et.writeFile(s,e.content,"utf-8");let l=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||e.content.startsWith("#!");l&&await et.chmod(s,493),Xi("write_file",s,r,e.content);let u=l?" [chmod +x applied]":"";return`Written: ${s} (${e.content.length} chars)${u}`}case"edit_file":{await ul();let s=Ct(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await jt(s)){let d=await Vi(e.path);if(d.fixedPath)s=d.fixedPath,console.log(`${$e.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Fe.relative(process.cwd(),s)}${$e.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
285
|
+
`+d.message:""}`}let r=await et.readFile(s,"utf-8"),i=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let{getActiveModelId:d,getActiveProviderName:f}=Be();if(Im(d(),f())==="strict"){let m=ir(r,e.old_text);return m?`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)
|
|
286
286
|
Most similar text (line ${m.line}, distance ${m.distance}):
|
|
287
|
-
${m.text}`:`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)`}let g=
|
|
288
|
-
`),C=Math.max(0,h.line-6),k=Math.min(
|
|
289
|
-
`),
|
|
287
|
+
${m.text}`:`ERROR: old_text not found in ${s} (strict mode \u2014 exact match required)`}let g=Lm(r,e.old_text);if(g)i=g,c=!0,console.log(`${$e.dim} \u2713 fuzzy whitespace match applied${$e.reset}`);else{let m=Fm(r,e.old_text,e.new_text);if(m){if(!n.autoConfirm){let C=await or(s,m.content);if(zi(s,r,m.content,{annotations:C}),!await sr(`Apply (auto-fix, line ${m.line}, distance ${m.distance})`))return"CANCELLED: User declined to apply edit."}await et.writeFile(s,m.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||m.content.startsWith("#!"))&&await et.chmod(s,493),Xi("edit_file",s,r,m.content);let S=m.matchText.length>80?m.matchText.substring(0,77)+"...":m.matchText;return console.log(`${$e.dim} \u2713 auto-fixed edit: line ${m.line}, distance ${m.distance}${$e.reset}`),`Edited: ${s} (auto-fixed, line ${m.line}, distance ${m.distance}, matched: "${S}")`}let h=ir(r,e.old_text);if(h){let S=r.split(`
|
|
288
|
+
`),C=Math.max(0,h.line-6),k=Math.min(S.length,h.line+10),x=S.slice(C,k).map((B,q)=>`${C+q+1}: ${B}`).join(`
|
|
289
|
+
`),E=`line_start=${Math.max(1,h.line-5)} line_end=${Math.min(S.length,h.line+15)}`;return`ERROR: old_text not found in ${s} (most similar at line ${h.line}, distance ${h.distance})
|
|
290
290
|
|
|
291
291
|
Actual file content around line ${h.line} \u2014 use this to correct old_text:
|
|
292
|
-
${
|
|
292
|
+
${x}
|
|
293
293
|
|
|
294
|
-
Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${
|
|
295
|
-
`)[0].slice(0,60),
|
|
294
|
+
Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${E}`}let y=(e.old_text||"").trim().split(`
|
|
295
|
+
`)[0].slice(0,60),b=y?`
|
|
296
296
|
Recovery: grep -n "${y.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
|
|
297
|
-
Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${s}${
|
|
298
|
-
`)||"(empty)"}case"search_files":{let s=
|
|
297
|
+
Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${s}${b}`}}if(!n.autoConfirm){let d=r.split(i).join(e.new_text),f=await or(s,d);if(zi(s,r,d,{annotations:f}),!await sr(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(i).join(e.new_text);return await et.writeFile(s,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||u.startsWith("#!"))&&await et.chmod(s,493),Xi("edit_file",s,r,u),c?`Edited: ${s} (fuzzy match)`:`Edited: ${s}`}case"list_directory":{let s=Ct(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await jt(s)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=Ct(u),f=await jt(d);if(d&&f)s=d;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let c=[],l=async(u,d,f)=>{if(d>r)return;let p;try{p=await et.readdir(u,{withFileTypes:!0})}catch{return}p=p.filter(g=>!g.name.startsWith(".")&&g.name!=="node_modules");for(let g of p){if(i&&!g.isDirectory()&&!i.test(g.name))continue;let m=g.isDirectory()?"/":"";c.push(`${f}${g.name}${m}`),g.isDirectory()&&await l(Fe.join(u,g.name),d+1,f+" ")}};return await l(s,1,""),c.join(`
|
|
298
|
+
`)||"(empty)"}case"search_files":{let s=Ct(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn","--null","-H"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,s);try{let{stdout:r}=await al("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),c=[];for(let l=0;l<i.length;l+=2){let u=i[l],d=i[l+1];if(u&&d){let f=d.split(`
|
|
299
299
|
`).filter(p=>p.trim());for(let p of f)if(c.push(`${u}:${p}`),c.length>=50)break}if(c.length>=50)break}return c.join(`
|
|
300
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?
|
|
301
|
-
`);return p.update({count:C.length,detail:e.pattern}),p.stop(),
|
|
300
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?Ct(e.path):o,i=e.pattern,c=q=>{let re=q.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${re}$`)},l=c(i),u=i.split("/").pop(),d=c(u),{ToolProgress:f}=Gs(),p=new f("glob","Finding files...");p.start();let{getFileIndex:g,getIndexedCwd:m,refreshIndex:h,isIndexValid:y}=jc(),b=g(),S=m();y(r)||(await h(r),b=g());let C=b.filter(q=>l.test(q)||d.test(Fe.basename(q))).map(q=>Fe.join(r,q));if(C.length===0)return p.stop(),"(no matches)";let k=await Promise.all(C.slice(0,210).map(async q=>{try{let re=await et.stat(q);return{path:q,mtime:re.mtimeMs}}catch{return{path:q,mtime:0}}}));k.sort((q,re)=>re.mtime-q.mtime);let x=k.map(q=>q.path),E=C.length>200,B=x.slice(0,200).join(`
|
|
301
|
+
`);return p.update({count:C.length,detail:e.pattern}),p.stop(),E?`${B}
|
|
302
302
|
|
|
303
|
-
\u26A0 Results truncated at 200. Use a more specific pattern.`:B}case"grep":{let s=e.path?
|
|
304
|
-
`);for(let y of f)if(y.startsWith("diff --git")){let
|
|
305
|
-
`).filter(
|
|
303
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:B}case"grep":{let s=e.path?Ct(e.path):process.cwd();if(e.staged){let{getDiff:l}=Bn(),u=await l(!0);if(!u.trim())return"(no staged changes)";let d=new Set,f=u.split(`
|
|
304
|
+
`);for(let y of f)if(y.startsWith("diff --git")){let b=y.match(/diff --git a\/(.+) b\/(.+)/);b&&d.add(b[2])}let p=["-rn","-E","--null","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&p.push("-i"),e.include&&p.push(`--include=${e.include}`),e.type&&p.push(`--include=*.${e.type}`),e.context?p.push("-C",String(e.context)):(e.before_context&&p.push("-B",String(e.before_context)),e.after_context&&p.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?p.push("-l"):e.output_mode==="count"&&p.push("-c"),p.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:g}=Gs(),m=new g("grep","Searching staged content...");m.start();let h=[];for(let y of d)try{let b=Fe.join(process.cwd(),y);if(await jt(b)){let S=[...p];S.push(e.pattern,b);let{stdout:C}=await al("grep",S,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let k=C.trim().split(`
|
|
305
|
+
`).filter(x=>x.trim());h=h.concat(k)}else{let k=C.split("\0");for(let x=0;x<k.length;x+=2){let E=k[x+1];if(E){let B=E.split(`
|
|
306
306
|
`).filter(q=>q.trim());for(let q of B)h.push(`${y}:${q}`)}}}}}catch{}return m.update({count:h.length,detail:"in staged files"}),m.stop(),h.join(`
|
|
307
|
-
`).trim()||"(no matches in staged files)"}let o=["-rn","-E","--null","-H"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),e.type&&o.push(`--include=*.${e.type}`);let r=20;e.context?o.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&o.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&o.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?o.push("-l"):e.output_mode==="count"&&o.push("-c"),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,s);let{ToolProgress:i}=
|
|
307
|
+
`).trim()||"(no matches in staged files)"}let o=["-rn","-E","--null","-H"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),e.type&&o.push(`--include=*.${e.type}`);let r=20;e.context?o.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&o.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&o.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?o.push("-l"):e.output_mode==="count"&&o.push("-c"),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,s);let{ToolProgress:i}=Gs(),c=new i("grep","Searching...");c.start();try{let{stdout:l}=await al("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),u;if(e.output_mode==="files_with_matches"||e.output_mode==="count")u=l.trim().split(`
|
|
308
308
|
`).filter(p=>p.trim());else{let p=l.split("\0");u=[];for(let g=0;g<p.length;g+=2){let m=p[g],h=p[g+1];if(m&&h){let y=h.split(`
|
|
309
|
-
`).filter(
|
|
310
|
-
`).trim()||"(no matches)"}catch(l){return c.stop(),l.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await
|
|
311
|
-
`+
|
|
309
|
+
`).filter(b=>b.trim());for(let b of y)u.push(`${m}:${b}`)}}}let d=e.offset||0,f=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return u=u.slice(d,d+f),c.update({count:u.length,detail:`in ${s}`}),c.stop(),u.join(`
|
|
310
|
+
`).trim()||"(no matches)"}catch(l){return c.stop(),l.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await ul();let s=Ct(e.path);if(!s)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await jt(s)){let b=await Vi(e.path);if(b.fixedPath)s=b.fixedPath,console.log(`${$e.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Fe.relative(process.cwd(),s)}${$e.reset}`);else return`ERROR: File not found: ${e.path}${b.message?`
|
|
311
|
+
`+b.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await et.readFile(s,"utf-8"),{getActiveModelId:c,getActiveProviderName:l}=Be(),u=Im(c(),l()),d=[],f=!1,p=!1;for(let b=0;b<r.length;b++){let{old_text:S,new_text:C}=r[b];if(i.includes(S))d.push({old_text:S,new_text:C});else if(u==="strict"){let k=ir(i,S);return k?`ERROR: Patch ${b+1} old_text not found in ${s} (strict mode \u2014 exact match required)
|
|
312
312
|
Most similar text (line ${k.line}, distance ${k.distance}):
|
|
313
|
-
${k.text}`:`ERROR: Patch ${
|
|
314
|
-
Most similar text (line ${
|
|
315
|
-
${
|
|
313
|
+
${k.text}`:`ERROR: Patch ${b+1} old_text not found in ${s} (strict mode \u2014 exact match required)`}else{let k=Lm(i,S);if(k)d.push({old_text:k,new_text:C}),f=!0;else{let x=ir(i,S);if(x){let E=Math.max(3,Math.ceil(S.length*.05));if(x.distance<=E)d.push({old_text:x.text,new_text:C}),p=!0;else return`ERROR: Patch ${b+1} old_text not found in ${s}
|
|
314
|
+
Most similar text (line ${x.line}, distance ${x.distance}):
|
|
315
|
+
${x.text}`}else return`ERROR: Patch ${b+1} old_text not found in ${s}`}}}let g=i;for(let{old_text:b,new_text:S}of d)g=g.split(b).join(S);if(!n.autoConfirm){let b=await or(s,g);if(zi(s,i,g,{annotations:b}),!await sr(f?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await et.writeFile(s,g,"utf-8");let m=/[/\\]\.git[/\\]hooks[/\\]/.test(s)||s.endsWith(".sh")||g.startsWith("#!");m&&await et.chmod(s,493),Xi("patch_file",s,i,g);let h=p?" (auto-fixed)":f?" (fuzzy match)":"",y=m?" [chmod +x applied]":"";return`Patched: ${s} (${r.length} replacements)${h}${y}`}case"web_fetch":{let s=e.url,o=e.max_length||1e4;try{let r=await cl.get(s,{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 ${s}: ${r.message}`}}case"web_search":{let s=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await cl.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||[],c=`[Perplexity grounded search]
|
|
316
316
|
|
|
317
317
|
${r}`;return i.length>0&&(c+=`
|
|
318
318
|
|
|
319
319
|
Sources:
|
|
320
320
|
`+i.slice(0,s).map((l,u)=>`${u+1}. ${l}`).join(`
|
|
321
|
-
`)),c}catch(o){console.error(`${$e.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${$e.reset}`)}try{let r=(await
|
|
321
|
+
`)),c}catch(o){console.error(`${$e.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${$e.reset}`)}try{let r=(await cl.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],c=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=c.exec(r))!==null&&i.length<s;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],d=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:d,url:decodeURIComponent(u)})}catch{i.push({title:d,url:u})}}return i.length===0?"(no results)":i.map((u,d)=>`${d+1}. ${u.title}
|
|
322
322
|
${u.url}`).join(`
|
|
323
323
|
|
|
324
|
-
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:s}=
|
|
324
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:s}=Ko();try{let o=await s(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
|
|
325
325
|
|
|
326
326
|
Links:
|
|
327
327
|
`+o.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
|
|
328
328
|
`):"";return`Title: ${o.title}
|
|
329
329
|
URL: ${o.url}
|
|
330
330
|
|
|
331
|
-
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:s}=
|
|
331
|
+
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:s}=Ko();try{let o=await s(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
|
|
332
332
|
Title: ${o.title}
|
|
333
333
|
URL: ${o.url}
|
|
334
334
|
|
|
335
|
-
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:s}=
|
|
335
|
+
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:s}=Ko();try{return await s(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:s}=Ko();try{return await s(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"ask_user":{let{question:s,options:o=[]}=e;return dl?new Promise(r=>{ws=()=>r("CANCELLED"),dl(s,o).then(i=>{ws=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});ws=()=>{i.close(),r("CANCELLED")};let c=o.length>0?`
|
|
336
336
|
${o.map((l,u)=>` ${u+1}. ${l}`).join(`
|
|
337
337
|
`)}
|
|
338
338
|
`:"";console.log(`
|
|
339
|
-
${$e.cyan}${$e.bold} ? ${s}${$e.reset}${c}`),i.question(`${$e.cyan} > ${$e.reset}`,l=>{
|
|
339
|
+
${$e.cyan}${$e.bold} ? ${s}${$e.reset}${c}`),i.question(`${$e.cyan} > ${$e.reset}`,l=>{ws=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await ll())return"ERROR: Not a git repository";let s=await Pm()||"(detached)",o=await Ax();if(o.length===0)return`Branch: ${s}
|
|
340
340
|
Clean working tree (no changes)`;let r=[`Branch: ${s}`,`Changed files (${o.length}):`];for(let i of o){let c=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${c}: ${i.file}`)}return r.join(`
|
|
341
|
-
`)}case"git_diff":{if(!await
|
|
341
|
+
`)}case"git_diff":{if(!await ll())return"ERROR: Not a git repository";let s;if(e.file){let o=["diff"];e.staged&&o.push("--cached"),o.push("--",e.file);try{s=execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{s=""}}else s=await Ox(!!e.staged);return s||"(no diff)"}case"git_log":{if(!await ll())return"ERROR: Not a git repository";let o=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&o.push("--",e.file);try{return execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:s,updateTask:o,getTaskList:r,renderTaskList:i,hasActiveTasks:c}=Li(),{getActiveTaskProgress:l}=Ke(),u=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let d=s(e.name,e.tasks);return u||console.log(`
|
|
342
342
|
`+i()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
343
343
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
344
344
|
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":o(e.task_id,e.status,e.result)?(u||console.log(`
|
|
345
345
|
`+i()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let d=r();return d.tasks.length===0?"No active tasks":(u||console.log(`
|
|
346
|
-
`+i()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:s}=
|
|
346
|
+
`+i()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:s}=Bi();return s(e)}case"switch_model":{let{setActiveModel:s,getActiveProviderName:o,getActiveModelId:r}=Be();return s(e.model)?`Switched to ${o()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let s=Math.min(e.limit||10,30),o=["run","list","--limit",String(s),"--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 We(`gh ${o.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let u=l.conclusion||l.status||"unknown",d=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",f=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${d} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${u} \xB7 ${f}`}).join(`
|
|
347
347
|
`)}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(`
|
|
348
348
|
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await We(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
|
|
349
349
|
...(truncated)`:"")}let{stdout:s}=await We(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(s),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 c=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${c} ${i.name} (${i.conclusion||i.status})`);for(let l of i.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${l.name}`)}}return r.join(`
|
|
350
350
|
`)}catch(s){return`ERROR: ${(s.stderr||s.message||"").toString().split(`
|
|
351
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:s}
|
|
351
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:s}=$t(),o=e.branch||await Pm()||"main",r=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",i=`gh workflow run ${e.workflow} --ref ${o} ${r}`.trim();if(console.log(`
|
|
352
352
|
${$e.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${$e.reset}`),!await s(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await We(i,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(l){return`ERROR: ${(l.stderr||l.message||"").toString().split(`
|
|
353
|
-
`)[0]}`}}case"k8s_pods":{let s=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=
|
|
354
|
-
`)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let s=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${s} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=
|
|
353
|
+
`)[0]}`}}case"k8s_pods":{let s=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=rr(`get pods ${s} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:c}=await We(r,{timeout:3e4,maxBuffer:2097152});return(i||c||"(no pods)").trim()}catch(i){let c=(i.stderr||i.message||"").toString().split(`
|
|
354
|
+
`)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let s=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${s} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=rr(r,e);try{let{stdout:c,stderr:l}=await We(i,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
|
|
355
355
|
...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
356
356
|
`)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let s=e.namespace||"default";if(console.log(`
|
|
357
|
-
${$e.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${s})${$e.reset}`),console.log(`${$e.dim} Command: ${e.command}${$e.reset}`),!await
|
|
357
|
+
${$e.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${s})${$e.reset}`),console.log(`${$e.dim} Command: ${e.command}${$e.reset}`),!await nn(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${s}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=rr(r,e);try{let{stdout:c,stderr:l}=await We(i,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
358
358
|
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let s=!!e.dry_run;if(!s){let i=e.file;if(console.log(`
|
|
359
|
-
${$e.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${$e.reset}`),!await
|
|
359
|
+
${$e.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${$e.reset}`),!await nn(" Apply to cluster?"))return"CANCELLED: User declined."}let o=`apply -f ${e.file}`;e.namespace&&(o+=` -n ${e.namespace}`),s&&(o+=" --dry-run=client");let r=rr(o,e);try{let{stdout:i,stderr:c}=await We(r,{timeout:12e4,maxBuffer:2097152});return(i||c||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
|
|
360
360
|
`)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let s=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let c=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
|
|
361
|
-
${$e.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${s})${$e.reset}`),!await
|
|
362
|
-
`)[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:s,readDocument:o}=
|
|
361
|
+
${$e.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${s})${$e.reset}`),!await nn(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${s}`,i=rr(r,e);try{let{stdout:c,stderr:l}=await We(i,{timeout:12e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
362
|
+
`)[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:s,readDocument:o}=Qo(),{name:r,content:i,mode:c}=e;if(c==="create"&&o(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(c==="append"){let l=o(r),u=l.content?l.content+`
|
|
363
363
|
|
|
364
|
-
`+i:i;return s(r,u),`Appended to brain document: ${r}.md`}return s(r,i),`${c==="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 s;try{s=
|
|
364
|
+
`+i:i;return s(r,u),`Appended to brain document: ${r}.md`}return s(r,i),`${c==="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 s;try{s=zt(e.server)}catch(E){return`ERROR: ${E.message}`}let o=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,c=Sx(o);if(c)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:
|
|
365
365
|
grep -n "pattern" /path/to/file -A 50
|
|
366
366
|
or to read the whole file:
|
|
367
367
|
cat /path/to/file
|
|
368
368
|
NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${c}
|
|
369
|
-
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,(
|
|
370
|
-
${$e.yellow} \u26A0 Remote command on ${
|
|
369
|
+
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,(E,B,q)=>{let re=Math.min(Number(q),20);return`${B} ${re}`}),o=o.replace(/(--(?:before|after|context)=)(\d+)/g,(E,B,q)=>B+Math.min(Number(q),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 E=s.user?`${s.user}@${s.host}`:s.host;if(console.log(`
|
|
370
|
+
${$e.yellow} \u26A0 Remote command on ${E}: ${o}${$e.reset}`),!await nn(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:u,stderr:d,exitCode:f,error:p}=await Rt(s,o,{timeout:i,sudo:r}),g=[u,d].filter(Boolean).join(`
|
|
371
371
|
`).trim();if(f!==0)return`EXIT ${f}
|
|
372
372
|
${p||g||"(no output)"}`;let m=/\bgrep\b/.test(o),h=g;m&&(h=h.split(`
|
|
373
|
-
`).filter(
|
|
374
|
-
`));let y=m?60:100,
|
|
375
|
-
`);
|
|
376
|
-
`+
|
|
377
|
-
`));let
|
|
378
|
-
`),k=[],
|
|
379
|
-
`)||"(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 s;try{s=
|
|
380
|
-
${$e.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${$e.reset}`),!await
|
|
381
|
-
${g.slice(-2e3)}`:g.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 s=["status","start","stop","restart","reload","enable","disable"];if(!s.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${s.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!o)try{i=
|
|
382
|
-
${$e.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${$e.reset}`),!await
|
|
383
|
-
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await
|
|
373
|
+
`).filter(E=>E!=="--").join(`
|
|
374
|
+
`));let y=m?60:100,b=h.split(`
|
|
375
|
+
`);b.length>y&&(h=`(${b.length-y} earlier lines omitted \u2014 showing last ${y})
|
|
376
|
+
`+b.slice(-y).join(`
|
|
377
|
+
`));let S=4,C=h.split(`
|
|
378
|
+
`),k=[],x=0;for(;x<C.length;){let E=x+1;for(;E<C.length&&C[E]===C[x];)E++;let B=E-x;if(k.push(C[x]),B>S)k.push(`... (${B-1} identical lines omitted)`);else for(let q=1;q<B;q++)k.push(C[x]);x=E}return k.join(`
|
|
379
|
+
`)||"(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 s;try{s=zt(e.server)}catch(i){return`ERROR: ${i.message}`}let o=s.user?`${s.user}@${s.host}`:s.host;if(console.log(`
|
|
380
|
+
${$e.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${$e.reset}`),!await nn(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await Mx(s,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 s;try{s=zt(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await Px(s,e.remote_path,e.local_path)}catch(o){return`ERROR: ${o.message}`}}case"remote_agent":{let s=require("path").join(process.cwd(),".nex","servers.json"),o=null;try{o=JSON.parse(require("fs").readFileSync(s,"utf-8"))[e.server]||null}catch{}let r=o?`${o.user||"root"}@${o.host}`:e.server,i=o?.key?["-i",o.key]:[],c=e.project_path||o?.home||"~",l=e.model||"",d=["TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt)",`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${c}" 2>/dev/null || true`,l?`nex-code --prompt-file "$TMPFILE" --auto --model "${l}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:f}=require("child_process"),p=f("ssh",[...i,"-o","StrictHostKeyChecking=no","-o","ConnectTimeout=10",r,`bash -c '${d}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(p.error)return`ERROR: SSH connection failed: ${p.error.message}`;let g=(p.stdout||"")+(p.stderr||"");return p.status!==0?`Remote nex-code exited with code ${p.status}.
|
|
381
|
+
${g.slice(-2e3)}`:g.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 s=["status","start","stop","restart","reload","enable","disable"];if(!s.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${s.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!o)try{i=zt(e.server)}catch(l){return`ERROR: ${l.message}`}if(!r){let l=o?"local machine":i.user?`${i.user}@${i.host}`:i.host;if(console.log(`
|
|
382
|
+
${$e.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${$e.reset}`),!await nn(" Execute?"))return"CANCELLED: User declined service action."}let c=`systemctl ${e.action} ${e.service}`;if(o){let u=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:d,stderr:f}=await We(u,{timeout:15e3});return(d||f||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(d){let f=(d.stderr||d.message||"").toString().trim();return/not found|loaded.*not-found/i.test(f)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${d.code||1}
|
|
383
|
+
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await Rt(i,c,{timeout:15e3,sudo:!0}),p=[l,u].filter(Boolean).join(`
|
|
384
384
|
`).trim();return d!==0?/not found|loaded.*not-found/i.test(p)?`ERROR: Service "${e.service}" not found on ${i.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${d}
|
|
385
385
|
${f||p||"(no output)"}`:p||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let s=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${o} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(s)try{let{stdout:m,stderr:h}=await We(c,{timeout:15e3});return(m||h||"(no log output)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
386
|
-
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=
|
|
386
|
+
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=zt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:u,stderr:d,exitCode:f,error:p}=await Rt(l,c,{timeout:2e4}),g=[u,d].filter(Boolean).join(`
|
|
387
387
|
`).trim();return f!==0?`EXIT ${f}
|
|
388
388
|
${p||g||"(no output)"}`:g||"(no log output)"}case"container_list":{let s=!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(s)try{let{stdout:p,stderr:g}=await We(r,{timeout:1e4});return(p||g||"(no containers)").trim()}catch(p){return`EXIT ${p.code||1}
|
|
389
|
-
${(p.stderr||p.message||"").toString().trim()}`}let i;try{i=
|
|
389
|
+
${(p.stderr||p.message||"").toString().trim()}`}let i;try{i=zt(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await Rt(i,r,{timeout:15e3}),f=[c,l].filter(Boolean).join(`
|
|
390
390
|
`).trim();return u!==0?`EXIT ${u}
|
|
391
391
|
${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let s=!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(s)try{let{stdout:g,stderr:m}=await We(i,{timeout:15e3});return(g||m||"(no log output)").trim()}catch(g){return`EXIT ${g.code||1}
|
|
392
|
-
${(g.stderr||g.message||"").toString().trim()}`}let c;try{c=
|
|
392
|
+
${(g.stderr||g.message||"").toString().trim()}`}let c;try{c=zt(e.server)}catch(g){return`ERROR: ${g.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Rt(c,i,{timeout:2e4}),p=[l,u].filter(Boolean).join(`
|
|
393
393
|
`).trim();return d!==0?`EXIT ${d}
|
|
394
394
|
${f||p}`:p||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let s=!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(!n.autoConfirm&&!o.test(e.command.trim())){let m=s?"local":e.server;if(console.log(`
|
|
395
|
-
${$e.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${$e.reset}`),!await
|
|
396
|
-
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=
|
|
395
|
+
${$e.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${$e.reset}`),!await nn(" Execute?"))return"CANCELLED: User declined."}let i=(e.container||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(!i)return"ERROR: Invalid container name";let c=`docker exec ${i} sh -c ${JSON.stringify(e.command)}`;if(s)try{let{stdout:m,stderr:h}=await We(c,{timeout:3e4});return(m||h||"(no output)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
396
|
+
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=zt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:u,stderr:d,exitCode:f,error:p}=await Rt(l,c,{timeout:35e3}),g=[u,d].filter(Boolean).join(`
|
|
397
397
|
`).trim();return f!==0?`EXIT ${f}
|
|
398
398
|
${p||g}`:g||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let s=["start","stop","restart","remove","inspect"];if(!s.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${s.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!n.autoConfirm){let m=o?"local":e.server;if(console.log(`
|
|
399
|
-
${$e.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${$e.reset}`),!await
|
|
400
|
-
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=
|
|
399
|
+
${$e.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${$e.reset}`),!await nn(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,c=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(o)try{let{stdout:m,stderr:h}=await We(c,{timeout:3e4});return(m||h||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
|
|
400
|
+
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=zt(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:u,stderr:d,exitCode:f,error:p}=await Rt(l,c,{timeout:35e3}),g=[u,d].filter(Boolean).join(`
|
|
401
401
|
`).trim();return f!==0?`EXIT ${f}
|
|
402
|
-
${p||g}`:g||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...
|
|
402
|
+
${p||g}`:g||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...Lx(e.config),...e},delete e.config,delete e._name}catch(d){return`ERROR: ${d.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let s=e.method||"rsync";if(s==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let o;try{o=zt(e.server)}catch(d){return`ERROR: ${d.message}`}let r=o.user?`${o.user}@${o.host}`:o.host;if(!e.dry_run&&!n.autoConfirm){if(s==="git"){let f=e.branch?` (branch: ${e.branch})`:"";console.log(`
|
|
403
403
|
${$e.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${f}${$e.reset}`)}else{let f=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
|
|
404
|
-
${$e.yellow} \u26A0 Deploy [rsync]: ${f} \u2192 ${r}:${e.remote_path}${$e.reset}`)}if(e.deploy_script&&console.log(`${$e.yellow} Then run: ${e.deploy_script}${$e.reset}`),e.health_check&&console.log(`${$e.yellow} Health check: ${e.health_check}${$e.reset}`),!await
|
|
404
|
+
${$e.yellow} \u26A0 Deploy [rsync]: ${f} \u2192 ${r}:${e.remote_path}${$e.reset}`)}if(e.deploy_script&&console.log(`${$e.yellow} Then run: ${e.deploy_script}${$e.reset}`),e.health_check&&console.log(`${$e.yellow} Health check: ${e.health_check}${$e.reset}`),!await nn(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(s==="git"){let d=(e.branch||"").replace(/[^a-zA-Z0-9._\/-]/g,"");if(e.branch&&d!==e.branch)return`ERROR: Invalid branch name: ${e.branch}`;let f=(e.remote_path||"").replace(/'/g,"'\\''"),p=d?`cd '${f}' && git fetch origin && git checkout '${d}' && git pull origin '${d}'`:`cd '${f}' && git pull`;if(e.dry_run)return`DRY RUN [git]: would run on ${r}:
|
|
405
405
|
${p}${e.deploy_script?`
|
|
406
|
-
${e.deploy_script}`:""}`;let{stdout:g,stderr:m,exitCode:h,error:y}=await
|
|
406
|
+
${e.deploy_script}`:""}`;let{stdout:g,stderr:m,exitCode:h,error:y}=await Rt(o,p,{timeout:12e4});if(i=[g,m].filter(Boolean).join(`
|
|
407
407
|
`).trim(),h!==0)return`ERROR (git pull, exit ${h}):
|
|
408
408
|
${y||i}`}else{let d=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}"`:"",f=(e.exclude||[]).map(h=>`--exclude="${h}"`).join(" "),p=e.dry_run?"--dry-run":"",g=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,m=`rsync -avz --delete ${p} ${f} ${d} ${g} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:h,stderr:y}=await We(m,{timeout:12e4});i=(h||y||"").trim()}catch(h){return`ERROR (rsync): ${(h.stderr||h.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
|
|
409
|
-
${i||"(nothing to sync)"}`}let c="";if(e.deploy_script){let{stdout:d,stderr:f,exitCode:p,error:g}=await
|
|
409
|
+
${i||"(nothing to sync)"}`}let c="";if(e.deploy_script){let{stdout:d,stderr:f,exitCode:p,error:g}=await Rt(o,e.deploy_script,{timeout:12e4}),m=[d,f].filter(Boolean).join(`
|
|
410
410
|
`).trim();if(p!==0)return`${s==="git"?"git pull":"rsync"} OK
|
|
411
411
|
|
|
412
412
|
ERROR (deploy_script, exit ${p}):
|
|
@@ -419,50 +419,50 @@ Health check: \u2713 ${d} \u2192 ${g.status}`;else return l=`
|
|
|
419
419
|
|
|
420
420
|
Health check FAILED: ${d} \u2192 HTTP ${g.status}`,(s==="git"?"git pull OK":"rsync OK")+i+c+l}catch(p){return l=`
|
|
421
421
|
|
|
422
|
-
Health check FAILED: ${d} \u2192 ${p.message}`,(s==="git"?"git pull OK":"rsync OK")+i+c+l}else{let{stdout:p,stderr:g,exitCode:m}=await
|
|
422
|
+
Health check FAILED: ${d} \u2192 ${p.message}`,(s==="git"?"git pull OK":"rsync OK")+i+c+l}else{let{stdout:p,stderr:g,exitCode:m}=await Rt(o,d,{timeout:15e3}),h=[p,g].filter(Boolean).join(`
|
|
423
423
|
`).trim();if(m!==0)return l=`
|
|
424
424
|
|
|
425
425
|
Health check FAILED (exit ${m}): ${h}`,(s==="git"?"git pull OK":"rsync OK")+i+c+l;l=`
|
|
426
426
|
|
|
427
427
|
Health check: \u2713 ${h||"(exit 0)"}`}}let u=s==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${s}] ${u}
|
|
428
|
-
${i}${c}${l}`.trim()}case"deployment_status":{let s=
|
|
428
|
+
${i}${c}${l}`.trim()}case"deployment_status":{let s=Ix(),o=e.config?[e.config]:Object.keys(s);if(o.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of o){let c=s[i];if(!c){r.push(`${i}: NOT FOUND`);continue}try{let l=zt(c.server||i),d=(await Rt(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",f="unknown";if(d&&c.deploy_script){let g=c.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(g)try{f=(await Rt(l,`systemctl is-active ${g[1]}`,{timeout:1e4})).stdout.trim()}catch{f="inactive"}}let p="N/A";if(c.health_check){let g=c.health_check.trim();if(/^https?:\/\//.test(g))try{let m=require("node-fetch"),h=await Promise.race([m(g),new Promise((y,b)=>setTimeout(()=>b(new Error("timeout")),1e4))]);p=h.ok?"healthy":`HTTP ${h.status}`}catch(m){p=`unhealthy: ${m.message.substring(0,50)}`}else try{p=(await Rt(l,g,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{p="unhealthy"}}r.push(`${i}: server=${d?"reachable":"unreachable"} service=${f} health=${p}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
|
|
429
429
|
${r.join(`
|
|
430
|
-
`)}`}case"frontend_recon":{let s=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(k,
|
|
431
|
-
`),re=q.slice(0,
|
|
432
|
-
`);return q.length>
|
|
433
|
-
... (${q.length-
|
|
434
|
-
`).filter(Boolean)}catch{return[]}},d=async(k,
|
|
430
|
+
`)}`}case"frontend_recon":{let s=process.cwd(),o=(e.type||"").toLowerCase(),r=[],i=async(k,x=120)=>{try{let E=Fe.isAbsolute(k)?k:Fe.join(s,k),q=(await et.readFile(E,"utf8")).split(`
|
|
431
|
+
`),re=q.slice(0,x).join(`
|
|
432
|
+
`);return q.length>x?re+`
|
|
433
|
+
... (${q.length-x} more lines \u2014 use read_file for full content)`:re}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(k=>`-not -path "*/${k}/*"`).join(" "),u=async k=>{try{let{stdout:x}=await We(`find "${s}" -type f -name "${k}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return x.trim().split(`
|
|
434
|
+
`).filter(Boolean)}catch{return[]}},d=async(k,x)=>{try{let{stdout:E}=await We(`grep -rl "${k}" "${s}" --include="${x}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return E.trim().split(`
|
|
435
435
|
`).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
|
|
436
436
|
`);let f=[...await u("tailwind.config.js"),...await u("tailwind.config.ts"),...await u("tailwind.config.mjs")];if(f.length>0){let k=await i(f[0],80);k&&r.push(`### Tailwind config (${Fe.relative(s,f[0])})
|
|
437
437
|
\`\`\`js
|
|
438
438
|
${k}
|
|
439
|
-
\`\`\``)}else r.push("(no tailwind.config found)");let p=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],g=!1;for(let k of p){let
|
|
439
|
+
\`\`\``)}else r.push("(no tailwind.config found)");let p=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],g=!1;for(let k of p){let x=await u(k);for(let E of x){let B=await i(E,100);if(B&&B.includes(":root")){r.push(`### CSS Variables (${Fe.relative(s,E)})
|
|
440
440
|
\`\`\`css
|
|
441
441
|
${B}
|
|
442
|
-
\`\`\``),g=!0;break}}if(g)break}if(!g){let k=await d(":root","*.css");if(k.length>0){let
|
|
442
|
+
\`\`\``),g=!0;break}}if(g)break}if(!g){let k=await d(":root","*.css");if(k.length>0){let x=await i(k[0],100);x&&r.push(`### CSS Variables (${Fe.relative(s,k[0])})
|
|
443
443
|
\`\`\`css
|
|
444
|
-
${
|
|
444
|
+
${x}
|
|
445
445
|
\`\`\``),g=!0}}g||r.push("(no CSS custom properties / :root found)"),r.push(`
|
|
446
446
|
## STEP 2: Main Layout / Index Page
|
|
447
|
-
`);let m=["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 k of m){let
|
|
447
|
+
`);let m=["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 k of m){let x=await u(k);if(x.length>0){let E=await i(x[0],150);if(E){r.push(`### Main layout: ${Fe.relative(s,x[0])}
|
|
448
448
|
\`\`\`html
|
|
449
|
-
${
|
|
449
|
+
${E}
|
|
450
450
|
\`\`\``),h=!0;break}}}h||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
|
|
451
451
|
## STEP 3: Reference Component (same type)
|
|
452
452
|
`);let y=[];if(o){for(let k of["*.html","*.vue","*.jsx","*.tsx"])if(y=await d(o,k),y.length>0)break}if(y.length===0)try{let{stdout:k}=await We(`find "${s}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});y=k.trim().split(`
|
|
453
|
-
`).filter(Boolean)}catch{y=[]}if(y.length>0){let k=y[0],
|
|
453
|
+
`).filter(Boolean)}catch{y=[]}if(y.length>0){let k=y[0],x=await i(k,150);x?r.push(`### Reference: ${Fe.relative(s,k)}
|
|
454
454
|
\`\`\`html
|
|
455
|
-
${
|
|
455
|
+
${x}
|
|
456
456
|
\`\`\``):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(`
|
|
457
457
|
## STEP 4: Framework Stack
|
|
458
|
-
`);let
|
|
458
|
+
`);let b=[],S=await i(Fe.join(s,"package.json"),999);if(S){if((S.includes('"react"')||S.includes("'react'"))&&b.push("React"),S.includes('"vue"')||S.includes("'vue'")){let x=S.match(/"vue":\s*"[\^~]?(\d+)/);b.push(x?`Vue.js v${x[1]}`:"Vue.js")}let k=S.match(/"alpinejs":\s*"[\^~]?(\d+)/);k&&b.push(`Alpine.js v${k[1]} (\u26A0 v2 vs v3 API differs!)`),(S.includes('"htmx')||S.includes("'htmx"))&&b.push("HTMX"),S.includes('"tailwindcss"')&&b.push("Tailwind CSS"),S.includes('"bootstrap"')&&b.push("Bootstrap")}if((await jt(Fe.join(s,"manage.py"))||(await i(Fe.join(s,"requirements.txt"),50)||"").includes("Django"))&&b.push("Django (server-rendered templates)"),!b.some(k=>k.includes("Alpine"))){let k=await d("alpinejs","*.html");if(k.length>0){let E=(await i(k[0],30)||"").match(/alpinejs[@/]v?(\d)/);b.push(E?`Alpine.js v${E[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return b.some(k=>k.includes("HTMX"))||(await d("htmx","*.html")).length>0&&b.push("HTMX (via CDN)"),b.length>0?(r.push(b.map(k=>`- ${k}`).join(`
|
|
459
459
|
`)),r.push(`
|
|
460
460
|
\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(`
|
|
461
461
|
---
|
|
462
462
|
\u2705 Design recon complete. Now build consistently with the patterns above.`),r.join(`
|
|
463
|
-
`)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let s=!e.server||e.server==="local"||e.server==="localhost",o;if(!s)try{o=
|
|
463
|
+
`)}case"sysadmin":{if(!e.action)return"ERROR: action is required";let s=!e.server||e.server==="local"||e.server==="localhost",o;if(!s)try{o=zt(e.server)}catch(l){return`ERROR: ${l.message}`}let r=async(l,u=3e4)=>{if(s)try{let{stdout:d,stderr:f}=await We(l,{timeout:u});return{out:(d||f||"").trim(),exitCode:0}}catch(d){return{out:(d.stderr||d.message||"").toString().trim(),exitCode:d.code||1}}else{let{stdout:d,stderr:f,exitCode:p,error:g}=await Rt(o,l,{timeout:u}),m=[d,f].filter(Boolean).join(`
|
|
464
464
|
`).trim();return{out:g&&p!==0&&!d.trim()?(g+`
|
|
465
|
-
`+m).trim():m,exitCode:p}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!n.autoConfirm){let l=s?"local":e.server;if(!await
|
|
465
|
+
`+m).trim():m,exitCode:p}}};if(!(["audit","disk_usage","process_list","network_status","ssl_check","log_tail","find_large","journalctl"].includes(e.action)||e.action==="package"&&e.package_action==="list"||e.action==="user_manage"&&["list","info"].includes(e.user_action)||e.action==="firewall"&&e.firewall_action==="status"||e.action==="cron"&&e.cron_action==="list"||e.action==="service"&&["status","list_failed"].includes(e.service_action))&&!n.autoConfirm){let l=s?"local":e.server;if(!await nn(`sysadmin [${e.action}] on ${l} \u2014 proceed?`))return"Cancelled."}switch(e.action){case"audit":{let l=["echo '=== OS / KERNEL ==='","cat /etc/os-release 2>/dev/null | grep -E '^(NAME|VERSION)=' || uname -a","echo '=== UPTIME / LOAD ==='","uptime","echo '=== MEMORY / SWAP ==='","free -h","echo '=== DISK ==='","df -h --output=target,size,used,avail,pcent 2>/dev/null || df -h","echo '=== TOP 10 PROCESSES (CPU) ==='","ps aux --sort=-%cpu | head -11","echo '=== FAILED SYSTEMD UNITS ==='","systemctl list-units --state=failed --no-legend 2>/dev/null || echo '(systemctl not available)'","echo '=== RECENT ERRORS (journalctl) ==='","journalctl -p err --no-pager -n 15 2>/dev/null || echo '(journalctl not available)'","echo '=== LISTENING PORTS ==='","ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null || echo '(ss/netstat not available)'"].join(" && "),{out:u,exitCode:d}=await r(l,45e3);return u||`EXIT ${d}
|
|
466
466
|
(no output)`}case"disk_usage":{let l=e.path||"/",u=`df -h ${l}; echo '--- Top subdirs ---'; du -d1 -x -h ${l} 2>/dev/null | sort -rh | head -20`,{out:d,exitCode:f}=await r(u,3e4);return f!==0?`EXIT ${f}
|
|
467
467
|
${d}`:d}case"process_list":{let l=e.sort_by==="mem"?"4":"3",u=(e.limit||20)+1,d=`ps aux --sort=-${e.sort_by==="mem"?"%mem":"%cpu"} 2>/dev/null | head -${u} || ps aux | awk 'NR==1{print; next} {print | "sort -k${l} -rn"}' | head -${u}`,{out:f,exitCode:p}=await r(d,15e3);return p!==0?`EXIT ${p}
|
|
468
468
|
${f}`:f}case"network_status":{let l="ss -tlnp 2>/dev/null || netstat -tlnp 2>/dev/null; echo '--- Active connections ---'; ss -tnp 2>/dev/null | head -30",{out:u,exitCode:d}=await r(l,15e3);return d!==0?`EXIT ${d}
|
|
@@ -504,8 +504,8 @@ ${d}`:d||"(empty log)"}case"find_large":{let l=e.path||"/",u=e.limit||20,d=e.min
|
|
|
504
504
|
${p}`:p||`(no files larger than ${d} in ${l})`}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 l=e.service_name?e.service_name.includes(".")?e.service_name:`${e.service_name}.service`:"",u;switch(e.service_action){case"status":u=`systemctl status ${l} --no-pager -l 2>&1 | head -40`;break;case"list_failed":u="systemctl list-units --state=failed --no-legend 2>/dev/null";break;case"start":u=`systemctl start ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"stop":u=`systemctl stop ${l} && echo "${l} stopped"`;break;case"restart":u=`systemctl restart ${l} && systemctl status ${l} --no-pager -l 2>&1 | head -20`;break;case"reload":u=`systemctl reload ${l} 2>&1 || systemctl reload-or-restart ${l} 2>&1`;break;case"enable":u=`systemctl enable ${l} && echo "${l} enabled"`;break;case"disable":u=`systemctl disable ${l} && echo "${l} disabled"`;break;default:return`ERROR: Unknown service_action: ${e.service_action}`}let{out:d,exitCode:f}=await r(u,3e4);return f===0||e.service_action==="status"&&f===3?d||`service ${e.service_action} OK`:`EXIT ${f}
|
|
505
505
|
${d}`}case"kill_process":{if(!e.pid&&!e.process_name)return"ERROR: pid or process_name is required for kill_process";let l=e.signal||"SIGTERM",u;e.pid?u=`ps -p ${e.pid} -o pid,user,%cpu,%mem,etime,cmd 2>/dev/null && kill -${l} ${e.pid} && echo "Sent ${l} to PID ${e.pid}"`:u=`pgrep -a "${e.process_name}" 2>/dev/null | head -5 && pkill -${l} "${e.process_name}" && echo "Sent ${l} to all '${e.process_name}' processes"`;let{out:d,exitCode:f}=await r(u,15e3);return f!==0?`EXIT ${f}
|
|
506
506
|
${d}`:d}case"journalctl":{let l=e.lines||100,u=["journalctl","--no-pager","-n",String(l)];e.unit&&u.push("-u",e.unit.includes(".")?e.unit:`${e.unit}.service`),e.priority&&u.push("-p",e.priority),e.since&&u.push(`--since="${e.since}"`),u.push('2>/dev/null || echo "(journalctl not available)"');let{out:d,exitCode:f}=await r(u.join(" "),2e4);return f!==0?`EXIT ${f}
|
|
507
|
-
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:s}=
|
|
508
|
-
`)}function
|
|
507
|
+
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:s}=tn(),o=s(e.type,e.name,e.content,e.description);return o.ok?o.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${o.path}`:`ERROR: ${o.error}`}case"delete_memory":{let{deleteMemory:s}=tn();return s(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:s}=Si(),o=await s(t,e,n);return o!==null?o:`ERROR: Unknown tool: ${t}`}}}async function Kx(t,e,n={}){let{emit:s}=Si(),{logToolExecution:o}=il(),r=Date.now(),i=n.silent?null:Cx(t,e);if(!i){let l=await Dm(t,e,n);return o({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await s("onToolResult",{tool:t,args:e,result:l}),l}let c=new Rx(i);c.start();try{let l=await Dm(t,e,n);return c.stop(),o({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await s("onToolResult",{tool:t,args:e,result:l}),l}catch(l){throw c.stop(),o({tool:t,args:e,result:l.message,duration:Date.now()-r,success:!1}),l}}Um.exports={TOOL_DEFINITIONS:Hx,executeTool:Kx,resolvePath:Ct,autoFixPath:Vi,autoFixEdit:Fm,enrichBashError:qm,cancelPendingAskUser:Ux,setAskUserHandler:Bx,fileExists:jt}});var en=oe((RR,Wm)=>{Wm.exports=Bm()});var pl=oe((AR,Hm)=>{var{loadServerProfiles:ar,resolveProfile:CR,sshExec:Yx}=ro(),fl={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 Gx(){let t=ar();if(Object.keys(t).length===0)return null;let n=["## Remote Servers (.nex/servers.json)"];n.push(""),n.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[o,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,c=r.port&&Number(r.port)!==22?`:${r.port}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",u=r.sudo?", sudo available":"";n.push(`- **${o}**: ${i}${c}${l}${u}`)}let s=new Set;for(let o of Object.values(t))o.os&&fl[o.os]&&s.add(o.os);if(s.size>0){n.push("");for(let o of s){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;n.push(`### ${r} Notes`);for(let i of fl[o])n.push(`- ${i}`)}}return n.join(`
|
|
508
|
+
`)}function zx(t){let e=ar();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function Xx(){return Object.keys(ar())}function Vx(){let t=require("fs"),n=require("path").join(process.cwd(),"NEX.md"),s="";try{s=t.readFileSync(n,"utf-8")}catch{}let o=ar(),r=Object.keys(o);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],c=s.toLowerCase();if(!i.some(p=>c.includes(p)))return null;let u=r.map(p=>{let g=o[p],m=g.user?`${g.user}@${g.host}`:g.host,h=g.port&&Number(g.port)!==22?`:${g.port}`:"";return` - **${p}**: ${m}${h}${g.os?` (${g.os})`:""}`}).join(`
|
|
509
509
|
`),d=r.map(p=>o[p].log_path).filter(Boolean),f=d.length>0?`
|
|
510
510
|
- Server log paths: ${d.join(", ")}`:"";return`# Deployment Context (Auto-detected)
|
|
511
511
|
|
|
@@ -523,7 +523,7 @@ ${u}
|
|
|
523
523
|
- \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
|
|
524
524
|
- \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
|
|
525
525
|
|
|
526
|
-
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${
|
|
526
|
+
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${Jx(o)}`}function Jx(t){return Object.values(t).some(n=>n.host==="94.130.37.43")?`
|
|
527
527
|
|
|
528
528
|
## Server Debugging Rules
|
|
529
529
|
|
|
@@ -534,33 +534,35 @@ ${u}
|
|
|
534
534
|
- 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.
|
|
535
535
|
- 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.
|
|
536
536
|
- 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.
|
|
537
|
-
- 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
|
|
538
|
-
`+i.trim()}catch{return null}}
|
|
539
|
-
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function
|
|
540
|
-
`)}var
|
|
537
|
+
- 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 Zx(t){if(typeof t!="string")return null;let e=[...t.matchAll(/https?:\/\/([a-zA-Z0-9._-]+)/g)];if(e.length===0)return null;let n=ar();if(Object.keys(n).length===0)return null;let s=null,o=null;for(let[,i]of e){let c=i.toLowerCase().split(".");for(let[l,u]of Object.entries(n))if(c.includes(l.toLowerCase())){s=u,o=l;break}if(s)break;for(let[l,u]of Object.entries(n))if(u.host===i){s=u,o=l;break}if(s)break}if(!s||!o)return null;let r=["ss -tlnp 2>/dev/null | awk 'NR>1{print $4}' | grep -oE ':[0-9]+$' | sort -u | head -8","echo '---services---'","ps aux 2>/dev/null | grep -E '(node |python3 |gunicorn|uvicorn|ruby |java )' | grep -v grep | awk '{print $11, $12, $13}' | head -6","echo '---data---'","find /home -maxdepth 5 -name 'data' -type d 2>/dev/null | head -6"].join("; ");try{let{stdout:i}=await Yx(s,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let c=s.user?`${s.user}@${s.host}`:s.host;return`[Server context for "${o}" (${c}) \u2014 probed at task start]
|
|
538
|
+
`+i.trim()}catch{return null}}Hm.exports={getServerContext:Gx,getDeploymentContextBlock:Vx,hasServerOS:zx,getProfileNames:Xx,probeUrlServer:Zx,OS_HINTS:fl}});var Qi=oe((OR,Gm)=>{var vt=require("fs").promises,Km=require("fs"),it=require("path"),Ji=require("util").promisify(require("child_process").exec),{C:po}=Ke(),{getMergeConflicts:Ym}=Bn(),{getServerContext:Qx}=pl(),ev=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function tv(t){try{return Km.readFileSync(t,"utf-8").split(`
|
|
539
|
+
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function nv(t,e){for(let n of e)if(n===t||n.includes("*")&&new RegExp("^"+n.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function sv(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:s=[]}={}){let o=it.join(t,".gitignore"),r=[...s,...tv(o)],i=0,c=[it.basename(t)+"/"];function l(u,d,f){if(f>e||i>=n)return;let p;try{p=Km.readdirSync(u,{withFileTypes:!0})}catch{return}p.sort((m,h)=>m.isDirectory()!==h.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(h.name));let g=p.filter(m=>!(ev.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||nv(m.name,r)));for(let m=0;m<g.length;m++){if(i>=n){c.push(`${d}\u2514\u2500\u2500 \u2026 (truncated)`);break}let h=g[m],y=m===g.length-1,b=y?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",S=d+(y?" ":"\u2502 "),C=h.isDirectory()?h.name+"/":h.name;c.push(`${d}${b}${C}`),i++,h.isDirectory()&&l(it.join(u,h.name),S,f+1)}}return l(t,"",1),c.join(`
|
|
540
|
+
`)}var ml=new Map,mo=new Map,Zi=null,ov=3e4;async function wn(t){try{return await t()}catch{return null}}async function rv(){if(!Zi||Date.now()>Zi)return!1;let t=[it.join(process.cwd(),"package.json"),it.join(process.cwd(),"README.md"),it.join(process.cwd(),".gitignore")];for(let e of t)try{let n=await vt.stat(e),s=mo.get(e);if(!s||n.mtimeMs!==s)return!1}catch{if(mo.has(e))return!1}try{let e=it.join(process.cwd(),".git","HEAD"),n=await vt.stat(e),s=mo.get(e);if(!s||n.mtimeMs!==s)return!1}catch{}return!0}async function iv(){let t=[it.join(process.cwd(),"package.json"),it.join(process.cwd(),"README.md"),it.join(process.cwd(),".gitignore"),it.join(process.cwd(),".git","HEAD"),it.join(process.cwd(),"CLAUDE.md"),it.join(process.cwd(),".nex","CLAUDE.md")];for(let e of t)try{let n=await vt.stat(e);mo.set(e,n.mtimeMs)}catch{mo.delete(e)}}async function av(t){let e="fileContext",n=ml.get(e),s=!1;if(n&&await rv()&&(s=!0),!s){let u=[],d=it.join(t,"package.json");if(await wn(()=>vt.access(d).then(()=>!0).catch(()=>!1)))try{let k=await vt.readFile(d,"utf-8"),x=JSON.parse(k),E={name:x.name,version:x.version};x.scripts&&(E.scripts=Object.keys(x.scripts).slice(0,15)),x.dependencies&&(E.deps=Object.keys(x.dependencies).length),x.devDependencies&&(E.devDeps=Object.keys(x.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(E)}`)}catch{}let p=it.join(t,"README.md");if(await wn(()=>vt.access(p).then(()=>!0).catch(()=>!1))){let x=(await vt.readFile(p,"utf-8")).split(`
|
|
541
541
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
542
|
-
${
|
|
543
|
-
`)}`)}let m=
|
|
544
|
-
${
|
|
542
|
+
${x.join(`
|
|
543
|
+
`)}`)}let m=it.join(t,".gitignore");if(await wn(()=>vt.access(m).then(()=>!0).catch(()=>!1))){let k=await vt.readFile(m,"utf-8");u.push(`GITIGNORE:
|
|
544
|
+
${k.trim()}`)}let y=it.join(t,"CLAUDE.md");if(await wn(()=>vt.access(y).then(()=>!0).catch(()=>!1))){let k=await vt.readFile(y,"utf-8");k.trim()&&u.push(`PROJECT INSTRUCTIONS (CLAUDE.md):
|
|
545
|
+
${k.trim()}`)}let S=it.join(t,".nex","CLAUDE.md");if(await wn(()=>vt.access(S).then(()=>!0).catch(()=>!1))){let k=await vt.readFile(S,"utf-8");k.trim()&&u.push(`PRIVATE PROJECT INSTRUCTIONS (.nex/CLAUDE.md):
|
|
546
|
+
${k.trim()}`)}n=u.join(`
|
|
545
547
|
|
|
546
|
-
`),
|
|
548
|
+
`),ml.set(e,n),Zi=Date.now()+ov,await iv()}let o=[n],[r,i,c,l]=await Promise.all([wn(async()=>{let{stdout:u}=await Ji("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),wn(async()=>{let{stdout:u}=await Ji("git status --short",{cwd:t,timeout:5e3});return u.trim()}),wn(async()=>{let{stdout:u}=await Ji("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),Ym()]);if(r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
|
|
547
549
|
${i}`),c&&o.push(`RECENT COMMITS:
|
|
548
550
|
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
549
551
|
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
550
|
-
${u}`)}try{let u=
|
|
552
|
+
${u}`)}try{let u=Qx();u&&o.push(u)}catch{}return o.join(`
|
|
551
553
|
|
|
552
|
-
`)}async function Kx(t){let e=xt.join(t,"package.json"),n="";if(await Bn(()=>tn.access(e).then(()=>!0).catch(()=>!1)))try{let i=await tn.readFile(e,"utf-8"),c=JSON.parse(i);n=`${c.name||"?"} v${c.version||"?"}`}catch{}let[o,r]=await Promise.all([Bn(async()=>{let{stdout:i}=await zi("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),jm()]);if(r&&r.length>0){console.log(`${fo.red} \u26A0 ${r.length} unresolved merge conflict(s):${fo.reset}`);for(let i of r)console.log(`${fo.red} ${i.file}${fo.reset}`);console.log(`${fo.yellow} \u2192 Resolve conflicts before starting tasks${fo.reset}`)}console.log()}Dm.exports={gatherProjectContext:Hx,printContext:Kx,generateFileTree:Fx,_clearContextCache:()=>{ul.clear(),po.clear(),Xi=null}}});var sn=ne((rR,Um)=>{var nn=require("fs"),Ji=require("path"),{atomicWrite:Yx}=kn();function ar(){return Ji.join(process.cwd(),".nex","sessions")}function dl(){let t=ar();nn.existsSync(t)||nn.mkdirSync(t,{recursive:!0})}function fl(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Ji.join(ar(),`${e}.json`)}function pl(t,e,n={}){dl();let s=fl(t),o={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return Yx(s,JSON.stringify(o,null,2)),{path:s,name:t}}function qm(t){let e=fl(t);if(!nn.existsSync(e))return null;try{return JSON.parse(nn.readFileSync(e,"utf-8"))}catch{return null}}function Fm(){dl();let t=ar(),e=nn.readdirSync(t).filter(s=>s.endsWith(".json")),n=[];for(let s of e)try{let o=JSON.parse(nn.readFileSync(Ji.join(t,s),"utf-8"));n.push({name:o.name||s.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider,score:o.score!=null?o.score:null,scoreGrade:o.scoreGrade||null})}catch{}return n.sort((s,o)=>(o.updatedAt||"").localeCompare(s.updatedAt||""))}function Gx(t){let e=fl(t);return nn.existsSync(e)?(nn.unlinkSync(e),!0):!1}function zx(){let t=Fm();return t.length===0?null:qm(t[0].name)}var ws=null,On=null,ir=null;function Xx(t,e={}){t.length!==0&&(ws&&clearTimeout(ws),On=t,ir=e||{},ws=setTimeout(()=>{On&&On.length>0&&pl("_autosave",On,ir),ws=null,On=null,ir=null},5e3))}function Vx(){ws&&(clearTimeout(ws),ws=null),On&&On.length>0&&(pl("_autosave",On,ir),On=null,ir=null)}function Jx(){dl();let t=ar(),e=nn.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,s=new Date(n.getTime()-720*60*60*1e3),o=0;for(let r of e){let i=Ji.join(t,r);try{let c=nn.statSync(i);new Date(c.mtime)<s&&(nn.unlinkSync(i),o++)}catch{}}return o}Um.exports={saveSession:pl,loadSession:qm,listSessions:Fm,deleteSession:Gx,getLastSession:zx,autoSave:Xx,flushAutoSave:Vx,clearOldSessions:Jx,_getSessionsDir:ar}});var Zi=ne((iR,Xm)=>{"use strict";var cr=require("fs"),Bm=require("path");function Wm(t){let e=[];return t.forEach((n,s)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_use"&&e.push({name:o.name||"",input:o.input||{},index:s,id:o.id||null})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(o=>{let r=o.function?.name||o.name||"",i={};try{i=typeof o.function?.arguments=="string"?JSON.parse(o.function.arguments):o.function?.arguments||o.input||{}}catch{}e.push({name:r,input:i,index:s,id:o.id||null})}))}),e}function Zx(t){let e=new Set;return t.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&e.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_result"&&s.tool_use_id&&typeof s.content=="string"&&s.content.startsWith("BLOCKED:")&&e.add(s.tool_use_id)})}),e}function Hm(t){let e=[];return t.forEach((n,s)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{if(o&&o.type==="tool_result"){let r=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(o.content||"");e.push({content:r,index:s})}}),n.role==="tool"){let o=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:o,index:s})}}),e}function Km(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let s=n.content.filter(o=>o&&(o.type==="text"||typeof o=="string")).map(o=>typeof o=="string"?o:o.text||"").join("").trim();if(s)return s}}}return""}function Ym(t,e){let n=[];for(let s=t.length-1;s>=0&&n.length<e;s--){let o=t[s];if(o.role!=="assistant")continue;let r="";typeof o.content=="string"?r=o.content.trim():Array.isArray(o.content)&&(r=o.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function Gm(t){let e=new Map;for(let n of t){let s;try{s=JSON.stringify(n.input)}catch{s=String(n.input)}let o=`${n.name}|${s}`;e.set(o,(e.get(o)||0)+1)}return e}function zm(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,n=[],s=Wm(t),o=Hm(t),r=s.length,i=Zx(t),c=s.filter(v=>!v.id||!i.has(v.id));t.some(v=>v.role==="user"&&typeof v.content=="string"&&v.content.startsWith("[SYSTEM WARNING]")&&(v.content.includes("edited")||v.content.includes("bash command")||v.content.includes("grep pattern")||v.content.includes("re-read")||v.content.includes("already in your context")))&&(e-=2,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let u=s.find(v=>{let j=v.input?.command||v.input?.cmd||"";return/\bsed\s+-n\b/.test(j)});if(u){let v=(u.input?.command||u.input?.cmd||"").slice(0,80);o.some(A=>A.content.includes("BLOCKED: sed -n is forbidden")||A.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${v}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${v}`))}s.find(v=>{if(v.name!=="grep"&&v.name!=="bash"&&v.name!=="ssh_exec")return!1;let j=v.input?.command||v.input?.cmd||"",A=v.input?.pattern||"",I=`${j} ${A}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(I)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(I)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let f=t.some(v=>v.role==="assistant"),p=Km(t),m=Ym(t,3).some(v=>v.length>100&&!/^[^.!]{0,40}\?$/.test(v));if(f&&!m&&(p.length<80||/^[^.!]{0,40}\?$/.test(p))){e-=2;let v=p.length>0?`"${p.slice(0,60)}..."`:"(no assistant text found)";n.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${v}`)}r>40?(e-=1.5,n.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,n.push(`High tool call count: ${r} (>25 threshold)`)),t.some(v=>{let j=typeof v.content=="string"?v.content:Array.isArray(v.content)?v.content.map(A=>typeof A=="string"?A:A.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(j)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let w=Gm(c),x=0,C="";for(let[v,j]of w)j>x&&(x=j,C=v);if(x>=3){let[v]=C.split("|");e-=1,n.push(`Same tool call repeated ${x}\xD7 (tool: ${v})`)}let k=!1,S=t.findIndex(v=>v.role==="user"&&typeof v.content=="string"&&v.content.includes("[SYSTEM STOP]")&&v.content.includes('"valid":true'));S>=0&&s.filter(j=>j.index>S).length>0&&(k=!0),k&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let T=s.filter(v=>v.name==="ssh_exec");if(T.length>=8){let v=0,j=1;for(let A=1;A<T.length;A++)T[A].index<=T[A-1].index+2?j++:(v=Math.max(v,j),j=1);v=Math.max(v,j),v>=8&&(e-=.5,n.push(`SSH reconnect storm: ${v} consecutive SSH calls`))}f&&T.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(p)&&(e-=2,n.push("Surrender: model asked user to manually provide server output instead of gathering it"));let B=new Map;for(let v of c)if(v.name==="read_file"&&v.input?.path){let j=v.input.path;B.has(j)||B.set(j,{count:0,ranges:[]});let A=B.get(j);if(A.count++,v.input.line_start!=null){let I=v.input.line_start||1,M=v.input.line_end||I+350;A.ranges.push([I,M])}}function q(v,j,A){for(let[I,M]of A){let N=Math.max(v,I),E=Math.min(j,M);if(E>N){let J=E-N,ee=j-v||1;if(J/ee>=.7)return!0}}return!1}let re=0,ie="";for(let[v,j]of B){if(j.count<3)continue;if(j.ranges.length===j.count){let M=!1,N=[];for(let[E,J]of j.ranges){if(N.length>0&&q(E,J,N)){M=!0;break}N.push([E,J])}if(!M)continue}if(j.count-j.ranges.length<=2&&j.ranges.length>=1){let M=!1,N=[];for(let[E,J]of j.ranges){if(N.length>0&&q(E,J,N)){M=!0;break}N.push([E,J])}if(!M)continue}j.count>re&&(re=j.count,ie=v)}if(re>=3){e-=1;let v=ie.split("/").slice(-2).join("/");n.push(`read_file loop: "${v}" read ${re}\xD7 (file already in context)`)}let Q=0,O="";for(let[v,j]of B){if(j.ranges.length<4)continue;let A=[],I=!1;for(let[M,N]of j.ranges){if(A.length>0&&q(M,N,A)){I=!0;break}A.push([M,N])}!I&&j.ranges.length>Q&&(Q=j.ranges.length,O=v)}if(Q>=4){e-=.5;let v=O.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${v}" read in ${Q} sequential sections \u2014 use grep instead`)}let ke=new Map;for(let v of c)if(v.name==="grep"&&v.input?.path&&v.input?.pattern){let j=v.input.path;ke.has(j)||ke.set(j,new Set),ke.get(j).add(v.input.pattern)}let X=0,V="";for(let[v,j]of ke)v.split("/").pop().includes(".")&&j.size>X&&(X=j.size,V=v);if(X>=3){e-=.75;let v=V.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${v}" searched ${X}\xD7 with different patterns (file already in context)`)}{let v=new Set,j=new Set,A=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let M of s){if(M.name==="write_file"&&M.input?.path){let N=M.input.path.split("/").pop(),E=M.input.path.includes("/tests/");A.test(N)&&!E&&v.add(M.input.path)}if((M.name==="bash"||M.name==="ssh_exec")&&M.input?.command){let N=M.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(N)for(let E of N){let J=E.split(/\s+/),ee=J[J.length-1];for(let Z of v)(Z.endsWith(ee)||ee.endsWith(Z.split("/").pop()))&&j.add(Z)}}}let I=j.size;if(I>=1){let M=Math.min(I*.25,.5);e-=M;let N=[...j].map(E=>E.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${N} \u2014 write inline logic or use tests/ instead`)}}let fe=o.filter(v=>v.content.startsWith("EXIT")).length;fe>=10?(e-=1,n.push(`Bash exit-error storm: ${fe} tool results started with EXIT (repeated failing commands)`)):fe>=5&&(e-=.5,n.push(`Repeated bash errors: ${fe} tool results with non-zero exit code`));for(let v of t){if(v.role!=="assistant")continue;let j="";if(typeof v.content=="string"?j=v.content:Array.isArray(v.content)&&(j=v.content.filter(ee=>ee&&(ee.type==="text"||typeof ee=="string")).map(ee=>typeof ee=="string"?ee:ee.text||"").join("")),j.length<=5e3)continue;let A=j.split(/(?<=\. )/).filter(ee=>ee.trim().length>0);if(A.length<6)continue;let I=new Map;for(let ee=0;ee<=A.length-3;ee++){let Z=A.slice(ee,ee+3).join("").trim();Z.length>30&&I.set(Z,(I.get(Z)||0)+1)}let M=0,N="";for(let[ee,Z]of I)Z>M&&(M=Z,N=ee);if(M<3)continue;let J=N.length*M/j.length;if(J>=.4||M>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${M}\xD7 same paragraph, ${Math.round(J*100)}% repeated)`);break}}{let v=new Set(["read_file","list_directory","search_files","glob","grep"]),j=t.some(I=>Array.isArray(I.tool_calls)?I.tool_calls.some(M=>v.has(M.function?.name)):Array.isArray(I.content)?I.content.some(M=>M.type==="tool_use"&&v.has(M.name)):!1);t.some(I=>I.role==="assistant"&&typeof I.content=="string"&&(I.content.includes("## Steps")||I.content.includes("/plan approve")))&&!j&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let he=o.filter(v=>v.content.startsWith("BLOCKED:")&&!v.content.includes("BLOCKED: sed -n")&&!v.content.includes("SSH paused")&&!v.content.includes("SSH temporarily paused"));if(he.length>0){let v=Math.min(he.length*.5,1.5);e-=v,n.push(`${he.length} tool call${he.length===1?"":"s"} blocked (agent attempted denied actions)`)}let be=t.filter(v=>{let j=typeof v.content=="string"?v.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(j)}).length;if(be>0){let v=Math.min(be*1,2);e-=v,n.push(`Super-nuclear context wipe fired ${be}\xD7 (context collapse \u2014 task too large or read loops)`)}{let v=!1,j=!1,A=!1;for(let M of s){if(M.name!=="bash")continue;let N=(M.input?.command||M.input?.cmd||"").trim();!(/cat\s*>/.test(N)||/<</.test(N))&&/\bcat\s+\S/.test(N)&&(v=!0),/^\s*ls(\s|$)/.test(N)&&!/npm|yarn|pnpm|make|git\b/.test(N)&&(j=!0),/\bfind\s+\S/.test(N)&&!/git\b|npm\b|-exec\b/.test(N)&&(A=!0)}let I=[v,j,A].filter(Boolean).length;if(I>0){let M=Math.min(I*.25,.75);e-=M;let N=[];v&&N.push("cat (use read_file)"),j&&N.push("ls (use list_directory)"),A&&N.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${N.join(", ")}`)}}{let v=s.some(N=>(N.name==="write_file"||N.name==="Write")&&N.input?.path&&(N.input.path.endsWith("requirements.txt")||N.input.path.endsWith("Pipfile")||N.input.path.endsWith("pyproject.toml"))),j=s.some(N=>(N.name==="write_file"||N.name==="Write")&&N.input?.path&&N.input.path.endsWith("package.json")),A=s.filter(N=>(N.name==="bash"||N.name==="Bash")&&N.input?.command).map(N=>N.input.command),I=A.some(N=>/pip\s+install|python\s+-m\s+venv/.test(N)),M=A.some(N=>/npm\s+install/.test(N));v&&!I?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):j&&!M&&s.some(E=>(E.name==="write_file"||E.name==="Write")&&E.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(E.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(f){let v=t.find(N=>N.role==="assistant"),j="";v&&(typeof v.content=="string"?j=v.content:Array.isArray(v.content)&&(j=v.content.filter(N=>N&&(N.type==="text"||typeof N=="string")).map(N=>typeof N=="string"?N:N.text||"").join("")));let A=j.slice(0,400),I=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,M=A.split(`
|
|
553
|
-
`).find(N=>{let
|
|
554
|
-
`)[0]).trim().slice(0,40);n.push(`Thinking-chain leak: non-sequitur artifact at response start: "${N}"`)}}if(f&&r>0){let v=t.findIndex(A=>A.role==="assistant"),j=t.findIndex(A=>!!(Array.isArray(A.tool_calls)&&A.tool_calls.length>0||Array.isArray(A.content)&&A.content.some(I=>I&&I.type==="tool_use")));if(v!==-1&&j!==-1&&v<j){let A=t[v],I="";typeof A.content=="string"?I=A.content:Array.isArray(A.content)&&(I=A.content.filter(
|
|
555
|
-
`).filter(N=>N.trim()).length<5&&/^\s*\[/.test(I)&&!/\]\s*$/.test(I.trimEnd())&&j++}j>=1&&(e-=.75,n.push(`Shallow JSON read: ${j} .json file${j>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let v=o.filter(j=>/argument errors?/i.test(j.content)||/missing required (argument|parameter)/i.test(j.content)||/invalid argument/i.test(j.content));v.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${v.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):v.length>=2&&(e-=.25,n.push(`Tool argument errors: ${v.length} tool calls returned argument errors`))}{let v=!1,j=0,A=0;for(let I of c){if((I.name==="bash"||I.name==="Bash")&&I.input?.command&&/git\s+commit\b/.test(I.input.command)){v&&(A=Math.max(A,j)),v=!0,j=0;continue}v&&(I.name==="bash"||I.name==="Bash")&&I.input?.command&&/git\s+(status|diff|log|show)\b/.test(I.input.command)&&j++}A=Math.max(A,j),A>=3&&(e-=.75,n.push(`Post-commit verification waste: ${A} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let ye=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",
|
|
554
|
+
`)}async function cv(t){let e=it.join(t,"package.json"),n="";if(await wn(()=>vt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await vt.readFile(e,"utf-8"),c=JSON.parse(i);n=`${c.name||"?"} v${c.version||"?"}`}catch{}let[o,r]=await Promise.all([wn(async()=>{let{stdout:i}=await Ji("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Ym()]);if(r&&r.length>0){console.log(`${po.red} \u26A0 ${r.length} unresolved merge conflict(s):${po.reset}`);for(let i of r)console.log(`${po.red} ${i.file}${po.reset}`);console.log(`${po.yellow} \u2192 Resolve conflicts before starting tasks${po.reset}`)}console.log()}Gm.exports={gatherProjectContext:av,printContext:cv,generateFileTree:sv,_clearContextCache:()=>{ml.clear(),mo.clear(),Zi=null}}});var on=oe((NR,Vm)=>{var sn=require("fs"),ea=require("path"),{atomicWrite:lv}=Tn();function lr(){return ea.join(process.cwd(),".nex","sessions")}function hl(){let t=lr();sn.existsSync(t)||sn.mkdirSync(t,{recursive:!0})}function gl(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return ea.join(lr(),`${e}.json`)}function $l(t,e,n={}){hl();let s=gl(t),o={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return lv(s,JSON.stringify(o,null,2)),{path:s,name:t}}function zm(t){let e=gl(t);if(!sn.existsSync(e))return null;try{return JSON.parse(sn.readFileSync(e,"utf-8"))}catch{return null}}function Xm(){hl();let t=lr(),e=sn.readdirSync(t).filter(s=>s.endsWith(".json")),n=[];for(let s of e)try{let o=JSON.parse(sn.readFileSync(ea.join(t,s),"utf-8"));n.push({name:o.name||s.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider,score:o.score!=null?o.score:null,scoreGrade:o.scoreGrade||null})}catch{}return n.sort((s,o)=>(o.updatedAt||"").localeCompare(s.updatedAt||""))}function uv(t){let e=gl(t);return sn.existsSync(e)?(sn.unlinkSync(e),!0):!1}function dv(){let t=Xm();return t.length===0?null:zm(t[0].name)}var bs=null,Mn=null,cr=null;function fv(t,e={}){t.length!==0&&(bs&&clearTimeout(bs),Mn=t,cr=e||{},bs=setTimeout(()=>{Mn&&Mn.length>0&&$l("_autosave",Mn,cr),bs=null,Mn=null,cr=null},5e3))}function pv(){bs&&(clearTimeout(bs),bs=null),Mn&&Mn.length>0&&($l("_autosave",Mn,cr),Mn=null,cr=null)}function mv(){hl();let t=lr(),e=sn.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,s=new Date(n.getTime()-720*60*60*1e3),o=0;for(let r of e){let i=ea.join(t,r);try{let c=sn.statSync(i);new Date(c.mtime)<s&&(sn.unlinkSync(i),o++)}catch{}}return o}Vm.exports={saveSession:$l,loadSession:zm,listSessions:Xm,deleteSession:uv,getLastSession:dv,autoSave:fv,flushAutoSave:pv,clearOldSessions:mv,_getSessionsDir:lr}});var ta=oe((MR,oh)=>{"use strict";var ur=require("fs"),Jm=require("path");function Zm(t){let e=[];return t.forEach((n,s)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_use"&&e.push({name:o.name||"",input:o.input||{},index:s,id:o.id||null})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(o=>{let r=o.function?.name||o.name||"",i={};try{i=typeof o.function?.arguments=="string"?JSON.parse(o.function.arguments):o.function?.arguments||o.input||{}}catch{}e.push({name:r,input:i,index:s,id:o.id||null})}))}),e}function hv(t){let e=new Set;return t.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&e.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_result"&&s.tool_use_id&&typeof s.content=="string"&&s.content.startsWith("BLOCKED:")&&e.add(s.tool_use_id)})}),e}function Qm(t){let e=[];return t.forEach((n,s)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{if(o&&o.type==="tool_result"){let r=typeof o.content=="string"?o.content:Array.isArray(o.content)?o.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(o.content||"");e.push({content:r,index:s})}}),n.role==="tool"){let o=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:o,index:s})}}),e}function eh(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let s=n.content.filter(o=>o&&(o.type==="text"||typeof o=="string")).map(o=>typeof o=="string"?o:o.text||"").join("").trim();if(s)return s}}}return""}function th(t,e){let n=[];for(let s=t.length-1;s>=0&&n.length<e;s--){let o=t[s];if(o.role!=="assistant")continue;let r="";typeof o.content=="string"?r=o.content.trim():Array.isArray(o.content)&&(r=o.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function nh(t){let e=new Map;for(let n of t){let s;try{s=JSON.stringify(n.input)}catch{s=String(n.input)}let o=`${n.name}|${s}`;e.set(o,(e.get(o)||0)+1)}return e}function sh(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,n=[],s=Zm(t),o=Qm(t),r=s.length,i=hv(t),c=s.filter(v=>!v.id||!i.has(v.id));t.some(v=>v.role==="user"&&typeof v.content=="string"&&v.content.startsWith("[SYSTEM WARNING]")&&(v.content.includes("edited")||v.content.includes("bash command")||v.content.includes("grep pattern")||v.content.includes("re-read")||v.content.includes("already in your context")))&&(e-=2,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let u=s.find(v=>{let j=v.input?.command||v.input?.cmd||"";return/\bsed\s+-n\b/.test(j)});if(u){let v=(u.input?.command||u.input?.cmd||"").slice(0,80);o.some(A=>A.content.includes("BLOCKED: sed -n is forbidden")||A.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${v}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${v}`))}s.find(v=>{if(v.name!=="grep"&&v.name!=="bash"&&v.name!=="ssh_exec")return!1;let j=v.input?.command||v.input?.cmd||"",A=v.input?.pattern||"",I=`${j} ${A}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(I)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(I)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let f=t.some(v=>v.role==="assistant"),p=eh(t),m=th(t,3).some(v=>v.length>100&&!/^[^.!]{0,40}\?$/.test(v));if(f&&!m&&(p.length<80||/^[^.!]{0,40}\?$/.test(p))){e-=2;let v=p.length>0?`"${p.slice(0,60)}..."`:"(no assistant text found)";n.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${v}`)}r>40?(e-=1.5,n.push(`Excessive tool calls: ${r} (>40 threshold)`)):r>25&&(e-=.5,n.push(`High tool call count: ${r} (>25 threshold)`)),t.some(v=>{let j=typeof v.content=="string"?v.content:Array.isArray(v.content)?v.content.map(A=>typeof A=="string"?A:A.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(j)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let b=nh(c),S=0,C="";for(let[v,j]of b)j>S&&(S=j,C=v);if(S>=3){let[v]=C.split("|");e-=1,n.push(`Same tool call repeated ${S}\xD7 (tool: ${v})`)}let k=!1,x=t.findIndex(v=>v.role==="user"&&typeof v.content=="string"&&v.content.includes("[SYSTEM STOP]")&&v.content.includes('"valid":true'));x>=0&&s.filter(j=>j.index>x).length>0&&(k=!0),k&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let E=s.filter(v=>v.name==="ssh_exec");if(E.length>=8){let v=0,j=1;for(let A=1;A<E.length;A++)E[A].index<=E[A-1].index+2?j++:(v=Math.max(v,j),j=1);v=Math.max(v,j),v>=8&&(e-=.5,n.push(`SSH reconnect storm: ${v} consecutive SSH calls`))}f&&E.length>0&&/\b(Könntest du|könntest du|Bitte (bereitstellen|kopier)|kannst du mir .* bereitstellen|could you (provide|share|paste)|please (provide|share|run .* and paste)|I (cannot|can't) access the server|nicht (auf den Server )?zugreifen|SSH .* (nicht verfügbar|unavailable|temporarily unavailable))\b/i.test(p)&&(e-=2,n.push("Surrender: model asked user to manually provide server output instead of gathering it"));let B=new Map;for(let v of c)if(v.name==="read_file"&&v.input?.path){let j=v.input.path;B.has(j)||B.set(j,{count:0,ranges:[]});let A=B.get(j);if(A.count++,v.input.line_start!=null){let I=v.input.line_start||1,M=v.input.line_end||I+350;A.ranges.push([I,M])}}function q(v,j,A){for(let[I,M]of A){let N=Math.max(v,I),T=Math.min(j,M);if(T>N){let J=T-N,ee=j-v||1;if(J/ee>=.7)return!0}}return!1}let re=0,ie="";for(let[v,j]of B){if(j.count<3)continue;if(j.ranges.length===j.count){let M=!1,N=[];for(let[T,J]of j.ranges){if(N.length>0&&q(T,J,N)){M=!0;break}N.push([T,J])}if(!M)continue}if(j.count-j.ranges.length<=2&&j.ranges.length>=1){let M=!1,N=[];for(let[T,J]of j.ranges){if(N.length>0&&q(T,J,N)){M=!0;break}N.push([T,J])}if(!M)continue}j.count>re&&(re=j.count,ie=v)}if(re>=3){e-=1;let v=ie.split("/").slice(-2).join("/");n.push(`read_file loop: "${v}" read ${re}\xD7 (file already in context)`)}let Q=0,O="";for(let[v,j]of B){if(j.ranges.length<4)continue;let A=[],I=!1;for(let[M,N]of j.ranges){if(A.length>0&&q(M,N,A)){I=!0;break}A.push([M,N])}!I&&j.ranges.length>Q&&(Q=j.ranges.length,O=v)}if(Q>=4){e-=.5;let v=O.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${v}" read in ${Q} sequential sections \u2014 use grep instead`)}let Te=new Map;for(let v of c)if(v.name==="grep"&&v.input?.path&&v.input?.pattern){let j=v.input.path;Te.has(j)||Te.set(j,new Set),Te.get(j).add(v.input.pattern)}let X=0,V="";for(let[v,j]of Te)v.split("/").pop().includes(".")&&j.size>X&&(X=j.size,V=v);if(X>=3){e-=.75;let v=V.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${v}" searched ${X}\xD7 with different patterns (file already in context)`)}{let v=new Set,j=new Set,A=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let M of s){if(M.name==="write_file"&&M.input?.path){let N=M.input.path.split("/").pop(),T=M.input.path.includes("/tests/");A.test(N)&&!T&&v.add(M.input.path)}if((M.name==="bash"||M.name==="ssh_exec")&&M.input?.command){let N=M.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(N)for(let T of N){let J=T.split(/\s+/),ee=J[J.length-1];for(let Z of v)(Z.endsWith(ee)||ee.endsWith(Z.split("/").pop()))&&j.add(Z)}}}let I=j.size;if(I>=1){let M=Math.min(I*.25,.5);e-=M;let N=[...j].map(T=>T.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${N} \u2014 write inline logic or use tests/ instead`)}}let fe=o.filter(v=>v.content.startsWith("EXIT")).length;fe>=10?(e-=1,n.push(`Bash exit-error storm: ${fe} tool results started with EXIT (repeated failing commands)`)):fe>=5&&(e-=.5,n.push(`Repeated bash errors: ${fe} tool results with non-zero exit code`));for(let v of t){if(v.role!=="assistant")continue;let j="";if(typeof v.content=="string"?j=v.content:Array.isArray(v.content)&&(j=v.content.filter(ee=>ee&&(ee.type==="text"||typeof ee=="string")).map(ee=>typeof ee=="string"?ee:ee.text||"").join("")),j.length<=5e3)continue;let A=j.split(/(?<=\. )/).filter(ee=>ee.trim().length>0);if(A.length<6)continue;let I=new Map;for(let ee=0;ee<=A.length-3;ee++){let Z=A.slice(ee,ee+3).join("").trim();Z.length>30&&I.set(Z,(I.get(Z)||0)+1)}let M=0,N="";for(let[ee,Z]of I)Z>M&&(M=Z,N=ee);if(M<3)continue;let J=N.length*M/j.length;if(J>=.4||M>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${M}\xD7 same paragraph, ${Math.round(J*100)}% repeated)`);break}}{let v=new Set(["read_file","list_directory","search_files","glob","grep"]),j=t.some(I=>Array.isArray(I.tool_calls)?I.tool_calls.some(M=>v.has(M.function?.name)):Array.isArray(I.content)?I.content.some(M=>M.type==="tool_use"&&v.has(M.name)):!1);t.some(I=>I.role==="assistant"&&typeof I.content=="string"&&(I.content.includes("## Steps")||I.content.includes("/plan approve")))&&!j&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let he=o.filter(v=>v.content.startsWith("BLOCKED:")&&!v.content.includes("BLOCKED: sed -n")&&!v.content.includes("SSH paused")&&!v.content.includes("SSH temporarily paused"));if(he.length>0){let v=Math.min(he.length*.5,1.5);e-=v,n.push(`${he.length} tool call${he.length===1?"":"s"} blocked (agent attempted denied actions)`)}let be=t.filter(v=>{let j=typeof v.content=="string"?v.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(j)}).length;if(be>0){let v=Math.min(be*1,2);e-=v,n.push(`Super-nuclear context wipe fired ${be}\xD7 (context collapse \u2014 task too large or read loops)`)}{let v=!1,j=!1,A=!1;for(let M of s){if(M.name!=="bash")continue;let N=(M.input?.command||M.input?.cmd||"").trim();!(/cat\s*>/.test(N)||/<</.test(N))&&/\bcat\s+\S/.test(N)&&(v=!0),/^\s*ls(\s|$)/.test(N)&&!/npm|yarn|pnpm|make|git\b/.test(N)&&(j=!0),/\bfind\s+\S/.test(N)&&!/git\b|npm\b|-exec\b/.test(N)&&(A=!0)}let I=[v,j,A].filter(Boolean).length;if(I>0){let M=Math.min(I*.25,.75);e-=M;let N=[];v&&N.push("cat (use read_file)"),j&&N.push("ls (use list_directory)"),A&&N.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${N.join(", ")}`)}}{let v=s.some(N=>(N.name==="write_file"||N.name==="Write")&&N.input?.path&&(N.input.path.endsWith("requirements.txt")||N.input.path.endsWith("Pipfile")||N.input.path.endsWith("pyproject.toml"))),j=s.some(N=>(N.name==="write_file"||N.name==="Write")&&N.input?.path&&N.input.path.endsWith("package.json")),A=s.filter(N=>(N.name==="bash"||N.name==="Bash")&&N.input?.command).map(N=>N.input.command),I=A.some(N=>/pip\s+install|python\s+-m\s+venv/.test(N)),M=A.some(N=>/npm\s+install/.test(N));v&&!I?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):j&&!M&&s.some(T=>(T.name==="write_file"||T.name==="Write")&&T.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(T.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(f){let v=t.find(N=>N.role==="assistant"),j="";v&&(typeof v.content=="string"?j=v.content:Array.isArray(v.content)&&(j=v.content.filter(N=>N&&(N.type==="text"||typeof N=="string")).map(N=>typeof N=="string"?N:N.text||"").join("")));let A=j.slice(0,400),I=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,M=A.split(`
|
|
555
|
+
`).find(N=>{let T=N.trim();return T.length>0&&T.length<=30&&/^\d/.test(T)&&/=/.test(T)&&!/[a-zA-Z]/.test(T)});if(I.test(A)||M){e-=1.5;let N=(M||A.split(`
|
|
556
|
+
`)[0]).trim().slice(0,40);n.push(`Thinking-chain leak: non-sequitur artifact at response start: "${N}"`)}}if(f&&r>0){let v=t.findIndex(A=>A.role==="assistant"),j=t.findIndex(A=>!!(Array.isArray(A.tool_calls)&&A.tool_calls.length>0||Array.isArray(A.content)&&A.content.some(I=>I&&I.type==="tool_use")));if(v!==-1&&j!==-1&&v<j){let A=t[v],I="";typeof A.content=="string"?I=A.content:Array.isArray(A.content)&&(I=A.content.filter(T=>T&&(T.type==="text"||typeof T=="string")).map(T=>typeof T=="string"?T:T.text||"").join(""));let M=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(I),N=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(I);(M||N)&&(e-=1,n.push("Answer-before-verify: model gave concrete file paths/SSH commands before making any tool calls (paths guessed, not verified)"))}}if(f){let v=p;if(v.length>100){let A=(v.match(/^```/gm)||[]).length%2!==0,I=/"\s*:\s*$/.test(v.trimEnd()),M=/[,\[{]\s*$/.test(v.trimEnd());(A||I||M)&&(e-=.75,n.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let v=[];t.forEach((A,I)=>{let M=[];Array.isArray(A.tool_calls)&&A.tool_calls.forEach(N=>{if((N.function?.name||N.name||"")==="read_file"){let J={};try{J=typeof N.function?.arguments=="string"?JSON.parse(N.function.arguments):N.function?.arguments||{}}catch{}(J.path||"").endsWith(".json")&&M.push({id:N.id,path:J.path})}}),Array.isArray(A.content)&&A.content.forEach(N=>{N&&N.type==="tool_use"&&N.name==="read_file"&&(N.input?.path||"").endsWith(".json")&&M.push({id:N.id,path:N.input.path})}),M.forEach(N=>v.push({...N,msgIdx:I}))});let j=0;for(let A of v){let I=null;for(let N of t){if(N.role==="tool"&&N.tool_call_id===A.id&&typeof N.content=="string"){I=N.content;break}if(N.role==="user"&&Array.isArray(N.content)){let T=N.content.find(J=>J&&J.type==="tool_result"&&J.tool_use_id===A.id);if(T){I=typeof T.content=="string"?T.content:"";break}}}if(!I)continue;I.split(`
|
|
557
|
+
`).filter(N=>N.trim()).length<5&&/^\s*\[/.test(I)&&!/\]\s*$/.test(I.trimEnd())&&j++}j>=1&&(e-=.75,n.push(`Shallow JSON read: ${j} .json file${j>1?"s":""} read with < 5 lines \u2014 array was incomplete, model drew conclusions from truncated data`))}{let v=o.filter(j=>/argument errors?/i.test(j.content)||/missing required (argument|parameter)/i.test(j.content)||/invalid argument/i.test(j.content));v.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${v.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):v.length>=2&&(e-=.25,n.push(`Tool argument errors: ${v.length} tool calls returned argument errors`))}{let v=!1,j=0,A=0;for(let I of c){if((I.name==="bash"||I.name==="Bash")&&I.input?.command&&/git\s+commit\b/.test(I.input.command)){v&&(A=Math.max(A,j)),v=!0,j=0;continue}v&&(I.name==="bash"||I.name==="Bash")&&I.input?.command&&/git\s+(status|diff|log|show)\b/.test(I.input.command)&&j++}A=Math.max(A,j),A>=3&&(e-=.75,n.push(`Post-commit verification waste: ${A} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let ye=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",Re=n.length===0?`Clean session \u2014 no quality issues detected (${r} tool calls)`:`${n.length} issue${n.length===1?"":"s"} found \u2014 ${r} tool calls`;return{score:e,grade:ye,issues:n,summary:Re}}function gv(t){try{let{loadSession:e}=on(),n=e(t);return n?sh(n.messages||[]):null}catch{return null}}function $v(t,e=null){let{score:n,issues:s}=t,o=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(n>=8||s.length===0)return"";let c=s.map(d=>d.replace(/:\s+\d+.*$/,"").replace(/\s*\(.*?\)/,"").replace(/\s*—.*$/,""));if(n>=6){let d=c.slice(0,3),f=c.length-d.length,p=d.join(" \xB7 ");return f>0&&(p+=` (+${f})`),`
|
|
556
558
|
${o}${p}${r}`}let l="";for(let d of c.slice(0,4))l+=`
|
|
557
559
|
${i}\u26A0${r} ${o}${d}${r}`;let u=c.length-4;return u>0&&(l+=`
|
|
558
|
-
${o}(+${u} more)${r}`),l}function
|
|
560
|
+
${o}(+${u} more)${r}`),l}function yv(t,e={}){try{let n=Jm.join(process.cwd(),".nex");ur.existsSync(n)||ur.mkdirSync(n,{recursive:!0});let s=Jm.join(n,"benchmark-history.json"),o=[];if(ur.existsSync(s))try{o=JSON.parse(ur.readFileSync(s,"utf-8"))}catch{o=[]}Array.isArray(o)||(o=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};o.push(i),o.length>100&&(o=o.slice(o.length-100)),ur.writeFileSync(s,JSON.stringify(o,null,2))}catch{}}oh.exports={scoreMessages:sh,scoreSession:gv,formatScore:$v,appendScoreHistory:yv,_extractToolCalls:Zm,_extractToolResults:Qm,_getLastAssistantText:eh,_getLastNAssistantTexts:th,_countDuplicateToolCalls:nh}});var Kn=oe((PR,lh)=>{"use strict";var wv=require("os"),yl=require("path"),Hn=require("fs"),dr=yl.join(wv.homedir(),".nex-code","model-routing.json"),na={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}},rh=["agentic","frontend","sysadmin","data","coding"];function bv(t){if(!t||t.length<8)return null;for(let e of rh){let n=na[e];if(!n.pattern||n.pattern.test(t))return n}return na.coding}function fr(){try{if(Hn.existsSync(dr))return JSON.parse(Hn.readFileSync(dr,"utf-8"))}catch{}return{}}function ih(t){let e=na[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:fr()[t]||null}var ah={plan:10,implement:35,verify:8},wl={plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function ch(){let t=fr();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=Be();if(e()==="ollama")return wl}catch{}return process.env.NEX_PHASE_ROUTING==="1"?wl:null}function _v(t,e){let n=ch();return n?.[t]?n[t]:e?ih(e):null}function xv(t){return fr().phaseBudgets?.[t]||ah[t]||20}function vv(){return process.env.NEX_PHASE_ROUTING==="0"?!1:ch()!==null}function Sv(t){let e=yl.dirname(dr);Hn.existsSync(e)||Hn.mkdirSync(e,{recursive:!0});let n=fr(),s={...n,...t};!t.phases&&n.phases&&(s.phases=n.phases),!t.phaseBudgets&&n.phaseBudgets&&(s.phaseBudgets=n.phaseBudgets),Hn.writeFileSync(dr,JSON.stringify(s,null,2));try{let o=yl.join(e,".env"),r="";Hn.existsSync(o)&&(r=Hn.readFileSync(o,"utf-8"));let i=r.split(/\r?\n/),c=(l,u)=>{let d=i.findIndex(f=>f.startsWith(l+"="));d>=0?i[d]=`${l}=${u}`:i.push(`${l}=${u}`)};s.coding&&c("NEX_ROUTE_CODING",s.coding),s.frontend&&c("NEX_ROUTE_FRONTEND",s.frontend),s.sysadmin&&c("NEX_ROUTE_SYSADMIN",s.sysadmin),s.data&&c("NEX_ROUTE_DATA",s.data),s.agentic&&c("NEX_ROUTE_AGENTIC",s.agentic),s.phases&&(s.phases.plan&&c("NEX_PHASE_PLAN_MODEL",s.phases.plan),s.phases.implement&&c("NEX_PHASE_IMPLEMENT_MODEL",s.phases.implement),s.phases.verify&&c("NEX_PHASE_VERIFY_MODEL",s.phases.verify)),Hn.writeFileSync(o,i.filter(l=>l.trim()!=="").join(`
|
|
559
561
|
`)+`
|
|
560
|
-
`)}catch{}}
|
|
562
|
+
`)}catch{}}lh.exports={CATEGORIES:na,DETECTION_ORDER:rh,detectCategory:bv,getModelForCategory:ih,getModelForPhase:_v,getPhaseBudget:xv,isPhaseRoutingEnabled:vv,DEFAULT_PHASE_BUDGETS:ah,BUILTIN_PHASE_DEFAULTS:wl,saveRoutingConfig:Sv,loadRoutingConfig:fr,ROUTING_CONFIG_PATH:dr}});var ph=oe((LR,fh)=>{"use strict";var _s=require("fs"),pr=require("path"),kv=require("os"),{detectCategory:Ev}=Kn(),ho=pr.join(kv.homedir(),".nex-code","examples"),bl=pr.join(__dirname,"..","examples");function uh(t){try{let n=_s.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),s=n.match(/^user:\s*(.+)$/m);if(!s)return null;let o=s[1].trim(),r=n.indexOf(`
|
|
561
563
|
A: |`);if(r===-1)return null;let i=n.slice(r+5),c=[],l=0;for(let d of i.split(`
|
|
562
564
|
`))if(d.startsWith(" ")){for(;l>0;)c.push(""),l--;c.push(d.slice(2))}else if(d.trim()==="")c.length>0&&l++;else break;if(c.length===0)return null;let u=c.join(`
|
|
563
|
-
`).trim();return{user:o,assistant:u}}catch{return null}}function
|
|
565
|
+
`).trim();return{user:o,assistant:u}}catch{return null}}function dh(t){let e=`${t}.md`,n=pr.join(ho,e);if(_s.existsSync(n)){let o=uh(n);if(o)return o}let s=pr.join(bl,e);return _s.existsSync(s)?uh(s):null}function Tv(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=Ev(t);return e?dh(e.id):null}function Rv(){let t=new Set;for(let e of[ho,bl])try{for(let n of _s.readdirSync(e))n.endsWith(".md")&&t.add(n.replace(".md",""))}catch{}return[...t].sort()}function Cv(t,e){_s.existsSync(ho)||_s.mkdirSync(ho,{recursive:!0});let n=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
|
|
564
566
|
|
|
565
567
|
user: ${e.user}
|
|
566
568
|
|
|
@@ -568,14 +570,14 @@ A: |
|
|
|
568
570
|
${e.assistant.split(`
|
|
569
571
|
`).map(s=>` ${s}`).join(`
|
|
570
572
|
`)}
|
|
571
|
-
`;
|
|
573
|
+
`;_s.writeFileSync(pr.join(ho,`${t}.md`),n,"utf-8")}fh.exports={getFewShotForInput:Tv,loadExampleForCategory:dh,listAvailableExamples:Rv,savePrivateExample:Cv,PRIVATE_EXAMPLES_DIR:ho,BUNDLED_EXAMPLES_DIR:bl}});var hr=oe((jR,yh)=>{var Dt=require("fs"),go=require("path"),{C:IR}=Ke(),{atomicWrite:Av,withFileLockSync:Ov}=Tn(),sa={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"},$o={...sa};function mh(){let t=go.join(process.cwd(),".nex","config.json");if(Dt.existsSync(t))try{let e=JSON.parse(Dt.readFileSync(t,"utf-8"));e.permissions&&($o={...sa,...e.permissions})}catch{}}function Nv(){let t=go.join(process.cwd(),".nex"),e=go.join(t,"config.json");Dt.existsSync(t)||Dt.mkdirSync(t,{recursive:!0}),Ov(e,()=>{let n={};if(Dt.existsSync(e))try{n=JSON.parse(Dt.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=$o,Av(e,JSON.stringify(n,null,2))})}function hh(t){return $o[t]||"ask"}function Mv(t,e){return["allow","ask","deny"].includes(e)?($o[t]=e,!0):!1}function Pv(t){return hh(t)}function Lv(){return Object.entries($o).map(([t,e])=>({tool:t,mode:e}))}function Iv(){$o={...sa}}var mr={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 gh(){let t=go.join(process.cwd(),".nex","config.json");try{return Dt.existsSync(t)&&JSON.parse(Dt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function jv(t){let e=go.join(process.cwd(),".nex"),n=go.join(e,"config.json");Dt.existsSync(e)||Dt.mkdirSync(e,{recursive:!0});let s={};try{Dt.existsSync(n)&&(s=JSON.parse(Dt.readFileSync(n,"utf-8")))}catch{s={}}s.teamPermissions=t,Dt.writeFileSync(n,JSON.stringify(s,null,2),"utf-8")}function $h(){let t=gh();if(!t)return mr.admin;let e=t.role||"admin",n=mr[e]||mr.admin;return{...n,...t.overrides,blockedTools:[...n.blockedTools||[],...t.overrides?.blockedTools||[]]}}function Dv(t){let e=$h();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 qv(){return Object.entries(mr).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}mh();yh.exports={getPermission:hh,setPermission:Mv,checkPermission:Pv,listPermissions:Lv,loadPermissions:mh,savePermissions:Nv,resetPermissions:Iv,DEFAULT_PERMISSIONS:sa,PERMISSION_PRESETS:mr,loadPresetConfig:gh,savePresetConfig:jv,getEffectivePreset:$h,isToolAllowed:Dv,listPresets:qv}});var rn=oe((qR,vh)=>{var vs=require("fs"),oa=require("path"),DR=require("readline"),{C:Ie}=Ke(),Pe=null,xl=!1,vl=null,wh=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function ra(){return oa.join(process.cwd(),".nex","plans")}function bh(){let t=ra();vs.existsSync(t)||vs.mkdirSync(t,{recursive:!0})}function Fv(t,e=[]){return Pe={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(n=>({description:n.description||n,files:n.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},Pe}function Uv(){return Pe}function Bv(t){xl=t}function Wv(){return xl}function Hv(){return!Pe||Pe.status!=="draft"?!1:(Pe.status="approved",Pe.updatedAt=new Date().toISOString(),!0)}function Kv(){return!Pe||Pe.status!=="approved"?!1:(Pe.status="executing",!0)}function _l(t,e){return!Pe||t<0||t>=Pe.steps.length?!1:(Pe.steps[t].status=e,Pe.updatedAt=new Date().toISOString(),Pe.steps.every(n=>n.status==="done"||n.status==="skipped")&&(Pe.status="completed"),!0)}function Yv(t){if(!t)return`${Ie.dim}No active plan${Ie.reset}`;let e={draft:`${Ie.yellow}DRAFT${Ie.reset}`,approved:`${Ie.green}APPROVED${Ie.reset}`,executing:`${Ie.blue}EXECUTING${Ie.reset}`,completed:`${Ie.green}COMPLETED${Ie.reset}`},n=[];n.push(`
|
|
572
574
|
${Ie.bold}${Ie.cyan}Plan: ${t.task}${Ie.reset}`),n.push(`${Ie.dim}Status: ${e[t.status]||t.status}${Ie.reset}
|
|
573
575
|
`);for(let s=0;s<t.steps.length;s++){let o=t.steps[s],r;switch(o.status){case"done":r=`${Ie.green}\u2713${Ie.reset}`;break;case"in_progress":r=`${Ie.blue}\u2192${Ie.reset}`;break;case"skipped":r=`${Ie.dim}\u25CB${Ie.reset}`;break;default:r=`${Ie.dim} ${Ie.reset}`}n.push(` ${r} ${Ie.bold}Step ${s+1}:${Ie.reset} ${o.description}`),o.files.length>0&&n.push(` ${Ie.dim}Files: ${o.files.join(", ")}${Ie.reset}`)}return n.push(""),n.join(`
|
|
574
|
-
`)}function
|
|
576
|
+
`)}function Gv(t){if(t||(t=Pe),!t)return null;bh();let e=oa.join(ra(),`${t.name}.json`);return vs.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function zv(t){let e=oa.join(ra(),`${t}.json`);if(!vs.existsSync(e))return null;try{let n=JSON.parse(vs.readFileSync(e,"utf-8"));return Pe=n,n}catch{return null}}function Xv(){bh();let t=ra(),e=vs.readdirSync(t).filter(s=>s.endsWith(".json")),n=[];for(let s of e)try{let o=JSON.parse(vs.readFileSync(oa.join(t,s),"utf-8"));n.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return n.sort((s,o)=>(o.createdAt||"").localeCompare(s.createdAt||""))}function Vv(t){if(!t)return[];let e=[],n=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),s=n?n[1]:t,o=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=o.exec(s))!==null;){let c=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();c.length>3&&e.push({description:c,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let c=r[1].replace(/\*\*/g,"").trim();c.length>3&&e.push({description:c,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,c=[...t.matchAll(i)];for(let l=0;l<Math.min(e.length,c.length);l++){let u=c[l][1];e[l].files=u.split(/[,\s]+/).filter(d=>/[./]/.test(d)).slice(0,5)}}return e}function Jv(t){vl=t}function Zv(){return vl}function Qv(){Pe=null,xl=!1,vl=null,sS()}function eS(){return`
|
|
575
577
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
576
578
|
|
|
577
579
|
# Allowed Tools (read-only)
|
|
578
|
-
You may ONLY use these tools: ${[...
|
|
580
|
+
You may ONLY use these tools: ${[...wh].join(", ")}
|
|
579
581
|
Any other tool call will be blocked and returned with an error.
|
|
580
582
|
|
|
581
583
|
# MANDATORY: Read Before You Plan
|
|
@@ -619,23 +621,23 @@ Bullet list of potential issues and mitigations.
|
|
|
619
621
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
620
622
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
621
623
|
- Do NOT make any file changes \u2014 your role is analysis and planning only.
|
|
622
|
-
- 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
|
|
623
|
-
`),n=[],s=!1,o="";for(let r of e){let i=
|
|
624
|
-
`)}function
|
|
624
|
+
- 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 xs=0;function tS(){!Pe||Pe.status!=="executing"||(xs>0&&_l(xs-1,"done"),xs<Pe.steps.length&&(_l(xs,"in_progress"),xs++))}function nS(){if(!Pe||Pe.status!=="executing"||Pe.steps.length===0)return null;let t=Math.min(xs,Pe.steps.length),e=Pe.steps.length,n=Math.max(0,t-1),s=Pe.steps[n]?.description||"";return{current:t,total:e,description:s}}function sS(){xs=0}var _h=["interactive","semi-auto","autonomous"],xh="interactive";function oS(t){return _h.includes(t)?(xh=t,!0):!1}function rS(){return xh}vh.exports={createPlan:Fv,getActivePlan:Uv,setPlanMode:Bv,isPlanMode:Wv,approvePlan:Hv,startExecution:Kv,updateStep:_l,formatPlan:Yv,savePlan:Gv,loadPlan:zv,listPlans:Xv,clearPlan:Qv,getPlanModePrompt:eS,setPlanContent:Jv,getPlanContent:Zv,extractStepsFromText:Vv,advancePlanStep:tS,getPlanStepInfo:nS,PLAN_MODE_ALLOWED_TOOLS:wh,setAutonomyLevel:oS,getAutonomyLevel:rS,AUTONOMY_LEVELS:_h}});var Ph=oe((FR,Mh)=>{var{C:R}=Ke();function Sh(){return Math.max(10,(process.stdout.columns||80)-2)}function iS(t){if(!t)return"";let e=t.split(`
|
|
625
|
+
`),n=[],s=!1,o="";for(let r of e){let i=Sh();if(r.trim().startsWith("```")){if(s)n.push(`${R.dim}${"\u2500".repeat(40)}${R.reset}`),s=!1,o="";else{s=!0,o=r.trim().substring(3).trim();let c=o?` ${o} `:"";n.push(`${R.dim}${"\u2500".repeat(3)}${c}${"\u2500".repeat(Math.max(0,37-c.length))}${R.reset}`)}continue}if(s){n.push(` ${kl(r,o)}`);continue}if(r.startsWith("### ")){n.push(`${R.bold}${R.cyan} ${Ss(r.substring(4))}${R.reset}`);continue}if(r.startsWith("## ")){n.push(`${R.bold}${R.cyan} ${Ss(r.substring(3))}${R.reset}`);continue}if(r.startsWith("# ")){n.push(`${R.bold}${R.cyan}${Ss(r.substring(2))}${R.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let c=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),u=`${c}${R.cyan}\u2022${R.reset} ${ks(l)}`;n.push(Es(u,i,c+" "));continue}if(/^\s*\d+\.\s/.test(r)){let c=r.match(/^(\s*)(\d+)\.\s(.*)/);if(c){let l=c[1],u=c[2],d=c[3],f=`${l}${R.cyan}${u}.${R.reset} ${ks(d)}`,p=l+" ".repeat(u.length+2);n.push(Es(f,i,p));continue}}n.push(Es(ks(r),i))}return n.join(`
|
|
626
|
+
`)}function Ss(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function ks(t){return t?t.replace(/`([^`]+)`/g,`${R.cyan}$1${R.reset}`).replace(/\*\*([^*]+)\*\*/g,`${R.bold}$1${R.reset}`).replace(/\*([^*]+)\*/g,`${R.dim}$1${R.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${R.cyan}$1${R.reset} ${R.dim}($2)${R.reset}`):""}function kl(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?kh(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Eh(t):e==="json"||e==="jsonc"?Th(t):e==="python"||e==="py"?Rh(t):e==="go"||e==="golang"?Ch(t):e==="rust"||e==="rs"?Ah(t):e==="css"||e==="scss"||e==="less"?Oh(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Nh(t):t:""}function kh(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(o,`${R.yellow}$1${R.reset}`),r=r.replace(e,`${R.magenta}$1${R.reset}`),r=r.replace(n,`${R.green}$&${R.reset}`),r=r.replace(s,`${R.dim}$1${R.reset}`),r}function Eh(t){let e=/^(\s*)([\w-]+)/,n=/(--?\w[\w-]*)/g,s=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(n,`${R.cyan}$1${R.reset}`),r=r.replace(e,`$1${R.green}$2${R.reset}`),r=r.replace(s,`${R.yellow}$&${R.reset}`),r=r.replace(o,`${R.dim}$1${R.reset}`),r}function Th(t){let e=/("[\w-]+")\s*:/g,n=/:\s*("(?:[^"\\]|\\.)*")/g,s=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${R.cyan}$1${R.reset}:`),r=r.replace(n,`: ${R.green}$1${R.reset}`),r=r.replace(s,`: ${R.yellow}$1${R.reset}`),r=r.replace(o,`: ${R.magenta}$1${R.reset}`),r}function Rh(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,n=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,s=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(o,`${R.yellow}$1${R.reset}`),i=i.replace(e,`${R.magenta}$1${R.reset}`),i=i.replace(r,`${R.cyan}$1${R.reset}`),i=i.replace(n,`${R.green}$&${R.reset}`),i=i.replace(s,`${R.dim}$1${R.reset}`),i}function Ch(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,n=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${R.yellow}$1${R.reset}`),i=i.replace(n,`${R.cyan}$1${R.reset}`),i=i.replace(e,`${R.magenta}$1${R.reset}`),i=i.replace(s,`${R.green}$&${R.reset}`),i=i.replace(o,`${R.dim}$1${R.reset}`),i}function Ah(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,n=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,s=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,c=t;return c=c.replace(r,`${R.yellow}$1${R.reset}`),c=c.replace(n,`${R.cyan}$1${R.reset}`),c=c.replace(e,`${R.magenta}$1${R.reset}`),c=c.replace(i,`${R.yellow}$1${R.reset}`),c=c.replace(s,`${R.green}$&${R.reset}`),c=c.replace(o,`${R.dim}$1${R.reset}`),c}function Oh(t){let e=/^(\s*)([\w-]+)\s*:/,n=/:\s*([^;]+)/,s=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(i,`${R.yellow}$1${R.reset}`),c=c.replace(o,`${R.yellow}$1${R.reset}`),c=c.replace(e,`$1${R.cyan}$2${R.reset}:`),c=c.replace(s,`$1${R.magenta}$&${R.reset}`),c=c.replace(r,`${R.dim}$1${R.reset}`),c}function Nh(t){let e=/<\/?(\w[\w-]*)/g,n=/\s([\w-]+)=/g,s=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(o,`${R.dim}$1${R.reset}`),i=i.replace(s,`${R.green}$&${R.reset}`),i=i.replace(e,`<${R.magenta}$1${R.reset}`),i=i.replace(n,` ${R.cyan}$1${R.reset}=`),i=i.replace(r,`${R.yellow}$1${R.reset}`),i}function Es(t,e,n=""){if(!e||e<10)return t;let s="",o=0,r=-1,i=0,c=0,l=t.length;for(;i<l;){if(t[i]==="\x1B"){let u=i+1;if(u<l&&t[u]==="["){for(u++;u<l&&!/[a-zA-Z]/.test(t[u]);)u++;u<l&&u++}i=u;continue}if(t[i]===" "&&(r=i),o++,o>e&&r!==-1){s+=t.slice(c,r)+`
|
|
625
627
|
`+n,c=r+1,i=c,o=n.length,r=-1;continue}o>e&&r===-1&&(s+=t.slice(c,i)+`
|
|
626
|
-
`+n,c=i,o=n.length+1),i++}return s+=t.slice(c),s}function
|
|
627
|
-
`)}function
|
|
628
|
+
`+n,c=i,o=n.length+1),i++}return s+=t.slice(c),s}function aS(t,e){if(!t||t.length===0)return"";let n=t.map((i,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(i.length,l)}),s=n.map(i=>"\u2500".repeat(i+2)).join("\u253C"),o=t.map((i,c)=>` ${R.bold}${i.padEnd(n[c])}${R.reset} `).join("\u2502"),r=[];r.push(`${R.dim}\u250C${s.replace(/┼/g,"\u252C")}\u2510${R.reset}`),r.push(`${R.dim}\u2502${R.reset}${o}${R.dim}\u2502${R.reset}`),r.push(`${R.dim}\u251C${s}\u2524${R.reset}`);for(let i of e){let c=t.map((l,u)=>` ${(i[u]||"").padEnd(n[u])} `).join(`${R.dim}\u2502${R.reset}`);r.push(`${R.dim}\u2502${R.reset}${c}${R.dim}\u2502${R.reset}`)}return r.push(`${R.dim}\u2514${s.replace(/┼/g,"\u2534")}\u2518${R.reset}`),r.join(`
|
|
629
|
+
`)}function cS(t,e,n,s=30){let o=n>0?Math.round(e/n*100):0,r=Math.round(o/100*s),i=s-r,c=o>=100?R.green:o>50?R.yellow:R.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${R.dim}${"\u2591".repeat(i)}${R.reset} ${o}% (${e}/${n})`}var Sl=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}_cursorWrite(e){try{process.stderr.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let n=[0,1,2,3,4,3,2,1],s=n[this._cursorFrame%n.length],o="";for(let r=0;r<5;r++)o+=r===s?"\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 n;for(;(n=this.buffer.indexOf(`
|
|
628
630
|
`))!==-1;){let s=this.buffer.substring(0,n);this.buffer=this.buffer.substring(n+1),this._renderLine(s)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${R.dim}${"\u2500".repeat(40)}${R.reset}
|
|
629
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=
|
|
631
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=Sh();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${R.dim}${"\u2500".repeat(40)}${R.reset}
|
|
630
632
|
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let o=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${R.dim}${"\u2500".repeat(3)}${o}${"\u2500".repeat(Math.max(0,37-o.length))}${R.reset}
|
|
631
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
632
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${R.bold}${R.cyan} ${
|
|
633
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${R.bold}${R.cyan} ${
|
|
634
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${R.bold}${R.cyan}${
|
|
635
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${R.cyan}\u2022${R.reset} ${
|
|
636
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let o=e.match(/^(\s*)(\d+)\.\s(.*)/);if(o){let r=o[1],i=o[2],c=o[3],l=`${r}${R.cyan}${i}.${R.reset} ${
|
|
637
|
-
`);return}}let s=ks(
|
|
638
|
-
`)}};
|
|
633
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${kl(e,this.codeBlockLang)}
|
|
634
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${R.bold}${R.cyan} ${Ss(e.substring(4))}${R.reset}
|
|
635
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${R.bold}${R.cyan} ${Ss(e.substring(3))}${R.reset}
|
|
636
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${R.bold}${R.cyan}${Ss(e.substring(2))}${R.reset}
|
|
637
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let o=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${o}${R.cyan}\u2022${R.reset} ${ks(r)}`,c=Es(i,n,o+" ");this._safeWrite(`${c}
|
|
638
|
+
`);return}if(/^\s*\d+\.\s/.test(e)){let o=e.match(/^(\s*)(\d+)\.\s(.*)/);if(o){let r=o[1],i=o[2],c=o[3],l=`${r}${R.cyan}${i}.${R.reset} ${ks(c)}`,u=r+" ".repeat(i.length+2),d=Es(l,n,u);this._safeWrite(`${d}
|
|
639
|
+
`);return}}let s=Es(ks(e),n);this._safeWrite(`${s}
|
|
640
|
+
`)}};Mh.exports={renderMarkdown:iS,renderInline:ks,stripHeadingMarkers:Ss,highlightCode:kl,highlightJS:kh,highlightBash:Eh,highlightJSON:Th,highlightPython:Rh,highlightGo:Ch,highlightRust:Ah,highlightCSS:Oh,highlightHTML:Nh,renderTable:aS,renderProgress:cS,wrapAnsi:Es,StreamRenderer:Sl}});var Rl=oe((UR,Dh)=>{var{execSync:lS}=require("child_process"),El=require("path"),gr=require("fs"),Tl=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Lh(){return El.join(process.cwd(),".nex","hooks")}function uS(){return El.join(process.cwd(),".nex","config.json")}function Ih(){let t=uS();if(!gr.existsSync(t))return{};try{return JSON.parse(gr.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function ia(t){if(!Tl.includes(t))return[];let e=[],n=Lh(),s=El.join(n,t);gr.existsSync(s)&&e.push(s);let o=Ih();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function jh(t,e={},n=3e4){try{return{success:!0,exitCode:0,output:lS(t,{cwd:process.cwd(),encoding:"utf-8",timeout:n,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(s){let o=typeof s.status=="number"?s.status:1;return{success:!1,exitCode:o,blocked:o===2,output:s.stdout?s.stdout.trim():"",error:s.stderr?s.stderr.trim():s.message}}}function dS(t,e={}){let n=ia(t);if(n.length===0)return{results:[],blocked:!1};let s={};for(let[r,i]of Object.entries(e))s[`NEX_${r.toUpperCase()}`]=String(i);let o=[];for(let r of n){let i=jh(r,s);if(o.push({command:r,...i}),i.blocked&&t.startsWith("pre-")){let c=i.output||i.error||"hook blocked tool call";return{results:o,blocked:!0,blockReason:c}}if(!i.success&&t.startsWith("pre-"))break}return{results:o,blocked:!1}}function fS(t){return ia(t).length>0}function pS(){let t=[];for(let e of Tl){let n=ia(e);n.length>0&&t.push({event:e,commands:n})}return t}function mS(){let t=Lh();return gr.existsSync(t)||gr.mkdirSync(t,{recursive:!0}),t}Dh.exports={HOOK_EVENTS:Tl,loadHookConfig:Ih,getHooksForEvent:ia,executeHook:jh,runHooks:dS,hasHooks:fS,listHooks:pS,initHooksDir:mS}});var $r=oe((KR,Zh)=>{"use strict";var{callWithRetry:Fh,runSubAgent:hS,clearAllLocks:gS}=Bi(),{parseModelSpec:Uh,getActiveProviderName:BR,getActiveModelId:WR}=Be(),{detectCategory:$S,getModelForCategory:qh}=Kn(),{MultiProgress:yS,C:_e}=Ke(),{getModelBriefing:HR}=Ii(),Bh=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),aa=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),Wh="devstral-2:123b",Hh="kimi-k2.5",Kh=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
|
|
639
641
|
|
|
640
642
|
RULES:
|
|
641
643
|
- Output ONLY a JSON array, no markdown fences, no explanation.
|
|
@@ -650,7 +652,7 @@ RULES:
|
|
|
650
652
|
- If the request is simple (single goal), return an array with exactly 1 item.
|
|
651
653
|
|
|
652
654
|
USER REQUEST:
|
|
653
|
-
{prompt}`,
|
|
655
|
+
{prompt}`,Yh=`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.
|
|
654
656
|
|
|
655
657
|
RULES:
|
|
656
658
|
- Output ONLY a JSON object with these fields:
|
|
@@ -664,16 +666,16 @@ ORIGINAL REQUEST:
|
|
|
664
666
|
{prompt}
|
|
665
667
|
|
|
666
668
|
SUB-AGENT RESULTS:
|
|
667
|
-
{results}`;async function
|
|
668
|
-
${e.slice(0,200)}`)}async function
|
|
669
|
+
{results}`;async function Gh(t,e=1,n=2e3){for(let s=0;s<=e;s++)try{return await t()}catch(o){if(s===e)throw o;await new Promise(r=>setTimeout(r,n))}}function zh(t){let e=0,n=[];return function(){return new Promise(o=>{let r=()=>{e<t?(e++,o(()=>{e--,n.length>0&&n.shift()()})):n.push(r)};r()})}}function wS(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,n=[],s=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);s&&s.length>=2&&(e=Math.max(e,s.length),n.push(`${s.length} numbered items`));let o=t.match(/(?:^|\n)\s*[-*]\s+\S/g);o&&o.length>=3&&(e=Math.max(e,o.length),n.push(`${o.length} bullet points`));let r=t.split(/;\s*/).filter(u=>u.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),n.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),n.push(`${i.length} transition keywords`));let c=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=c,estimatedGoals:e,reason:n.length>0?n.join(", "):"single goal"}}function Cl(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let n=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(n)try{return JSON.parse(n[1].trim())}catch{}let s=e.search(/[[\{]/);if(s>=0){let o=e.slice(s);try{return JSON.parse(o)}catch{}}throw new Error(`Could not extract valid JSON from response:
|
|
670
|
+
${e.slice(0,200)}`)}async function Xh(t,e,n={}){let s=n.maxSubTasks||aa,r=[{role:"system",content:Kh.replace("{maxSubTasks}",String(s)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let h=Uh(e);h.provider&&(i.provider=h.provider),h.model&&(i.model=h.model)}let l=(await Fh(r,[],i)).content||"",u=Cl(l);if(!Array.isArray(u))throw new Error(`Decompose returned non-array: ${typeof u}`);let d=10,p=u.slice(0,s).map((h,y)=>({id:h.id||`t${y+1}`,task:String(h.task||""),scope:Array.isArray(h.scope)?h.scope:[],estimatedCalls:typeof h.estimatedCalls=="number"?Math.min(h.estimatedCalls,d):8,priority:typeof h.priority=="number"?h.priority:y+1})).filter(h=>h.task.length>0),g=p.reduce((h,y)=>h+y.estimatedCalls,0),m=aa*d;if(g>m){let{debugLog:h}=hi();h(`\x1B[33m \u26A0 Orchestrator: total estimated calls ${g} > ${m} \u2014 consider raising maxSubTasks\x1B[0m`)}return p}async function Vh(t,e,n){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let s=t.map((d,f)=>{let p=d.status==="done"?"SUCCESS":d.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${f+1} [${p}] ---
|
|
669
671
|
Task: ${d.task}
|
|
670
672
|
Result: ${d.result}
|
|
671
673
|
Tools: ${(d.toolsUsed||[]).join(", ")||"none"}`}).join(`
|
|
672
674
|
|
|
673
|
-
`),r=[{role:"system",content:
|
|
675
|
+
`),r=[{role:"system",content:Yh.replace("{prompt}",e).replace("{results}",s)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let d=Uh(n);d.provider&&(i.provider=d.provider),d.model&&(i.model=d.model)}let l=(await Fh(r,[],i)).content||"",u=Cl(l);return{summary:String(u.summary||""),conflicts:Array.isArray(u.conflicts)?u.conflicts:[],commitMessage:String(u.commitMessage||""),filesChanged:Array.isArray(u.filesChanged)?u.filesChanged:[]}}async function bS(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Hh,s=e.workerModel||Wh,o=e.maxParallel||Bh,r=e.maxSubTasks||aa,i=e.onProgress||(()=>{}),c={input:0,output:0};console.log(`
|
|
674
676
|
${_e.bold}Orchestrator${_e.reset} ${_e.dim}model: ${n} | workers: ${s} | max parallel: ${o}${_e.reset}
|
|
675
|
-
`),i("decomposing"),console.log(`${_e.dim}Phase 1: Decomposing prompt into sub-tasks...${_e.reset}`);let l;try{l=await
|
|
676
|
-
`);let d=Date.now(),f=
|
|
677
|
+
`),i("decomposing"),console.log(`${_e.dim}Phase 1: Decomposing prompt into sub-tasks...${_e.reset}`);let l;try{l=await Xh(t,n,{maxSubTasks:r})}catch(X){return console.log(`${_e.red}Decompose failed: ${X.message}${_e.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${X.message}`,conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:c}}if(l.length===0)return console.log(`${_e.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${_e.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",resourcesChanged:[]},totalTokens:c};console.log(`${_e.green}Decomposed into ${l.length} sub-tasks:${_e.reset}`);for(let X of l){console.log(` ${_e.dim}${X.id}:${_e.reset} ${X.task}`);let V=X.scope.filter(Boolean);V.length>0&&console.log(` ${_e.dim}scope: ${V.join(", ")}${_e.reset}`)}console.log("");let u=new Map;for(let X=0;X<l.length;X++)for(let V of l[X].scope)V&&!u.has(V)&&u.set(V,X);i("executing"),console.log(`${_e.dim}Phase 2: Running ${l.length} sub-agents (max ${o} parallel)...${_e.reset}
|
|
678
|
+
`);let d=Date.now(),f=zh(o),p={findings:[],_lock:!1},g=l.map(X=>{let V=$S(X.task);return(V?qh(V.id):null)||s}),m=l.map((X,V)=>{let fe=`Agent ${V+1} [${g[V]}]: `,he=Math.max(20,60-fe.length),be=X.task.substring(0,he)+(X.task.length>he?"...":"");return fe+be}),h=new yS(m);h.start();let y=`
|
|
677
679
|
You are a focused coding agent executing ONE specific sub-task.
|
|
678
680
|
Your scope is limited to the files listed in your task definition.
|
|
679
681
|
|
|
@@ -694,40 +696,40 @@ RULES:
|
|
|
694
696
|
- If your task says "add X to README" \u2014 add it, don't check if it exists first.
|
|
695
697
|
- Max 10 tool calls. If you need more, you are doing too much \u2014 narrow your scope.
|
|
696
698
|
- When done: stop calling tools and write a one-line summary of what you changed.
|
|
697
|
-
`,
|
|
698
|
-
`),be=[...u.entries()].filter(([,
|
|
699
|
+
`,b=new Map;for(let X=0;X<l.length;X++){let V=l[X].priority||1;b.has(V)||b.set(V,[]),b.get(V).push({st:l[X],idx:X})}let S=[...b.keys()].sort((X,V)=>X-V),C=new Array(l.length);for(let X of S){let fe=b.get(X).map(async({st:he,idx:be})=>{let ye=await f();try{let Re=await k(he,be,{acquire:f,subTaskModels:g,labels:m,progress:h,sharedContext:p,_fileOwnership:u,workerModel:s,WORKER_SYSTEM_PROMPT:y});return C[be]=Re,Re}finally{ye()}});await Promise.all(fe)}async function k(X,V,fe){try{let he=p.findings.filter(T=>T.agentId!==X.id).map(T=>`Agent ${T.agentId} found: ${T.summary}`).join(`
|
|
700
|
+
`),be=[...u.entries()].filter(([,T])=>T===V).map(([T])=>T),ye=[...u.entries()].filter(([,T])=>T!==V).map(([T])=>T),Re=[he?`Prior agent findings:
|
|
699
701
|
${he}
|
|
700
|
-
`:"",X.scope.length>0?`Focus on files: ${X.scope.join(", ")}`:"",be.length>0?`You OWN these files (may read+write): ${be.join(", ")}`:"",ye.length>0?`READ ONLY (owned by other agents, do NOT write): ${ye.join(", ")}`:""].filter(Boolean),v=
|
|
701
|
-
`)),I++;let J=
|
|
702
|
-
`):void 0,max_iterations:Math.min(X.estimatedCalls||10,15),model:J,_skipLog:!0,_systemPrompt:y,_readOnlyFiles:ye},{onUpdate:ee=>{if(ee&&ee.type==="tool_call"&&process.stderr.isTTY){let Z=`Agent ${V+1} [${J}]`,ge=ee.tool||"...";h.labels[V]=`${Z}: ${ge}`}}})},1,2e3),N=typeof M.result=="string"?M.result.slice(0,200):String(M.result||"").slice(0,200);return p.findings.push({agentId:X.id,summary:N,files:Array.isArray(X.scope)?X.scope:[]}),h.labels[V]=m[V],h.update(V,M.status==="failed"?"error":"done"),c.input+=M.tokensUsed?.input||0,c.output+=M.tokensUsed?.output||0,M.tokensUsed?._estimated&&(c._estimated=!0),{...M,_scope:X.scope,_idx:V}}catch(he){return h.labels[V]=m[V],h.update(V,"error"),{task:X.task,status:"failed",result:`Error: ${he.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let
|
|
702
|
+
`:"",X.scope.length>0?`Focus on files: ${X.scope.join(", ")}`:"",be.length>0?`You OWN these files (may read+write): ${be.join(", ")}`:"",ye.length>0?`READ ONLY (owned by other agents, do NOT write): ${ye.join(", ")}`:""].filter(Boolean),v=Jh(X.task),j=g[V],A=process.env.NEX_FALLBACK_MODEL||qh("agentic")||s,I=0,M=await Gh(async()=>{let T=I>0;T&&(h.update(V,"retry"),process.stderr.write(` ${_e.dim}[Agent ${V+1}] retrying after error...${_e.reset}
|
|
703
|
+
`)),I++;let J=T&&j!==A?A:j;return hS({task:X.task,type:v,context:Re.length>0?Re.join(`
|
|
704
|
+
`):void 0,max_iterations:Math.min(X.estimatedCalls||10,15),model:J,_skipLog:!0,_systemPrompt:y,_readOnlyFiles:ye},{onUpdate:ee=>{if(ee&&ee.type==="tool_call"&&process.stderr.isTTY){let Z=`Agent ${V+1} [${J}]`,ge=ee.tool||"...";h.labels[V]=`${Z}: ${ge}`}}})},1,2e3),N=typeof M.result=="string"?M.result.slice(0,200):String(M.result||"").slice(0,200);return p.findings.push({agentId:X.id,summary:N,files:Array.isArray(X.scope)?X.scope:[]}),h.labels[V]=m[V],h.update(V,M.status==="failed"?"error":"done"),c.input+=M.tokensUsed?.input||0,c.output+=M.tokensUsed?.output||0,M.tokensUsed?._estimated&&(c._estimated=!0),{...M,_scope:X.scope,_idx:V}}catch(he){return h.labels[V]=m[V],h.update(V,"error"),{task:X.task,status:"failed",result:`Error: ${he.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}}let x;try{x=C}finally{h.stop({silent:!0}),gS()}console.log("");let E=Math.round((Date.now()-d)/1e3),B=E>=60?`${Math.floor(E/60)}m ${E%60}s`:`${E}s`;for(let X=0;X<x.length;X++){let V=x[X],he=V.status==="done"||V.status==="truncated"&&V.result&&!V.result.startsWith("Error")?`${_e.green}\u2713${_e.reset}`:`${_e.red}\u2717${_e.reset}`,be=V._scope&&V._scope.length>0?V._scope.map(v=>v.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],ye=be.length>0?be.join(", "):V.task.substring(0,35)+(V.task.length>35?"...":""),Re=X===x.length-1;console.log(` ${he} Agent ${X+1} ${_e.dim}${ye}${_e.reset}${Re?` ${_e.dim}${B}${_e.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${_e.dim}Phase 3: Synthesizing results...${_e.reset}`);let q;try{q=await Vh(x,t,n)}catch(X){console.log(`${_e.yellow}Synthesize failed: ${X.message} \u2014 using raw results.${_e.reset}`),q={summary:x.map(V=>V.result).join(`
|
|
703
705
|
`),conflicts:[],commitMessage:"",resourcesChanged:[]}}let re=p.findings.flatMap(X=>X.files),ie=new Map;for(let X of re)ie.set(X,(ie.get(X)||0)+1);let Q=[...ie.values()].some(X=>X>1),O=p.findings.length>1&&Q?` ${_e.dim}(agents shared context)${_e.reset}`:"";if(console.log(`
|
|
704
|
-
${_e.bold}Summary:${_e.reset} ${q.summary}${O}`),q.conflicts.length>0){console.log(`${_e.yellow}Conflicts:${_e.reset}`);for(let X of q.conflicts)console.log(` - ${X}`)}q.commitMessage&&console.log(`${_e.dim}Suggested commit: ${q.commitMessage}${_e.reset}`);let
|
|
705
|
-
`),{results:
|
|
706
|
-
`)}var
|
|
706
|
+
${_e.bold}Summary:${_e.reset} ${q.summary}${O}`),q.conflicts.length>0){console.log(`${_e.yellow}Conflicts:${_e.reset}`);for(let X of q.conflicts)console.log(` - ${X}`)}q.commitMessage&&console.log(`${_e.dim}Suggested commit: ${q.commitMessage}${_e.reset}`);let Te=c.input===0&&c.output===0?"n/a (provider does not report token counts)":c._estimated?`~${c.input} input / ~${c.output} output (est.)`:`${c.input} input + ${c.output} output`;return console.log(`${_e.dim}Tokens: ${Te}${_e.reset}
|
|
707
|
+
`),{results:x,synthesis:q,totalTokens:c}}var _S=/\b(research|analyze|investigate|check|verify|review|audit|read|find|search|discover|look|examine|inspect|scan|list)\b/i,xS=/\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 Jh(t){if(!t)return"implement";let e=_S.test(t);return xS.test(t)?"implement":e?"explore":"implement"}Zh.exports={runOrchestrated:bS,decompose:Xh,synthesize:Vh,detectComplexPrompt:wS,extractJSON:Cl,createSemaphore:zh,DECOMPOSE_PROMPT:Kh,SYNTHESIZE_PROMPT:Yh,DEFAULT_ORCHESTRATOR_MODEL:Hh,DEFAULT_WORKER_MODEL:Wh,DEFAULT_MAX_PARALLEL:Bh,DEFAULT_MAX_SUBTASKS:aa,withRetry:Gh,_classifyWorkerType:Jh}});var Ee=oe((JR,wg)=>{var{C:$,Spinner:wo,TaskProgress:vS,formatToolCall:SS,formatToolSummary:Bl,formatSectionHeader:ca,formatMilestone:kS,setActiveTaskProgress:YR,getThinkingVerb:Al,setActiveModelForSpinner:ES}=Ke(),{debugLog:K,warnLog:GR}=hi(),{MilestoneTracker:TS}=uf(),{callStream:Qh}=Be(),{parseToolArgs:RS}=eo(),{executeTool:CS}=en(),{gatherProjectContext:AS}=Qi(),{fitToContext:OS,forceCompress:bn,getUsage:an,estimateTokens:NS,buildProgressSnapshot:MS}=Lt(),{autoSave:PS,flushAutoSave:LS}=on(),{scoreMessages:IS,formatScore:jS,appendScoreHistory:DS}=ta(),{detectCategory:qS,getModelForPhase:Wl,getPhaseBudget:Ts,isPhaseRoutingEnabled:FS}=Kn();function tt(t){PS(t),LS()}function US(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 Ol(t){try{if(!t.some(s=>s.role!=="assistant"?!1:!!(Array.isArray(s.content)&&s.content.some(o=>o&&o.type==="tool_use")||Array.isArray(s.tool_calls)&&s.tool_calls.length>0)))return;let n=IS(t);if(!n)return;console.log(jS(n,$));try{let{_getSessionsDir:s}=on(),o=require("fs"),r=require("path").join(s(),"_autosave.json");if(o.existsSync(r)){let i=JSON.parse(o.readFileSync(r,"utf-8"));i.score=n.score,i.scoreGrade=n.grade,i.scoreIssues=n.issues,o.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:s}=eo(),o=Hs();DS(n.score,{version:o.version,model:s?s():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:BS}=tn(),{getDeploymentContextBlock:WS,probeUrlServer:HS}=pl(),{getFewShotForInput:KS}=ph(),{checkPermission:YS,setPermission:GS,savePermissions:zS}=hr(),{confirm:dg,setAllowAlwaysHandler:XS,getAutoConfirm:VS}=$t(),{isPlanMode:Er,getPlanModePrompt:JS,PLAN_MODE_ALLOWED_TOOLS:fg,setPlanContent:ZS,extractStepsFromText:QS,createPlan:ek,getActivePlan:zR,startExecution:XR,advancePlanStep:tk,getPlanStepInfo:nk}=rn(),{StreamRenderer:sk}=Ph(),{runHooks:eg}=Rl(),{routeMCPCall:ok,getMCPToolDefinitions:rk}=xi(),{getSkillInstructions:ik,getSkillToolDefinitions:ak,routeSkillCall:ck,matchSkillTriggers:lk}=Cn(),{trackUsage:tg,estimateTokens:ng}=Qs();function sg(t){return!t||typeof t!="string"?0:typeof ng=="function"?ng(t):Math.ceil(t.length/4)}var{validateToolArgs:uk}=Oc(),{filterToolsForModel:og,getModelTier:dk,PROVIDER_DEFAULT_TIER:VR}=Wo(),{getConfiguredProviders:fk,getActiveProviderName:bo,getActiveModelId:un,setActiveModel:rg,MODEL_EQUIVALENTS:_a}=Be(),{getModelProfile:pk,getModelBriefing:mk}=Ii(),tu=require("fs"),nu=require("path"),hk=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function gk(t){let e=kS(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
|
|
708
|
+
`)}var ig=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function $k(t){let e=[],n;for(ig.lastIndex=0;(n=ig.exec(t))!==null;){let s=n[1].trim(),o=s.startsWith("~")?s.replace("~",process.env.HOME||""):nu.resolve(s);tu.existsSync(o)&&e.push({raw:s,abs:o})}return e}function yk(t){let e=tu.readFileSync(t),n=nu.extname(t).toLowerCase().replace(".",""),s=n==="jpg"||n==="jpeg"?"image/jpeg":n==="png"?"image/png":n==="gif"?"image/gif":n==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:s}}function pg(t){let e=$k(t);if(e.length===0)return t;let n=[{type:"text",text:t}];for(let s of e)try{let{data:o,media_type:r}=yk(s.abs);n.push({type:"image",media_type:r,data:o})}catch{}return n.length>1?n:t}var wk=[/\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 mg(t){return typeof t!="string"||!t?!1:wk.some(e=>e.test(t))}function bk(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let n=t.split(/(?<=\. )/).filter(l=>l.trim().length>0);if(n.length<6)return{text:t,truncated:!1,repeatCount:0};let s=new Map;for(let l=0;l<=n.length-3;l++){let u=n.slice(l,l+3).join("").trim();u.length>30&&s.set(u,(s.get(u)||0)+1)}let o=0,r="";for(let[l,u]of s)u>o&&(o=u,r=l);if(o<3)return{text:t,truncated:!1,repeatCount:o};let i=`
|
|
707
709
|
|
|
708
|
-
[SYSTEM: Output repetition detected \u2014 response truncated (${o}\xD7 repeated paragraph)]`,c;if(t.length>8e3)c=t.slice(0,3e3)+i;else{let l=0,u=-1,d=0;for(;l<2;){let f=t.indexOf(r,d);if(f===-1)break;l++,u=f+r.length,d=f+1}c=u>0?t.slice(0,u)+i:t.slice(0,3e3)+i}return{text:c,truncated:!0,repeatCount:o}}function
|
|
710
|
+
[SYSTEM: Output repetition detected \u2014 response truncated (${o}\xD7 repeated paragraph)]`,c;if(t.length>8e3)c=t.slice(0,3e3)+i;else{let l=0,u=-1,d=0;for(;l<2;){let f=t.indexOf(r,d);if(f===-1)break;l++,u=f+r.length,d=f+1}c=u>0?t.slice(0,u)+i:t.slice(0,3e3)+i}return{text:c,truncated:!0,repeatCount:o}}function Hl(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let n=t.split(`
|
|
709
711
|
`),s=new Map;for(let f of n){let p=f.trim();p.length>=20&&s.set(p,(s.get(p)||0)+1)}let o=0,r="";for(let[f,p]of s)p>o&&(o=p,r=f);if(o<=e)return{text:t,truncated:!1,repeatCount:o};let i=`
|
|
710
712
|
|
|
711
|
-
\u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,c=0,l=-1,u=0;for(;c<e;){let f=t.indexOf(r,u);if(f===-1)break;c++,l=f+r.length,u=f+1}return{text:l>0?t.slice(0,l)+i:t.slice(0,2e3)+i,truncated:!0,repeatCount:o}}var
|
|
713
|
+
\u26A0 [Response truncated: repeated paragraph detected (${o}\xD7)]`,c=0,l=-1,u=0;for(;c<e;){let f=t.indexOf(r,u);if(f===-1)break;c++,l=f+r.length,u=f+1}return{text:l>0?t.slice(0,l)+i:t.slice(0,2e3)+i,truncated:!0,repeatCount:o}}var Nl=null,Ml=null,Pl=null;function yt(){if(Nl===null){let{TOOL_DEFINITIONS:t}=en();Nl=t}return Ml===null&&(Ml=ak()),Pl===null&&(Pl=rk()),[...Nl,...Ml,...Pl]}var Kl=50;function _k(t){Number.isFinite(t)&&t>0&&(Kl=t)}var da=()=>null;function xk(t){da=t}var br=null,Yl=null,_o=null,fa=new Map,vk=1e4,Sk=6e3,kk=/\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 Ek(t){return!t||typeof t!="string"?t:t.replace(kk,(e,n)=>`${n}=***REDACTED***`)}var Tk=7e3,Rk=4e3;function Ck(t,e=null){let n=Ek(t),s=NS(n),o=e==="read_file"?Tk:vk,r=e==="read_file"?Rk:Sk;if(s>o)try{let{compressToolResult:i}=Lt();return i(n,r)}catch{return n}return n}function hg(t){try{let{getActiveModel:e}=Be(),n=e(),s=n?`${n.provider}:${n.id}`:"default";if(fa.has(s))return fa.get(s);let o=og(t);return fa.set(s,o),o}catch{return og(t)}}function Ak(){fa.clear()}var _r={hash:null,ts:0},Ok=3e4;async function gg(){if(_r.hash&&Date.now()-_r.ts<Ok)return _r.hash;try{let t=require("fs").promises,e=require("path"),n=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],o=(await Promise.allSettled(n.map(i=>t.stat(i).then(c=>`${i}:${c.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=tn(),c=i();c&&o.push(`memory:${c}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(tu.existsSync(i)){let c=await t.stat(i);o.push(`brain:${c.mtimeMs}`)}}catch{}let r=o.join("|");return _r={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function Gl(){br=null,Yl=null,_r={hash:null,ts:0},_o=null}var Nk=new Set(["spawn_agents"]),Ll=5,Il=3,la=2,ag=6e4,jl=12e4,Mk=process.env.NEX_STALE_AUTO_SWITCH!=="0";function Pk(t){try{let e=require("fs"),n=require("path"),s=n.join(process.cwd(),".nex","plans");e.existsSync(s)||e.mkdirSync(s,{recursive:!0});let o=n.join(s,"current-plan.md");e.writeFileSync(o,t,"utf-8")}catch{}}XS(t=>{GS(t,"allow"),zS(),console.log(`${$.green} \u2713 ${t}: always allow${$.reset}`)});async function Lk(t){let e=t.function.name,n=RS(t.function.arguments),s=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!n){let d=yt().find(p=>p.function.name===e),f=d?JSON.stringify(d.function.parameters,null,2):"unknown";return K(`${$.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${$.reset}`),{callId:s,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
712
714
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
713
715
|
|
|
714
716
|
Expected JSON schema for "${e}":
|
|
715
717
|
${f}
|
|
716
718
|
|
|
717
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:s}}}let o=
|
|
718
|
-
`)[0]}${$.reset}`);let u=(
|
|
719
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:s}}}let o=uk(e,n);if(!o.valid){K(`${$.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
720
|
+
`)[0]}${$.reset}`);let u=(lg.get(e)||0)+1;lg.set(e,u);let d=u>=2?`${o.error}
|
|
719
721
|
|
|
720
|
-
[SYSTEM: This is argument error #${u} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:o.error;return{callId:s,fnName:e,args:n,canExecute:!1,errorResult:{role:"tool",content:d,tool_call_id:s}}}let r=o.corrected||n;if(o.corrected){let u=Object.keys(n),d=Object.keys(o.corrected),f=u.filter(p=>!d.includes(p));f.length&&console.log(`${$.dim} \u2713 ${e}: corrected args (${f.join(", ")})${$.reset}`)}if(
|
|
722
|
+
[SYSTEM: This is argument error #${u} for "${e}". Study the "Expected parameters" schema above and correct your call \u2014 do not repeat the same mistake.]`:o.error;return{callId:s,fnName:e,args:n,canExecute:!1,errorResult:{role:"tool",content:d,tool_call_id:s}}}let r=o.corrected||n;if(o.corrected){let u=Object.keys(n),d=Object.keys(o.corrected),f=u.filter(p=>!d.includes(p));f.length&&console.log(`${$.dim} \u2713 ${e}: corrected args (${f.join(", ")})${$.reset}`)}if(Er()&&!fg.has(e))return console.log(`${$.yellow} \u2717 ${e}: blocked in plan mode${$.reset}`),{callId:s,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:s}};let i=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),c=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]);if(Oe&&Je==="plan"&&!i.has(e)&&!e.startsWith("skill_"))return zn++,K(`${$.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${zn})${$.reset}`),{callId:s,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${e}' is blocked. Analyze the codebase using read-only tools, then present your findings as text. Edits happen in the next phase.`,tool_call_id:s}};if(Oe&&Je==="verify"&&!c.has(e)&&!e.startsWith("skill_"))return K(`${$.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${$.reset}`),{callId:s,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${e}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:s}};let l=YS(e);if(l==="deny")return console.log(`${$.red} \u2717 ${e}: denied by permissions${$.reset}`),{callId:s,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:s}};if(l==="ask"){let u=` Allow ${e}?`;return e==="bash"&&r.command&&(u=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await dg(u,{toolName:e})?{callId:s,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:s,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:s}}}return{callId:s,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function Ik(t,e,n={}){let s=await ck(t,e);if(s!==null)return s;let o=await ok(t,e);return o!==null?o:CS(t,e,n)}function jk(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 Dl(t,e=!1){e||console.log(SS(t.fnName,t.args));let n=eg("pre-tool",{tool_name:t.fnName}),s=n.results;if(n.blocked){let h=`BLOCKED: pre-tool hook rejected ${t.fnName}: ${n.blockReason}`;e||console.log(`${$.yellow} [hook pre-tool] BLOCKED: ${n.blockReason}${$.reset}`);let y=Bl(t.fnName,t.args,h,!0);return e||console.log(y),{msg:{role:"tool",content:h,tool_call_id:t.callId},summary:y}}if(!e&&s.length>0)for(let h of s)h.success?console.log(`${$.dim} [hook pre-tool] ${h.command} \u2192 ${h.output||"ok"}${$.reset}`):console.log(`${$.yellow} [hook pre-tool] ${h.command} \u2192 ERROR: ${h.error}${$.reset}`);vn?.onToolStart&&vn.onToolStart(t.fnName,t.args);let o=await Ik(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),r=String(o??""),i=r.length>5e4?r.substring(0,5e4)+`
|
|
721
723
|
...(truncated ${r.length-5e4} chars)`:r,c=i.split(`
|
|
722
|
-
`)[0],l=c.startsWith("ERROR")||c.includes("CANCELLED")||c.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(i)&&/✗ Agent/.test(i),u=
|
|
724
|
+
`)[0],l=c.startsWith("ERROR")||c.includes("CANCELLED")||c.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(i)&&/✗ Agent/.test(i),u=Bl(t.fnName,t.args,i,l);e||console.log(u),vn?.onToolEnd&&vn.onToolEnd(t.fnName,u,!l);let f=eg("post-tool",{tool_name:t.fnName}).results;if(!e&&f.length>0)for(let h of f)h.success?console.log(`${$.dim} [hook post-tool] ${h.command} \u2192 ${h.output||"ok"}${$.reset}`):console.log(`${$.yellow} [hook post-tool] ${h.command} \u2192 ERROR: ${h.error}${$.reset}`);let g=Ck(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)?g+=`
|
|
723
725
|
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)?g+=`
|
|
724
726
|
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)&&(g+=`
|
|
725
|
-
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:g,tool_call_id:t.callId},summary:u}}var
|
|
726
|
-
`)):(
|
|
727
|
-
`)}function
|
|
728
|
-
${
|
|
727
|
+
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:g,tool_call_id:t.callId},summary:u}}var Dk=[{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 ql(t){for(let{re:e,label:n}of Dk){let s=t.match(e);if(s){let o=(s[1]||"").trim();return o?`${n}: ${o}`:n}}return null}async function qk(t,e=!1,n={}){let s=new Array(t.length),o=[],r=[],i=null;if(e&&!n.skipSpinner){let l=t.filter(u=>u.canExecute);if(l.length>0){let u;if(l.length===1){let d=l[0],f=jk(d.fnName,d.args);u=`\u23FA ${d.fnName}${f?`(${f})`:""}`}else{let d=l.map(f=>f.fnName).join(", ");u=`\u23FA ${l.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}i=new wo(u),i.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await Dl(t[l],e);s[l]=u,o.push(d)}else{let l=r.map(d=>Dl(t[d],e)),u=await Promise.all(l);for(let d=0;d<r.length;d++)s[r[d]]=u[d].msg,o.push(u[d].summary)}r=[]}}for(let l=0;l<t.length;l++){let u=t[l];if(!u.canExecute){await c(),s[l]=u.errorResult,o.push(Bl(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(Nk.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await Dl(u,e);s[l]=d,o.push(f)}else r.push(l)}if(await c(),i&&i.stop(),e&&o.length>0&&!n.skipSummaries)for(let l of o)console.log(l);return{results:s,summaries:o}}var H=[],cg=300,$g=900*1e3;function _n(t,e){let n=t.get(e);return n?Date.now()-n.ts>$g?(t.delete(e),0):n.count:0}function Rs(t,e){let n=t.get(e),s=n&&Date.now()-n.ts<=$g?n.count+1:1;return t.set(e,{count:s,ts:Date.now()}),s}function Fl(t,e,n){t.set(e,{count:n,ts:Date.now()})}var su=new Map,ou=new Map,Tr=new Map,ru=new Map,Rr=new Map,Gn=new Map,Pn=new Map,Cr=new Map,Xt=new Map,Ns=new Map,lg=new Map,xa=new Map,va=new Map,Vt=0,xr=0,pa=0,zl="",ma=0,qt=!1,ua=0,ha=0,Cs=-1,Xl=!1,ga=0,$a=!1,xn=0,cn=!1,Ln=0,ln=0,ut=!1,At="",vr=0,Yn=0,ya="",As=0,Os=0,wa="",Jt=!1,Vl=!1,Ar=new Map,Or=new Set,Sr=null,Ul=!1,yr=0,ug=!1,Je="plan",Sa=0,Oe=!1,zn=0,In=null,Jl=null,Zl=null,kr=0,xo=null;function yo(t,e){t===zl?(ma++,hi().DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${ma})${$.reset}
|
|
728
|
+
`)):(zl=t,ma=1,K(`${e} \u26A0 ${t}${$.reset}`))}var ba=[];function Fk(t){ba.push(t.trim())}function Uk(){return ba.length===0?null:ba.splice(0,ba.length).join(`
|
|
729
|
+
`)}function wr(t,e,n,s){if(!Oe)return null;let o=Je;Je=t,Sa=0,In=Wl(t,xo),xn=0,cn=!1,Ln=0,ln=0,Gn.clear(),Pn.clear(),Ns.clear(),xa.clear(),va.clear(),ou.clear(),Tr.clear(),ru.clear(),Rr.clear(),su.clear(),Cr.clear();let r;if(t==="implement")Jl=e?.slice(0,800)||"",r=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
|
|
730
|
+
${Jl}
|
|
729
731
|
|
|
730
|
-
Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`;else if(t==="verify"){
|
|
732
|
+
Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`;else if(t==="verify"){Zl=e?.slice(0,500)||"";let i=n?[...n].join(", "):"none";r=`[PHASE: VERIFICATION] Implementation complete. Verify the changes:
|
|
731
733
|
1. Read each modified file and confirm changes are correct
|
|
732
734
|
2. If test command exists (npm test / pytest): run it
|
|
733
735
|
3. If linter exists: run it
|
|
@@ -735,18 +737,18 @@ Now implement the fix/changes. Do not investigate further \u2014 edit files dire
|
|
|
735
737
|
Report PASS (all good) or FAIL (list specific issues).
|
|
736
738
|
|
|
737
739
|
Files modified: ${i}
|
|
738
|
-
Summary: ${
|
|
740
|
+
Summary: ${Zl}`}return K(`${$.cyan} \u21B3 Phase transition: ${o} \u2192 ${t} (model: ${In||"default"})${$.reset}`),r?{role:"user",content:r}:null}function Bk(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,n=process.env.NEX_COMMIT_LANGUAGE,s=!t||t==="auto"?null:t,o=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
739
741
|
`];s?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${s}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${s} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),o.push(" \u2022 FILE CREATION TASKS (Makefile, Dockerfile, config files): paste the COMPLETE file content in a fenced code block in your TEXT RESPONSE \u2014 writing a file with a tool does NOT make it visible. The fenced code block MUST appear in your response, not just via write_file."),o.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),o.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),o.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),o.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),o.push(' \u2022 For Makefiles, paste the COMPLETE Makefile code DIRECTLY in your text response \u2014 every target, recipe, dependency, and .PHONY line. Writing the Makefile with a tool does NOT count as showing it. The Makefile MUST appear verbatim in your chat text as a code block, even if you also wrote it to a file. Never describe structure without showing the actual code. CRITICAL: use EXACTLY the command specified \u2014 if the task says "runs jest", write "jest" in the recipe, NEVER "npm test". npm test is NOT jest. Recipes need real TAB indentation. ONE .PHONY line listing ALL phony targets.'),o.push(" \u2022 For dataclasses, paste the COMPLETE dataclass code DIRECTLY in your text response \u2014 @dataclass decorator, all fields with types and defaults, full __post_init__ validation. Writing the file with a tool does NOT count as showing the code. The code MUST appear verbatim in your chat text, even if you also wrote it to a file."),o.push(" \u2022 For cron expressions, re-read the exact time boundaries in the task before writing. If asked for 8-18h, the range is 8,9,...,18 \u2014 write exactly what was asked, not an approximation."),o.push(' \u2022 When a task explicitly specifies a tool (e.g., "use tsc"), NEVER mention alternatives (e.g., "swc build") \u2014 use exactly what was requested.'),o.push(' \u2022 In Makefile prerequisites, NEVER use shell glob patterns like src/**/*.ts \u2014 make does not expand these natively. Keep prerequisite lists explicit or omit them. When a Makefile target says "runs jest", call jest directly in the recipe (not npm test).'),o.push(" \u2022 For bash in-place text replacements with backups: use ONLY ONE backup method \u2014 either sed -i.bak (let sed create the backup) OR cp file file.bak followed by sed -i (no extension). Never use both cp and sed -i.bak together \u2014 that produces redundant double backups (file.bak and file.bak.bak)."),o.push(" \u2022 For iterative array-flattening (flattenDeep): use push() and reverse() at the end \u2014 NEVER unshift(). unshift is O(n) per call making the whole function O(n^2). The iterative version MUST use a loop (while/for) and an explicit stack array \u2014 zero recursive calls. If a function calls itself, it is recursive regardless of its name. Never label a recursive function as iterative."),o.push(" \u2022 FORBIDDEN: when refactoring callbacks to async/await, NEVER write try { ... } catch(e) { throw e } \u2014 this is an explicit anti-pattern. WRONG: async function f() { try { const d = await readFile(..); await writeFile(.., d); } catch(e) { throw e; } } \u2014 RIGHT: async function f() { const d = await readFile(..); await writeFile(.., d); } \u2014 omit the try-catch entirely, let rejections propagate."),o.push(' \u2022 Docker HEALTHCHECK: always include --start-period=30s (or appropriate startup time) so the container has time to initialise before failures are counted. Also note that curl may not be available in minimal Node.js images \u2014 offer wget or "node -e" as alternatives.'),o.push(' \u2022 When fixing a bash word-splitting bug like "for f in $(ls *.txt)": replace the entire $(ls *.txt) with a bare glob directly \u2014 "for f in *.txt". The fix is eliminating the ls command and $() subshell entirely. Emphasise this in the explanation: the glob in the for loop prevents word splitting because the shell expands the glob into separate words before the loop \u2014 there is no subshell output to split. CRITICAL: NEVER suggest "ls -N" or any ls variant as a fix \u2014 ls -N outputs filenames one per line, but word splitting still occurs on each line when used in a subshell expansion. The only correct fix is the bare glob pattern.');let r=e||"English";o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let i=n||"English";return o.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),s&&o.push(`
|
|
740
742
|
This is a hard requirement. Always respond in ${s}. Do NOT switch to any other language \u2014 even if the user writes to you in German, French, or any other language, your reply MUST be in ${s}.`),o.join(`
|
|
741
743
|
`)+`
|
|
742
744
|
|
|
743
|
-
`}function
|
|
745
|
+
`}function Wk(){if(_o!==null)return _o;try{let e=fk().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:dk(r.id,o.name),name:r.name})));if(e.length<2)return _o="","";let n={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},s=`
|
|
744
746
|
# Sub-Agent Model Routing
|
|
745
747
|
|
|
746
748
|
`;s+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',s+=`| Model | Tier | Auto-assigned for |
|
|
747
749
|
|---|---|---|
|
|
748
750
|
`;for(let o of e)s+=`| ${o.spec} | ${o.tier} | ${n[o.tier]||o.tier} |
|
|
749
|
-
`;return
|
|
751
|
+
`;return _o=s,s}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),_o="",""}}var Ql="<!-- SYSTEM_PROMPT_DYNAMIC_BOUNDARY -->";function Hk(t){let e=t.indexOf(Ql);return e===-1?{dynamic:t,static:""}:{dynamic:t.slice(0,e).trimEnd(),static:t.slice(e+Ql.length).trimStart()}}async function eu(){let t=await gg()+":"+un();if(br!==null&&t===Yl)return br;let e=await AS(process.cwd()),n=BS(),s=ik(),o=Er()?JS():"",r=Bk(),i=WS(),c=mk(un());return br=`${c?`## Model Briefing
|
|
750
752
|
${c}
|
|
751
753
|
|
|
752
754
|
---
|
|
@@ -767,7 +769,7 @@ ${o}
|
|
|
767
769
|
${r?`${r}
|
|
768
770
|
`:""}${i?`${i}
|
|
769
771
|
|
|
770
|
-
`:""}${
|
|
772
|
+
`:""}${VS()?`# YOLO Mode \u2014 Auto-Execute
|
|
771
773
|
|
|
772
774
|
You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
|
|
773
775
|
- NEVER ask for confirmation \u2014 just execute tasks directly
|
|
@@ -993,7 +995,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
|
|
|
993
995
|
- Instead: use bash with inline node -e '...' for quick one-off checks.
|
|
994
996
|
- If the test is worth keeping, write it to tests/ with a proper name.
|
|
995
997
|
- Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
|
|
996
|
-
${
|
|
998
|
+
${Wk()}
|
|
997
999
|
|
|
998
1000
|
# Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
|
|
999
1001
|
|
|
@@ -1184,104 +1186,106 @@ class ErrorBoundary extends React.Component {
|
|
|
1184
1186
|
- Use migrations for schema changes, never manual ALTER TABLE
|
|
1185
1187
|
- Add database-level constraints (unique, foreign key, check) not just app-level
|
|
1186
1188
|
|
|
1187
|
-
`,
|
|
1188
|
-
`):[]).filter(f=>{let p=f.split(".").pop();return r.has(p)});if(i.length<3)return null;let c={};for(let f of i){let p=f.split(".").pop();c[p]=(c[p]||0)+1}let u=` \u{1F4C1} ${Object.entries(c).sort((f,p)=>p[1]-f[1]).slice(0,4).map(([f,p])=>`${p} .${f}`).join(" \xB7 ")}`,d=
|
|
1189
|
-
\u{1F4E6} ${g}${m}`}}catch{}return u}function
|
|
1190
|
-
${$.dim} ${c}${$.reset}`),l>=30&&process.stdout.isTTY){let u=n.size>0?`Done \u2014 ${n.size} ${n.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;
|
|
1191
|
-
`),p==="")return c({action:"quit"});let m=i.find(h=>h.key===g);!m||m.key==="q"||!m.model&&m.key!=="r"?c({action:"quit"}):m.key==="r"?c({action:"retry"}):c({action:"switch",model:m.model,provider:t})};l.on("data",f)})}var
|
|
1189
|
+
`,Yl=t,br}function yg(){su.clear(),ou.clear(),Tr.clear(),ru.clear(),Rr.clear(),Gn.clear(),Pn.clear(),Cr.clear(),Xt.clear(),Ns.clear(),xa.clear(),va.clear(),Vt=0,xr=0,pa=0,qt=!1,ha=0,Cs=-1,Xl=!1,ga=0,$a=!1,xn=0,cn=!1,Ln=0,ln=0,ut=!1,At="",vr=0,ya="",As=0,wa="",Os=0,Jt=!1,Vl=!1,Je="plan",Sa=0,Oe=!1,In=null,Jl=null,Zl=null,kr=0,zn=0,xo=null,Ar.clear(),Or.clear(),zl="",ma=0}function Kk(){H=[],Sr=null,yg();try{let{resetCompactionFailures:t}=Kc();t()}catch{}}function Yk(){H.length>cg&&H.splice(0,H.length-cg)}function Gk(){return H.length}function zk(){return H}function Xk(t){H=t}async function Vk(){let{execFile:t}=require("child_process"),e=require("fs"),n=process.cwd(),s=(f,p)=>new Promise(g=>{t(f,p,{cwd:n,timeout:3e3},(m,h)=>{g(m?"":(h||"").trim())})}),[o]=await Promise.all([s("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(o?o.split(`
|
|
1190
|
+
`):[]).filter(f=>{let p=f.split(".").pop();return r.has(p)});if(i.length<3)return null;let c={};for(let f of i){let p=f.split(".").pop();c[p]=(c[p]||0)+1}let u=` \u{1F4C1} ${Object.entries(c).sort((f,p)=>p[1]-f[1]).slice(0,4).map(([f,p])=>`${p} .${f}`).join(" \xB7 ")}`,d=nu.join(n,"package.json");if(e.existsSync(d))try{let f=JSON.parse(e.readFileSync(d,"utf-8")),p=Object.keys({...f.dependencies||{},...f.devDependencies||{}});if(p.length>0){let g=p.slice(0,5).join(" \xB7 "),m=p.length>5?` +${p.length-5}`:"";u+=`
|
|
1191
|
+
\u{1F4E6} ${g}${m}`}}catch{}return u}function Jk(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 nt(t,e,n,s,o,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((u,d)=>u+d,0),c=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`,l=0;if(o){let u=Date.now()-o;l=Math.round(u/1e3),c+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}if(n.size>0&&(c+=` \xB7 ${n.size} ${n.size===1?"file":"files"} modified`),c+=" \u2500\u2500",console.log(`
|
|
1192
|
+
${$.dim} ${c}${$.reset}`),l>=30&&process.stdout.isTTY){let u=n.size>0?`Done \u2014 ${n.size} ${n.size===1?"file":"files"} modified in ${l}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${l}s`;Jk(u)}if(Or.size>0&&Ar.size>0)for(let u of Or){let d=Ar.get(u);d&&console.log(`${$.dim} \u2714 task #${u} auto-matched: ${d.slice(0,60)}${$.reset}`)}n.size>0?console.log(`${$.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${$.reset}`):!r&&s.size>=5&&n.size===0&&t>=3?console.log(`${$.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${$.reset}`):s.size>0&&t>=2&&console.log(`${$.dim} \u{1F4A1} /save \xB7 /clear${$.reset}`)}async function Zk(){if(!process.stdout.isTTY)return{action:"quit"};let t=bo(),e=un(),n=_a.fast?.[t],s=_a.strong?.[t],o=n&&n!==e,r=s&&s!==e&&s!==n,i=[];i.push({key:"r",label:`Retry with current model ${$.dim}(${e})${$.reset}`}),o&&i.push({key:"f",label:`Switch to ${$.bold}${n}${$.reset} ${$.dim}\u2014 fast, low latency${$.reset}`,model:n}),r&&i.push({key:"s",label:`Switch to ${$.bold}${s}${$.reset} ${$.dim}\u2014 reliable tool-calling, medium speed${$.reset}`,model:s}),i.push({key:"q",label:`${$.dim}Quit${$.reset}`}),console.log(),console.log(`${$.yellow} Stream stale \u2014 all retries exhausted.${$.reset} What would you like to do?`);for(let c of i)console.log(` ${$.cyan}[${c.key}]${$.reset} ${c.label}`);return process.stdout.write(` ${$.yellow}> ${$.reset}`),new Promise(c=>{let l=process.stdin,u=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let d=!1,f=p=>{if(d)return;d=!0,l.removeListener("data",f),l.setRawMode(u||!1),l.pause();let g=p.toLowerCase().trim();if(process.stdout.write(`${g}
|
|
1193
|
+
`),p==="")return c({action:"quit"});let m=i.find(h=>h.key===g);!m||m.key==="q"||!m.model&&m.key!=="r"?c({action:"quit"}):m.key==="r"?c({action:"retry"}):c({action:"switch",model:m.model,provider:t})};l.on("data",f)})}var vn=null;async function Qk(t,e=null,n={}){let s=pk(un());ag=s.staleWarn,jl=s.staleAbort,vn=e;let o=t;Sr&&typeof t=="string"&&(o=`${Sr}
|
|
1192
1194
|
|
|
1193
|
-
${t}`,
|
|
1195
|
+
${t}`,Sr=null),typeof o=="string"&&mg(o)&&(o+=`
|
|
1196
|
+
|
|
1197
|
+
[Note for assistant: the user appears frustrated \u2014 acknowledge their concern briefly and empathetically before proceeding]`);let r=pg(o);H.push({role:"user",content:r}),Yk();let i=n.autoOrchestrate!==!1&&process.env.NEX_AUTO_ORCHESTRATE!=="false",c=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:Me,runOrchestrated:Le}=$r(),He=Me(typeof t=="string"?t:"");if(i&&He.isComplex&&He.estimatedGoals>=c)return console.log(`${$.yellow}\u26A1 Auto-orchestrate: ${He.estimatedGoals} goals \u2192 parallel agents${$.reset}`),await Le(t,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});He.isComplex&&process.stdout.isTTY&&console.log(`${$.dim}Hint: ~${He.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${$.reset}`)}catch{}let{setOnChange:l}=Li(),u=null,d=0;l((Me,Le)=>{Me==="create"?(u&&u.stop(),u=new vS(Le.name,Le.tasks),u.setStats({tokens:d}),u.start()):Me==="update"&&u?u.updateTask(Le.id,Le.status):Me==="clear"&&u&&(u.stop(),u=null)});let f=await eu(),p=f;try{let{getBrainContext:Me}=Qo(),Le=await Me(t);Le&&(p=f+`
|
|
1194
1198
|
`+Le+`
|
|
1195
|
-
`)}catch(Me){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",Me.message)}let m=
|
|
1199
|
+
`)}catch(Me){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",Me.message)}let m=lk(typeof t=="string"?t:"");if(m.length>0){let Me=m.map(Le=>`[Triggered: ${Le.name}]
|
|
1196
1200
|
${Le.instructions}`).join(`
|
|
1197
1201
|
`);p+=`
|
|
1198
1202
|
`+Me+`
|
|
1199
|
-
`}let h=[{role:"system",content:p},...H];
|
|
1200
|
-
${ie}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...O.slice(1)]),
|
|
1201
|
-
`),Le=
|
|
1202
|
-
`+
|
|
1203
|
-
`));let
|
|
1203
|
+
`}let h=[{role:"system",content:p},...H];ES(un());let y=new wo(Al());y.start();let b=H.length===1,S=b?Vk().catch(()=>null):Promise.resolve(null),C=b?HS(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),k=yt(),[{messages:x,compressed:E,compacted:B,tokensRemoved:q},re,ie]=await Promise.all([OS(h,k),S,C]),Q=an(h,k);if(y.stop(),re&&console.log(`${$.dim}${re}${$.reset}`),B)console.log(`${$.dim} [context compacted \u2014 summary (~${q} tokens freed)]${$.reset}`);else if(E){let Me=Q.limit>0?Math.round(q/Q.limit*100):0;K(`${$.dim} [context compressed \u2014 ~${q} tokens freed (${Me}%)]${$.reset}`)}Q.percentage>85&&K(`${$.yellow} \u26A0 Context ${Math.round(Q.percentage)}% used (${Math.round(100-Q.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${$.reset}`);let O=x;if(ie&&b&&(O=[O[0],{role:"user",content:`[Server probe at task start]
|
|
1204
|
+
${ie}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...O.slice(1)]),b){let Me=KS(typeof t=="string"?t:"");Me&&(O=[O[0],{role:"user",content:Me.user},{role:"assistant",content:Me.assistant},...O.slice(1)])}if(an(O,yt()).percentage>=65){let{messages:Le,tokensRemoved:He}=bn(O,yt());He>0&&(O=Le,console.log(`${$.dim} [pre-flight compress \u2014 ${He} tokens freed, now ${Math.round(an(O,yt()).percentage)}% used]${$.reset}`))}let Te=0,X=0,V=0,fe=0,he=0,be=9,ye=0,Re=(()=>{let Me=H.find(Le=>Le.role==="user");return typeof Me?.content=="string"?Me.content:""})(),v=/set_reminder|google.?auth|cron:|api\.log|swarm.{0,30}(agent|crash|gecrasht|abgestürzt|fail)|agent.{0,30}(gecrasht|abgestürzt|crashed|fail)|server.{0,30}(passiert|fehler|crash|problem)|am.server/i.test(Re),j=0;if(!ut){let Me=H.filter(He=>He.role==="user"||He.role==="tool").map(He=>typeof He.content=="string"?He.content:"").join(`
|
|
1205
|
+
`),Le=ql(Me);Le&&(ut=!0,At=Le.slice(0,120),K(`${$.yellow} \u26A1 Root cause in briefing: ${At} \u2014 fix phase active from start (read budget: 3)${$.reset}`))}!ut&&!Jt&&/\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)&&(Jt=!0,K(`${$.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${$.reset}`)),H.length<=1&&!n.skipPhaseRouting&&(Oe=FS(),Oe&&(xo=qS(Re)?.id||"coding",Je="plan",In=Wl("plan",xo),Sa=0,kr=0,zn=0,process.stdout.isTTY&&console.log(`${$.dim} \u21B3 Phase routing: plan(${In||"default"}) \u2192 implement \u2192 verify${$.reset}`),K(`${$.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${In||"default model"} (category: ${xo})${$.reset}`)));let A=0,I=new Map,M=new Set,N=new Set,T=Date.now(),J=new TS(hk),ee=Cr,Z=n.skillLoop?10:1,ge=3*Z,Se=5*Z,xe=su,Ne=5*Z,Ue=8*Z,bt=ou,qe=(Oe?6:4)*Z,Wt=(Oe?10:7)*Z,Qn=Tr,Co=(Oe?5:3)*Z,es=(Oe?8:5)*Z,Is=ru,Kr=(Oe?4:3)*Z,js=(Oe?6:4)*Z,Fa=3*Z,Q$=4*Z,Ds=Gn,ey=(Oe?3:2)*Z,ty=(Oe?5:3)*Z,qs=(Oe?6:4)*Z,ny=25,ts=0,sy=6*Z,oy=10*Z,ns=0,zu=5*Z,ss=0,ry=2*Z,iy=3,Ua=0,Ao=10,ay=16,Xu=n.skillLoop?999:s.investigationCap,ot,mn=n.maxIterations||(Oe?Ts(Je):Kl),Ba=0,Vu=3,Wa=!1,Yr=0;e:for(;;){for(Wa=!1,ot=0;ot<mn&&!da()?.aborted;ot++){{let _=yt(),w=an(O,_),ce=A===0?65:78;if(w.percentage>=ce){if(M.size>0||Oe&&Je!=="plan"){let ae=MS(H,{filesModified:M,currentPhase:Oe?Je:null});if(ae){let W=O.findIndex(F=>F._progressSnapshot);W!==-1&&O.splice(W,1);let we=O.findIndex(F=>F.role==="system");O.splice(we+1,0,ae)}}let{messages:P,tokensRemoved:D}=bn(O,_,A===0);if(D>0&&(O=P,D>50&&console.log(`${$.dim} [auto-compressed \u2014 ~${D} tokens freed, now ${Math.round(an(O,_).percentage)}%]${$.reset}`),Jt&&M.size>=3)){let ae=[...M].map(we=>we.split("/").pop()).slice(0,10).join(", "),W={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${M.size} files: ${ae}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};O.push(W)}}}if(qt&&!ut&&vr<2){vr++;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."};O.push(_),H.push(_),K(`${$.yellow} \u26A0 Pre-call SSH-blocked nudge #${vr} injected \u2014 model told to synthesize${$.reset}`)}qt||(vr=0);let Le=!0;A>0&&tk();let He=null;if(u&&u.isActive())u._paused&&u.resume();else if(!u){let _,w=nk();if(w&&w.total>1){let ce=w.description.length>40?w.description.slice(0,37)+"\u2026":w.description;_=`Plan step ${w.current}/${w.total}: ${ce}`}else _=A>0?`${Al()} (step ${A+1})`:Al();He=new wo(_),He.start()}let Fs=!0,Nt="",Us=!1,mt=new sk,hn,Ha=Date.now(),Gr=!1,Ka=new AbortController,Ju=setInterval(()=>{let _=Date.now()-Ha;if(_>=jl)mt._clearCursorLine(),K(`${$.yellow} \u26A0 Stream stale for ${Math.round(_/1e3)}s \u2014 aborting and retrying${$.reset}`),Ka.abort();else if(_>=ag&&!Gr){Gr=!0,mt._clearCursorLine();let w=_a.fast?.[bo()],ce=V>0?` (retry ${V+1}/${la})`:"",P=Math.round((jl-_)/1e3);K(`${$.yellow} \u26A0 No tokens received for ${Math.round(_/1e3)}s \u2014 waiting...${ce}${$.reset}`),w&&w!==un()?console.log(`${$.dim} \u{1F4A1} Will auto-switch to ${w} in ~${P}s if no tokens arrive${$.reset}`):console.log(`${$.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${P}s${$.reset}`)}},5e3),Ht="",Sn=null;try{let _=hg(yt()),w=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),ce=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),P;Er()?P=_.filter(W=>fg.has(W.function.name)):Oe&&Je==="plan"?P=_.filter(W=>w.has(W.function.name)):Oe&&Je==="verify"?P=_.filter(W=>ce.has(W.function.name)):P=_;let D=da(),ae=new AbortController;D&&D.addEventListener("abort",()=>ae.abort(),{once:!0}),Ka.signal.addEventListener("abort",()=>ae.abort(),{once:!0}),hn=await Qh(O,P,{signal:ae.signal,...In?{model:In}:{},onThinkingToken:()=>{Ha=Date.now(),Gr=!1,vn?.onThinkingToken&&vn.onThinkingToken()},onToken:W=>{if(Ha=Date.now(),Gr=!1,vn?.onToken){vn.onToken(W),Nt+=W;return}if(Nt+=W,!Us&&Nt.length>400&&Nt.length%250<W.length+1){let we=Hl(Nt,3);we.truncated&&(Us=!0,mt._clearCursorLine?.(),K(`${$.yellow} \u26A0 LLM stream loop detected (${we.repeatCount}\xD7 repeated) \u2014 suppressing display${$.reset}`))}Us||(Ht+=W,process.stdout.isTTY?Sn||(Sn=setTimeout(()=>{Ht&&mt&&mt.push(Ht),Ht="",Sn=null},50)):(mt.push(Ht),Ht=""),Fs&&(u&&!u._paused?u.pause():He&&He.stop(),Le||(Le=!0),mt.startCursor(),Fs=!1))}})}catch(_){if(clearInterval(Ju),Sn&&(clearTimeout(Sn),Sn=null),Ht&&mt&&(mt.push(Ht),Ht=""),u&&!u._paused&&u.pause(),He&&He.stop(),mt.stopCursor(),Ka.signal.aborted&&!da()?.aborted){if(V++,V>la){if(fe<1){fe++,yo("Stale retries exhausted \u2014 last-resort force-compress...",$.yellow);let we=yt(),{messages:F,tokensRemoved:Y}=bn(O,we);O=F,Y>50&&K(`${$.dim} [force-compressed \u2014 ~${Y} tokens freed]${$.reset}`),V=0,ot--;continue}u&&(u.stop(),u=null);let W=await Zk();if(W.action==="quit"){l(null),nt(A,I,M,N,T),tt(H);break}W.action==="switch"&&(rg(`${W.provider}:${W.model}`),console.log(`${$.green} \u2713 Switched to ${W.provider}:${W.model}${$.reset}`)),V=0,ot--;continue}let D=V===1?3e3:5e3;if(V>=1&&ye<1){ye++,yo(`Stale retry ${V}/${la} \u2014 force-compressing before retry...`,$.yellow);let W=yt(),{messages:we,tokensRemoved:F}=bn(O,W,!0);if(O=we,F>0&&F>50&&K(`${$.dim} [force-compressed \u2014 ~${F} tokens freed]${$.reset}`),Mk){let Y=_a.fast?.[bo()];Y&&Y!==un()&&(rg(`${bo()}:${Y}`),console.log(`${$.cyan} \u26A1 Auto-switched to ${Y} to avoid further stale timeouts${$.reset}`),console.log(`${$.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${$.reset}`))}}else K(`${$.yellow} \u26A0 Stale retry ${V}/${la} \u2014 retrying in ${D/1e3}s...${$.reset}`);let ae=new wo(`Waiting ${D/1e3}s before retry...`);ae.start(),await new Promise(W=>setTimeout(W,D)),ae.stop(),ot--;continue}if(_.name==="AbortError"||_.name==="CanceledError"||_.message?.includes("canceled")||_.message?.includes("aborted")){u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T),tt(H);break}let w=_.message;if(_.code==="ECONNREFUSED"||_.message.includes("ECONNREFUSED"))w="Connection refused \u2014 please check your internet connection or API endpoint";else if(_.code==="ENOTFOUND"||_.message.includes("ENOTFOUND"))w="Network error \u2014 could not reach the API server. Please check your connection";else if(_.code==="ETIMEDOUT"||_.message.includes("timeout"))w="Request timed out \u2014 the API server took too long to respond. Please try again";else if(_.message.includes("401")||_.message.includes("Unauthorized"))w="Authentication failed \u2014 please check your API key in the .env file";else if(_.message.includes("403")||_.message.includes("Forbidden"))w="Access denied \u2014 your API key may not have permission for this model";else if(_.message.includes("404")){w=`Model not found (404): ${un?un():"unknown"} \u2014 check your .env MODEL setting or run /models to list available models`,console.log(`${$.red} \u2717 ${w}${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T),tt(H);break}else if(_.message.includes("400")){if(fe<3&&he<be){fe++,he++;let D=A===0&&fe===1,ae=D||fe===3||ye>0;if(D){fe=3;let Y=_.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);yo(`Bad request (400) \u2014 ${Y||"system prompt too large"}, compressing...`,$.yellow)}else yo(ae?`Bad request (400) \u2014 nuclear compression (attempt ${fe}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${fe}/3)`,$.yellow);let W=yt(),{messages:we,tokensRemoved:F}=bn(O,W,ae);O=we,F>50&&K(`${$.dim} [force-compressed \u2014 ~${F} tokens freed]${$.reset}`),ot--;continue}{let D=O.find(G=>G.role==="system"),ae=O.find(G=>G.role==="user"&&!String(G.content).startsWith("[SYSTEM")&&!String(G.content).startsWith("BLOCKED:")),W=[D,ae].filter(Boolean),{getUsage:we}=Lt(),F=Lt().estimateMessagesTokens(W),Y=Lt().estimateMessagesTokens(O);if(F<Y){let G=[],te=H.filter(ue=>ue.role==="assistant"&&typeof ue.content=="string"&&ue.content.trim().length>30).slice(-5).map(ue=>ue.content.trim().slice(0,300).replace(/\n+/g," "));te.length>0&&G.push(`Key findings:
|
|
1206
|
+
`+te.map(ue=>`- ${ue}`).join(`
|
|
1207
|
+
`));let se=H.filter(ue=>ue.role==="tool"&&typeof ue.content=="string"&&!ue.content.startsWith("BLOCKED:")&&ue.content.trim().length>10).slice(-5).map(ue=>ue.content.trim().split(`
|
|
1204
1208
|
`).slice(0,8).join(`
|
|
1205
|
-
`).slice(0,500));if(
|
|
1206
|
-
`+
|
|
1207
|
-
`)),M.size>0){let ue=[...M].map(Xe=>Xe.split("/").slice(-2).join("/")).join(", ");
|
|
1208
|
-
${JSON.stringify(
|
|
1209
|
-
${
|
|
1209
|
+
`).slice(0,500));if(se.length>0&&G.push(`Tool results summary:
|
|
1210
|
+
`+se.map(ue=>`- ${ue}`).join(`
|
|
1211
|
+
`)),M.size>0){let ue=[...M].map(Xe=>Xe.split("/").slice(-2).join("/")).join(", ");G.unshift(`Already modified: ${ue} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(N.size>0){let ue=[...N].map(Xe=>Xe.split("/").slice(-2).join("/")).join(", ");G.push(`Files already investigated: ${ue}`)}let pe=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(pe,JSON.stringify({filesWritten:[...M].map(ue=>ue.split("/").slice(-2).join("/")),filesRead:[...N].map(ue=>ue.split("/").slice(-2).join("/")),isCreationTask:Jt,wipeNumber:xr+1,timestamp:Date.now()},null,2)),G.push(`Session checkpoint: ${pe} \u2014 read it for exact file list`)}catch{}let ke=0;{let Xe=((typeof ae?.content=="string"?ae.content:Array.isArray(ae?.content)?ae.content.filter(ct=>ct.type==="text").map(ct=>ct.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(ct=>ct.trim()).filter(Boolean),rt=[...M],Kt=Xe.filter(ct=>!rt.some(za=>za.endsWith(ct)||ct.endsWith(za.split("/").pop())));ke=Kt.length;let Mt=[...H].reverse().find(ct=>ct.role==="tool"&&typeof ct.content=="string"&&!ct.content.startsWith("BLOCKED:")&&ct.content.length>5),En={completed:rt.map(ct=>ct.split("/").slice(-2).join("/")),pending:Kt.length>0?Kt:rt.length===0?["(task files not yet identified)"]:[],lastEdit:Mt?Mt.content.trim().slice(0,120):null};(En.completed.length>0||En.pending.length>0)&&G.unshift(`Work manifest:
|
|
1212
|
+
${JSON.stringify(En,null,2)}`)}if(G.length>0){let ue={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
|
|
1213
|
+
${G.join(`
|
|
1210
1214
|
`)}
|
|
1211
|
-
Continue implementing the fixes based on these findings.`};W.push(ue)}if(
|
|
1212
|
-
Files modified so far: ${[...M].map(Xe=>Xe.split("/").slice(-1)[0]).join(", ")}`:"";K(`${$.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${$.reset}`),console.log(`${$.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${ue?$.dim+ue:""}${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,
|
|
1215
|
+
Continue implementing the fixes based on these findings.`};W.push(ue)}if(xr>=3){let ue=M.size>0?`
|
|
1216
|
+
Files modified so far: ${[...M].map(Xe=>Xe.split("/").slice(-1)[0]).join(", ")}`:"";K(`${$.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${$.reset}`),console.log(`${$.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${ue?$.dim+ue:""}${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T,{suppressHint:!0}),tt(H);break}O=W,xr++,Cs=12+Math.min(ke*3,15),Xl=!0,ga=M.size,$a=!1,Vt=0,j=0;for(let[ue,Xe]of Gn){let rt=Xe?.count??Xe??0;Fl(Gn,ue,rt>=2?rt:1)}for(let[ue]of Pn)_n(Gn,ue)<2&&Pn.delete(ue);Xt.clear(),Ns.clear(),Jt&&ln>0&&(cn=!0,K(`${$.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${ln} edits already made)${$.reset}`));for(let[ue]of Tr)Fl(Tr,ue,es-1);if(yo(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${Y-F} tokens freed)`,$.yellow),xr>=1){let ue=[...Gn.entries()].filter(([,Mt])=>Mt>=qs).map(([Mt])=>Mt.split("/").slice(-1)[0]),Xe=ue.length>0?`
|
|
1213
1217
|
|
|
1214
|
-
Files already at read cap \u2014 use grep_search instead: ${ue.join(", ")}`:"",
|
|
1215
|
-
Use /undo to revert changes made during this session.${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,
|
|
1218
|
+
Files already at read cap \u2014 use grep_search instead: ${ue.join(", ")}`:"",Kt={role:"user",content:qt&&!ut?"[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.${Xe}`};H.push(Kt),O.push(Kt)}fe=0,ot--;continue}}w="Context too large to compress \u2014 use /clear to start fresh"}else _.message.includes("500")||_.message.includes("502")||_.message.includes("503")||_.message.includes("504")?w="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(_.message.includes("fetch failed")||_.message.includes("fetch"))&&(w="Network request failed \u2014 please check your internet connection");if(console.log(`${$.red} \u2717 ${w}${$.reset}`),_.message.includes("429")){if(Te++,Te>Ll){console.log(`${$.red} Rate limit: max retries (${Ll}) exceeded. Try again later or use /budget to check your limits.${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T),tt(H);break}let D=Math.min(1e4*Math.pow(2,Te-1),12e4),ae=new wo(`Rate limit \u2014 waiting ${Math.round(D/1e3)}s (retry ${Te}/${Ll})`);ae.start(),await new Promise(W=>setTimeout(W,D)),ae.stop();continue}let ce=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return Be().getActiveProviderName()==="ollama"}catch{return!1}})();if(_.message.includes("socket disconnected")||_.message.includes("TLS")||_.message.includes("ECONNRESET")||_.message.includes("ECONNABORTED")||_.message.includes("ETIMEDOUT")||ce&&(_.message.includes("500")||_.message.includes("502")||_.message.includes("503")||_.message.includes("504")||_.message.includes("401")||_.message.includes("Unauthorized"))||_.code==="ECONNRESET"||_.code==="ECONNABORTED"){if(X++,X>Il){console.log(`${$.red} Network error: max retries (${Il}) exceeded. Check your connection and try again.
|
|
1219
|
+
Use /undo to revert changes made during this session.${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T),tt(H);break}let D=Math.min(2e3*Math.pow(2,X-1),3e4),ae=new wo(`API temporarily unavailable \u2014 retrying in ${Math.round(D/1e3)}s (${X}/${Il}). Your changes are safe.`);ae.start(),await new Promise(W=>setTimeout(W,D)),ae.stop(),ot--;continue}u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T),tt(H);break}if(clearInterval(Ju),Te=0,X=0,Fs&&(u&&!u._paused&&u.pause(),He&&He.stop()),Sn&&(clearTimeout(Sn),Sn=null),Ht&&mt&&(mt.push(Ht),Ht=""),Nt&&mt.flush(),X=0,V=0,hn&&hn.usage){let _=hn.usage.prompt_tokens||0,w=hn.usage.completion_tokens||0;tg(bo(),un(),_,w),d+=_+w,u&&u.setStats({tokens:d})}else if(hn&&!hn.usage){let _=O.map(P=>typeof P.content=="string"?P.content:Array.isArray(P.content)?P.content.map(D=>typeof D=="string"?D:D.text||"").join(""):"").join(" "),w=sg(_),ce=sg(hn.content||Nt||"");tg(bo(),un(),w,ce),d+=w+ce,u&&u.setStats({tokens:d})}let{content:Zu,tool_calls:kn}=hn,zr=Hl(Zu||""),Qu=zr.truncated?zr.text:Zu;zr.truncated&&K(`${$.yellow} \u26A0 LLM output loop detected (${zr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${$.reset}`);let Xr=bk(Qu||""),gn=Xr.truncated?Xr.text:Qu;Xr.truncated&&K(`${$.yellow} \u26A0 LLM output loop detected (${Xr.repeatCount}\xD7 repeated window) \u2014 response truncated${$.reset}`);let Ya={role:"assistant",content:gn||""};if(kn&&kn.length>0&&(Ya.tool_calls=kn),H.push(Ya),O.push(Ya),!ut&&gn&&kn&&kn.length>0){let _=ql(gn);if(_){ut=!0,At=_.slice(0,120),xn=0,cn=!1,Ln=0,K(`${$.yellow} \u26A1 Root cause in model analysis: ${At} \u2014 fix phase (read budget: 3)${$.reset}`);let w={role:"user",content:`[SYSTEM] Root cause identified: ${At}. Read only the file that needs fixing, then edit it. Do not read other files.`};H.push(w),O.push(w)}}if(!kn||kn.length===0){let _=(gn||"").trim().length>0||Nt.trim().length>0,w=!1;if(qt&&_&&(ua>=2?K(`${$.yellow} \u26A0 SSH permanently blocked after ${ua} storm warnings \u2014 no further SSH calls allowed${$.reset}`):(qt=!1,Vt=Ao-4,w=!0)),w&&_){let P=(gn||"").trim();if(P.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(P.slice(-200))){let ae={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};O.push(ae),H.push(ae);continue}}if(!_&&A>0&&ot<Kl-1){let P={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};O.push(P),H.push(P);continue}let ce=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if(_&&ot<3&&ce.test((gn||"").slice(0,600)))if(Xl&&Cs<=0||qt){K(`${$.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${$.reset}`);let D={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."};O.push(D),H.push(D);continue}else{K(`${$.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${$.reset}`);let D={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."};O.push(D),H.push(D);continue}if(n.skillLoop&&_&&A>3&&Yr<5){let P=(gn||Nt||"").toLowerCase();if(/\b(i.ll stop|stop the|stopped|done with|complet|summar|conclud|no more|finish|end of|that.s all|final|wrapped up|no further|mindful of|reached.*limit|tool call limit|at this point|recommend keep)/.test(P.slice(-600))){Yr=(Yr||0)+1,K(`${$.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${Yr}${$.reset}`);let ae={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."};O.push(ae),H.push(ae);continue}}if(Oe&&Je==="plan"&&zn>=2){K(`${$.cyan} \u21B3 Plan phase: ${zn} consecutive blocks \u2014 auto-advancing to implement${$.reset}`),zn=0;let P=wr("implement","[auto-advance: task only requires direct action]");if(P){H.push(P),O.push(P),ot=0,mn=Ts("implement");continue}}if(Oe&&_){let P=(gn||Nt||"").trim();if(Je==="plan"){let D=wr("implement",P);if(D){H.push(D),O.push(D),ot=0,mn=Ts("implement");continue}}else if(Je==="implement"&&M.size>0){let D=H.find(we=>we.role==="user"),ae=typeof D?.content=="string"?D.content:"",W=wr("verify",P,M,ae);if(W){H.push(W),O.push(W),ot=0,mn=Math.min(Ts("verify")+Math.max(0,(M.size-2)*2),20);continue}}else if(Je==="verify"){let ae=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(P.slice(0,500));if(ae&&kr<1){kr++;let W={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
|
|
1216
1220
|
${P.slice(0,400)}
|
|
1217
1221
|
|
|
1218
|
-
Fix the identified issues. This is the final attempt.`};Je="implement",
|
|
1222
|
+
Fix the identified issues. This is the final attempt.`};Je="implement",In=Wl("implement",xo),H.push(W),O.push(W),ot=0,mn=Ts("implement"),K(`${$.yellow} \u21B3 Verify \u2192 implement loop-back #${kr} (issues found)${$.reset}`);continue}if(K(`${$.green} \u2713 Verification phase complete${ae?" (loop-back exhausted)":" (PASS)"}${$.reset}`),!ae){nt(A,I,M,N,T),tt(H),Ol(H);break e}}}if(Er()&&_&&A===0)if(pa++,pa>2)K(`${$.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${$.reset}`);else{let P={role:"user",content:`[SYSTEM] You wrote a plan without reading any files. This plan may be based on incorrect assumptions (wrong database type, wrong file structure, etc.).
|
|
1219
1223
|
|
|
1220
|
-
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.`};H.push(P),O.push(P),K(`${$.yellow} \u26A0 Plan rejected (${
|
|
1221
|
-
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${D.length} ${we})${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${$.reset} ${$.yellow}[E]${$.reset}${$.dim}dit${$.reset} ${$.red}[R]${$.reset}${$.dim}eject${$.reset} ${$.dim}[\u21B5 = approve]:${$.reset} `);let
|
|
1222
|
-
`),pe==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(pe==="e")console.log(`${$.yellow}Type /plan edit to open in editor, or give feedback.${$.reset}`);else if(Y()){
|
|
1224
|
+
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.`};H.push(P),O.push(P),K(`${$.yellow} \u26A0 Plan rejected (${pa}/2): no files read \u2014 forcing investigation${$.reset}`);continue}if(Er()&&_){let P=(gn||Nt||"").trim();ZS(P),Pk(P);let D=QS(P);if(D.length>0){let ae=H.find(Y=>Y.role==="user"),W=typeof ae?.content=="string"?ae.content.slice(0,120):"Task";ek(W,D);let we=D.length===1?"step":"steps",F=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:Y,startExecution:G,setPlanMode:te}=rn();process.stdout.write(`
|
|
1225
|
+
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${D.length} ${we})${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${$.reset} ${$.yellow}[E]${$.reset}${$.dim}dit${$.reset} ${$.red}[R]${$.reset}${$.dim}eject${$.reset} ${$.dim}[\u21B5 = approve]:${$.reset} `);let se=process.stdin.isRaw,pe=await new Promise(ke=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",ue=>{try{process.stdin.setRawMode(se||!1)}catch{}let Xe=ue.toString().toLowerCase()[0]||"\r";ke(Xe)})});if(process.stdout.write(`
|
|
1226
|
+
`),pe==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(pe==="e")console.log(`${$.yellow}Type /plan edit to open in editor, or give feedback.${$.reset}`);else if(Y()){G(),te(!1),Gl(),console.log(`${$.green}${$.bold}Approved!${$.reset} Executing ${D.length} ${we}...`);let ke=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1223
1227
|
|
|
1224
1228
|
Implement the following plan step by step. All tools are now available.
|
|
1225
1229
|
|
|
1226
|
-
${P}`;H.push({role:"user",content:
|
|
1227
|
-
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${D.length} ${we} extracted).${$.reset} Type ${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ${$.reset}${$.cyan}/plan edit${$.reset}${$.dim} to review.${$.reset}`);if(F){u&&(u.stop(),u=null),ot--;continue}}else{let ae=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:W,startExecution:we,setPlanMode:F}=
|
|
1228
|
-
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${$.reset} ${$.red}[R]${$.reset}${$.dim}eject${$.reset} ${$.dim}[\u21B5 = approve]:${$.reset} `);let Y=process.stdin.isRaw,
|
|
1229
|
-
`),
|
|
1230
|
+
${P}`;H.push({role:"user",content:ke}),O.push({role:"user",content:ke}),F=!0}}else console.log(`
|
|
1231
|
+
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${D.length} ${we} extracted).${$.reset} Type ${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ${$.reset}${$.cyan}/plan edit${$.reset}${$.dim} to review.${$.reset}`);if(F){u&&(u.stop(),u=null),ot--;continue}}else{let ae=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:W,startExecution:we,setPlanMode:F}=rn();process.stdout.write(`
|
|
1232
|
+
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${$.reset} ${$.red}[R]${$.reset}${$.dim}eject${$.reset} ${$.dim}[\u21B5 = approve]:${$.reset} `);let Y=process.stdin.isRaw,G=await new Promise(te=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",se=>{try{process.stdin.setRawMode(Y||!1)}catch{}te(se.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
|
|
1233
|
+
`),G==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(W()){we(),F(!1),Gl(),console.log(`${$.green}${$.bold}Approved!${$.reset} Executing...`);let se=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1230
1234
|
|
|
1231
1235
|
Implement the following plan step by step. All tools are now available.
|
|
1232
1236
|
|
|
1233
|
-
${getPlanContent()||
|
|
1234
|
-
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.dim}Type ${$.reset}${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ask follow-up questions to refine.${$.reset}`);if(ae){u&&(u.stop(),u=null),ot--;continue}}}if(u&&(u.stop(),u=null),l(null),nt(A,I,M,N,
|
|
1235
|
-
${W}`),H.push({role:"user",content:P},{role:"assistant",content:W}))}catch{}tt(H),Tl(H);return}A++,_a++,A>=1&&(Le=!1);for(let _ of vn){let b=_.function.name;I.set(b,(I.get(b)||0)+1)}if(A>=30&&!tg){tg=!0,K(`${$.yellow} \u26A0 Tool budget warning: ${A} tool calls used \u2014 nudging model to wrap up${$.reset}`);let _={role:"user",content:"[SYSTEM] \u26A0 You have used "+A+" 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."};H.push(_),O.push(_)}let Ce=await Promise.all(vn.map(_=>$k(_)));{let _=rn(O,$t()),b=_.percentage,ce=Ce.some(W=>W.canExecute&&W.fnName==="read_file"&&!W.args?.line_end),P=Ce.filter(W=>W.canExecute&&W.fnName==="read_file"&&W.args?.path&&wn(js,W.args.path)>=1&&!W.args?.line_start).map(W=>W.args.path.split("/").slice(-2).join("/")),D=P.length>0;if(b>=70&&ce&&Da<70||b>=85&&Da<85||D){Da=b;let W=b>=85?"URGENT":"WARNING",we;D?(W="WARNING",we=`Full-file read of ${P.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):ce?we=`Unbounded read at ${Math.round(b)}% context \u2014 use line_start/line_end to avoid overflow.`:we="Use targeted reads (line_start/line_end) to save space.";let F={role:"user",content:`[SYSTEM ${W}] Context ${Math.round(b)}% used (${_.used}/${_.limit} tokens). ${we}`};if(H.push(F),O.push(F),b>=85){let Y=D?` (re-read of: ${P.join(", ")})`:"";K(`${$.yellow} \u26A0 Context ${Math.round(b)}% used \u2014 agent warned to use targeted reads${Y}${$.reset}`)}}}let Ha=new Map;for(let _ of Ce){if(!_.canExecute||_.fnName!=="read_file")continue;let b=_.args?.path;if(!b)continue;let ce=wn(js,b),P=Ha.get(b)||0,D=ce+P,ae=_.args?.line_start!=null,W=Rs.get(b)||0,we=W>0,F=2;if(D>=Ds){let Y=b.split("/").slice(-2).join("/"),z=(Ns.get(b)||0)+1;if(Ns.set(b,z),z===1)K(`${$.red} \u2716 Blocked: "${Y}" read ${D}\xD7 \u2014 hard cap (${Ds}) reached${$.reset}`);else if(z===2){K(`${$.red} \u2716 Escalated block: "${Y}" \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let se={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${b}") and tried again anyway. This file has reached its read cap (${Ds}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};H.push(se),O.push(se)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already read ${D}\xD7 (hard cap: ${Ds}). 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(D>=1&&ae)if(we&&W<=F){let Y=b.split("/").slice(-2).join("/");console.log(`${$.cyan} \u21A9 Targeted re-read: "${Y}" (line_start=${_.args.line_start}) \u2014 edit recovery #${W}${$.reset}`),Rs.set(b,W-1)}else if(we&&W>F){let Y=b.split("/").slice(-2).join("/");K(`${$.red} \u2716 Edit recovery blocked: "${Y}" \u2014 ${F} recovery reads already used. Use grep to find the exact line numbers, then retry.${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 edit recovery budget exhausted (${F} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:_.callId}}else{let Y=_.args.line_start||1,z=_.args.line_end||Y+350,se=Nn.get(b)||[],oe=!1;for(let[pe,Se]of se){let ue=Math.max(Y,pe),Xe=Math.min(z,Se);if(Xe>ue){let rt=Xe-ue,Ht=z-Y||1,Nt=Se-pe||1,Sn=rt/Nt>=.7&&rt/Ht<.7,at=z-Y<=U$;if(rt>=Ht||!at&&(rt/Ht>=.7||rt/Nt>=.7)){let Ya=b.split("/").slice(-2).join("/"),Vu=`${b}:${Y}-${z}`,Bs=(wa.get(Vu)||0)+1;if(wa.set(Vu,Bs),K(Sn?`${$.red} \u2716 Blocked superread: "${Ya}" lines ${Y}-${z} subsumes already-read ${pe}-${Se} \u2014 use line_start=${Se+1} to skip known content (block #${Bs})${$.reset}`:`${$.red} \u2716 Blocked duplicate read: "${Ya}" lines ${Y}-${z} (\u226570% overlap with lines ${pe}-${Se} already in context, block #${Bs})${$.reset}`),Bs>=2){K(`${$.red} \u2716 Escalated range-block: "${Ya}" lines ${Y}-${z} \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let Ju={role:"user",content:Sn?`[SYSTEM] Read blocked ${Bs}\xD7 for read_file("${b}", lines ${Y}-${z}). Lines ${pe}-${Se} were already read. Use line_start=${Se+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Bs}\xD7 for read_file("${b}", lines ${Y}-${z}). Lines ${pe}-${Se} were already read and will NOT change. Use grep_search to find specific content instead.`};H.push(Ju),O.push(Ju)}_.canExecute=!1,_.errorResult={role:"tool",content:Sn?`BLOCKED: read_file("${b}", lines ${Y}-${z}) re-reads lines ${pe}-${Se} already in context. Use line_start=${Se+1} to read only the new content beyond line ${Se}.`:`BLOCKED: read_file("${b}", lines ${Y}-${z}) is a duplicate \u2014 lines ${pe}-${Se} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:_.callId},oe=!0;break}}}if(!oe){let pe=se.length,Se=2;if(pe>=3){let Xe=b.split("/").slice(-2).join("/");K(`${$.red} \u2716 Blocked file-scroll: "${Xe}" \u2014 ${pe} sections already read. Use grep to find specific content.${$.reset}`);let rt=wn(Zn,b)>=Qn;_.canExecute=!1,_.errorResult={role:"tool",content:rt?`BLOCKED: read_file("${b}") denied \u2014 you have already read ${pe} different sections of this file (file-scroll pattern). Grep is also exhausted. The content you need is already in your context \u2014 work with what you have.`:`BLOCKED: read_file("${b}") denied \u2014 you have already read ${pe} 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 pe>=Se&&(_._scrollWarn={sectionCount:pe+1,path:b})}}else if(D>=1){let Y=b.split("/").slice(-2).join("/"),z=(Ns.get(b)||0)+1;if(Ns.set(b,z),z===1)K(`${$.red} \u2716 Blocked unbounded re-read: "${Y}" \u2014 already in context. Use line_start/line_end for specific sections.${$.reset}`);else if(z===2){K(`${$.red} \u2716 Escalated block: "${Y}" \u2014 model ignored unbounded re-read block, injecting system warning${$.reset}`);let se={role:"user",content:`[SYSTEM] read_file("${b}") was blocked again \u2014 full-file reads are disabled after the first read. Use line_start/line_end for a specific section, or use grep_search to find what you need.`};H.push(se),O.push(se)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already in context (read ${D}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:_.callId}}_.canExecute&&Ha.set(b,(Ha.get(b)||0)+1)}if(Kn>=3)for(let _ of Ce)_.canExecute&&(_.fnName!=="read_file"&&_.fnName!=="edit_file"||(K(`${$.red} \u2716 Blocked ${_.fnName} \u2014 ${Kn} consecutive file-not-found errors, must search first${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${Kn} 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 Ce){if(!_.canExecute||_.fnName!=="bash")continue;let b=(_.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(b)&&!/npm|yarn|pnpm|make|git/.test(b)){K(`${$.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:_.callId};continue}/\bfind\s+[\S.]/.test(b)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(b)&&(K(`${$.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:_.callId})}for(let _ of Ce)_.canExecute&&(_.fnName!=="ssh_exec"&&_.fnName!=="bash"||/\bsed\s+-n\b/.test(_.args?.command||"")&&(K(`${$.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:'BLOCKED: sed -n is forbidden \u2014 it floods context with line ranges. Use grep -n "pattern" <file> | head -30 to read a specific section, or cat <file> for the full file.',tool_call_id:_.callId}));for(let _ of Ce){if(!_.canExecute||_.fnName!=="write_file")continue;let b=_.args?.path,ce=_.args?.content||"";if(b)try{let P=require("fs"),D=require("path").resolve(process.cwd(),b);if(P.existsSync(D)){let ae=P.statSync(D).size,W=Buffer.byteLength(ce,"utf8"),we=ae>0?W/ae:1;if(we<.6&&ae>200){let F=b.split("/").slice(-2).join("/");console.log(`${$.red} \u2716 write_file shrink guard: "${F}" would shrink to ${Math.round(we*100)}% of original \u2014 likely context loss${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: write_file("${b}") denied \u2014 new content is only ${Math.round(we*100)}% of current file size (${ae} \u2192 ${W} 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 Yu=new Map;for(let _ of Ce){if(!_.canExecute||_.fnName!=="grep")continue;let b=_.args?.path;if(!b)continue;let ce=Yu.get(b)||0,P=wn(Zn,b)+ce,D=wn(js,b)>=1,ae=D?Math.min(3,Qn):Qn;if(P>=ae){let W=b.split("/").slice(-2).join("/");K(`${$.red} \u2716 Blocked grep: "${W}" grepped ${P}\xD7 with different patterns \u2014 flood threshold exceeded${$.reset}`);let we=wn(js,b),F=we>=Ds;if(F){let Y={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${b}". You have already read ${we} sections and tried ${P} grep patterns. Do NOT attempt to read or grep this file again. The content you need is already in your conversation context \u2014 scroll back to find it, or proceed with what you know.`};H.push(Y),O.push(Y),K(`${$.red} \u2716 Deadlock detected: "${W}" \u2014 both read and grep blocked, injecting deadlock-break${$.reset}`)}_.canExecute=!1,_.errorResult={role:"tool",content:F?`BLOCKED: grep("${b}") denied \u2014 ${P} patterns already tried AND reads are also exhausted. The content is already in your context. Do not attempt to read or grep this file again.`:D?`BLOCKED: grep("${b}") denied \u2014 file was already read and ${P} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${b}") denied \u2014 ${P} patterns already tried. Work with the grep results already in your context.`,tool_call_id:_.callId}}_.canExecute&&Yu.set(b,ce+1)}let G$=5,Gu=new Map;for(let _ of Ce){if(!_.canExecute||_.fnName!=="ssh_exec")continue;let ce=(_.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),P=Gu.get(ce)||0,D=wn(xe,ce)+P;D>=G$&&(K(`${$.yellow} \u26A0 Blocked ssh_exec: same command run ${D}\xD7 \u2014 result already in context${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${D} 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&&Gu.set(ce,P+1)}if(Dt){let _=Ce.filter(P=>P.canExecute&&P.fnName==="ssh_exec"),b=Ce.some(P=>P.canExecute&&P.fnName!=="ssh_exec"),ce=v&&j<3;if(_.length>0&&!b&&ce&&fa<1)Dt=!1,fa++,zt=Math.max(0,Co-2),K(`${$.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${fa}/1)]${$.reset}`);else for(let P of _)P.canExecute=!1,P.errorResult={role:"tool",content:lt?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Co}+ 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 (${Co}+ calls). Provide a text summary of your findings first. Do NOT ask the user to run commands. SSH re-enables after your summary. For one-off lookups use bash("ssh user@host 'cmd'") instead.`,tool_call_id:P.callId}}if(v&&j<3&&!Dt){for(let _ of Ce)if(_.canExecute&&["bash","read_file","find_files"].includes(_.fnName)){j++;{let b=$t(),{messages:ce}=yn(O,b);O=ce}K(`${$.yellow} \u26A0 Server-local guard: blocking local ${_.fnName} \u2014 use ssh_exec on 94.130.37.43${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${_.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:_.callId};break}}if(!Oe&&an&&Xt&&cn>=1){let _=["read_file","grep","search_files","glob","list_directory","find_files"];for(let b of Ce)b.canExecute&&_.includes(b.fnName)&&(K(`${$.red} \u2716 Creation hard-block: ${b.fnName} denied \u2014 cap fired, files already written${$.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.",tool_call_id:b.callId})}if(Cs>=0){let _=Ce.filter(b=>b.canExecute).length;if(_>0&&(Cs-=_,Cs<0))if(!ma&&M.size>pa){ma=!0,Cs=5,K(`${$.green} \u2713 Post-wipe progress detected (${M.size-pa} files modified) \u2014 granting 5 bonus tool calls${$.reset}`);let b={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};H.push(b),O.push(b)}else{K(`${$.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${$.reset}`);for(let ce of Ce)ce.canExecute&&(ce.canExecute=!1,ce.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:ce.callId});let b={role:"user",content:"[SYSTEM] Post-wipe tool budget exhausted. All tool calls are now blocked. Respond with a final summary of what was done and stop \u2014 do not attempt any more tool calls."};H.push(b),O.push(b)}}let z$=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 Ce){if(!_.canExecute||z$.has(_.fnName))continue;let b=JSON.stringify(_.args||{}),ce=`${_.fnName}|${b}`,P=wn(ba,ce);P>=2?(K(`${$.red} \u2716 Blocked duplicate: ${_.fnName}(${b.substring(0,80)}) \u2014 called ${P+1}\xD7 with identical args${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${_.fnName}() with these exact arguments has already been called ${P}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:_.callId}):P===1&&K(`${$.yellow} \u26A0 Duplicate tool call: ${_.fnName}(${b.substring(0,80)}) \u2014 2nd call with identical args${$.reset}`),Ts(ba,ce)}let Ao=u?{skipSpinner:!0,skipSummaries:!0}:{},X$=Ce.some(_=>_.fnName==="ask_user"),zu=!Ao.skipSummaries&&!Le,Gr=null,Us=null;zu&&!X$?(Le=!0,Ao.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(Us=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write(ra(Ce,A,!1,"blink")),Gr=!0):_n||process.stdout.write(ra(Ce,A,!1)+`
|
|
1236
|
-
`)):
|
|
1237
|
+
${getPlanContent()||hn.content}`;H.push({role:"user",content:se}),O.push({role:"user",content:se}),ae=!0}}else console.log(`
|
|
1238
|
+
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.dim}Type ${$.reset}${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ask follow-up questions to refine.${$.reset}`);if(ae){u&&(u.stop(),u=null),ot--;continue}}}if(u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T),Jt&&M.size>=3){let P=[...M].map(F=>F.split("/").pop()).slice(0,8).join(", "),D=[...M].some(F=>F.endsWith("package.json")),ae=[...M].some(F=>F.endsWith("requirements.txt")),W=[...M].some(F=>F.endsWith("package-lock.json")||F.endsWith("yarn.lock")||F.endsWith("pnpm-lock.yaml")),we=D&&!W?"npm install not yet run":ae?"pip install not yet run":null;Sr=`[Previous session created ${M.size} files: ${P}`+(we?` \u2014 ${we}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Jt&&!Vl&&A>0){let P=[...M].some(se=>se.endsWith("package.json")),D=[...M].some(se=>se.endsWith("requirements.txt")||se.endsWith("Pipfile")||se.endsWith("pyproject.toml")),ae=[...M].some(se=>se.endsWith("package-lock.json")||se.endsWith("yarn.lock")||se.endsWith("pnpm-lock.yaml")),W=H.flatMap(se=>{let pe=Array.isArray(se.tool_calls)?se.tool_calls:[],ke=Array.isArray(se.content)?se.content.filter(ue=>ue?.type==="tool_use"):[];return[...pe,...ke]}).filter(se=>{let pe=se.function?.name||se.name||"";return pe==="bash"||pe==="Bash"}).map(se=>{try{let pe=se.function?.arguments??se.input??{};return(typeof pe=="string"?JSON.parse(pe):pe)?.command||""}catch{return""}}),we=W.some(se=>/pip\s+install|python\s+-m\s+venv/.test(se)),F=W.some(se=>/npm\s+install/.test(se)),G=[...M].some(se=>/\/App\.(js|ts|jsx|tsx)$/.test(se))&&!P&&!F;if(D&&!we||P&&!ae&&!F||G){Vl=!0;let se=[];D&&!we&&se.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),G?se.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):P&&!ae&&!F&&se.push("npm install");let pe=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${se.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;K(`${$.dim} [post-creation] bootstrapping environment (${se.join(", ")})${$.reset}`),H.push({role:"user",content:pe}),O.push({role:"user",content:pe});continue}}if(A>0&&!n._isSummaryTurn&&US(gn))try{K(`${$.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${$.reset}`);let P=M.size>0?"Write a closing summary (3+ sentences): what files changed and why, what the result is, anything the user should know or do next.":"Write a closing diagnosis (3+ sentences): what you investigated, what you found, and what the user should do next or what the root cause is.",D=[...O,{role:"user",content:P}],W=((await Qh(D,[],{}))?.content||"").trim();W&&(console.log(`
|
|
1239
|
+
${W}`),H.push({role:"user",content:P},{role:"assistant",content:W}))}catch{}tt(H),Ol(H);return}A++,Sa++,A>=1&&(Le=!1);for(let _ of kn){let w=_.function.name;I.set(w,(I.get(w)||0)+1)}if(A>=30&&!ug){ug=!0,K(`${$.yellow} \u26A0 Tool budget warning: ${A} tool calls used \u2014 nudging model to wrap up${$.reset}`);let _={role:"user",content:"[SYSTEM] \u26A0 You have used "+A+" 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."};H.push(_),O.push(_)}let Ce=await Promise.all(kn.map(_=>Lk(_)));{let _=an(O,yt()),w=_.percentage,ce=Ce.some(W=>W.canExecute&&W.fnName==="read_file"&&!W.args?.line_end),P=Ce.filter(W=>W.canExecute&&W.fnName==="read_file"&&W.args?.path&&_n(Ds,W.args.path)>=1&&!W.args?.line_start).map(W=>W.args.path.split("/").slice(-2).join("/")),D=P.length>0;if(w>=70&&ce&&Ua<70||w>=85&&Ua<85||D){Ua=w;let W=w>=85?"URGENT":"WARNING",we;D?(W="WARNING",we=`Full-file read of ${P.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):ce?we=`Unbounded read at ${Math.round(w)}% context \u2014 use line_start/line_end to avoid overflow.`:we="Use targeted reads (line_start/line_end) to save space.";let F={role:"user",content:`[SYSTEM ${W}] Context ${Math.round(w)}% used (${_.used}/${_.limit} tokens). ${we}`};if(H.push(F),O.push(F),w>=85){let Y=D?` (re-read of: ${P.join(", ")})`:"";K(`${$.yellow} \u26A0 Context ${Math.round(w)}% used \u2014 agent warned to use targeted reads${Y}${$.reset}`)}}}let Ga=new Map;for(let _ of Ce){if(!_.canExecute||_.fnName!=="read_file")continue;let w=_.args?.path;if(!w)continue;let ce=_n(Ds,w),P=Ga.get(w)||0,D=ce+P,ae=_.args?.line_start!=null,W=Xt.get(w)||0,we=W>0,F=2;if(D>=qs){let Y=w.split("/").slice(-2).join("/"),G=(Ns.get(w)||0)+1;if(Ns.set(w,G),G===1)K(`${$.red} \u2716 Blocked: "${Y}" read ${D}\xD7 \u2014 hard cap (${qs}) reached${$.reset}`);else if(G===2){K(`${$.red} \u2716 Escalated block: "${Y}" \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let te={role:"user",content:`[SYSTEM WARNING] You already received a BLOCKED error for read_file("${w}") and tried again anyway. This file has reached its read cap (${qs}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};H.push(te),O.push(te)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${w}") denied \u2014 file already read ${D}\xD7 (hard cap: ${qs}). 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(D>=1&&ae)if(we&&W<=F){let Y=w.split("/").slice(-2).join("/");console.log(`${$.cyan} \u21A9 Targeted re-read: "${Y}" (line_start=${_.args.line_start}) \u2014 edit recovery #${W}${$.reset}`),Xt.set(w,W-1)}else if(we&&W>F){let Y=w.split("/").slice(-2).join("/");K(`${$.red} \u2716 Edit recovery blocked: "${Y}" \u2014 ${F} recovery reads already used. Use grep to find the exact line numbers, then retry.${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${w}") denied \u2014 edit recovery budget exhausted (${F} recovery reads used). You already have the file content. Use grep_search to find the exact line numbers of the text you want to change, then retry edit_file with the exact text shown.`,tool_call_id:_.callId}}else{let Y=_.args.line_start||1,G=_.args.line_end||Y+350,te=Pn.get(w)||[],se=!1;for(let[pe,ke]of te){let ue=Math.max(Y,pe),Xe=Math.min(G,ke);if(Xe>ue){let rt=Xe-ue,Kt=G-Y||1,Mt=ke-pe||1,En=rt/Mt>=.7&&rt/Kt<.7,ct=G-Y<=ny;if(rt>=Kt||!ct&&(rt/Kt>=.7||rt/Mt>=.7)){let Xa=w.split("/").slice(-2).join("/"),od=`${w}:${Y}-${G}`,Ws=(xa.get(od)||0)+1;if(xa.set(od,Ws),K(En?`${$.red} \u2716 Blocked superread: "${Xa}" lines ${Y}-${G} subsumes already-read ${pe}-${ke} \u2014 use line_start=${ke+1} to skip known content (block #${Ws})${$.reset}`:`${$.red} \u2716 Blocked duplicate read: "${Xa}" lines ${Y}-${G} (\u226570% overlap with lines ${pe}-${ke} already in context, block #${Ws})${$.reset}`),Ws>=2){K(`${$.red} \u2716 Escalated range-block: "${Xa}" lines ${Y}-${G} \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let rd={role:"user",content:En?`[SYSTEM] Read blocked ${Ws}\xD7 for read_file("${w}", lines ${Y}-${G}). Lines ${pe}-${ke} were already read. Use line_start=${ke+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Ws}\xD7 for read_file("${w}", lines ${Y}-${G}). Lines ${pe}-${ke} were already read and will NOT change. Use grep_search to find specific content instead.`};H.push(rd),O.push(rd)}_.canExecute=!1,_.errorResult={role:"tool",content:En?`BLOCKED: read_file("${w}", lines ${Y}-${G}) re-reads lines ${pe}-${ke} already in context. Use line_start=${ke+1} to read only the new content beyond line ${ke}.`:`BLOCKED: read_file("${w}", lines ${Y}-${G}) is a duplicate \u2014 lines ${pe}-${ke} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:_.callId},se=!0;break}}}if(!se){let pe=te.length,ke=2;if(pe>=3){let Xe=w.split("/").slice(-2).join("/");K(`${$.red} \u2716 Blocked file-scroll: "${Xe}" \u2014 ${pe} sections already read. Use grep to find specific content.${$.reset}`);let rt=_n(Qn,w)>=es;_.canExecute=!1,_.errorResult={role:"tool",content:rt?`BLOCKED: read_file("${w}") denied \u2014 you have already read ${pe} 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("${w}") denied \u2014 you have already read ${pe} 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 pe>=ke&&(_._scrollWarn={sectionCount:pe+1,path:w})}}else if(D>=1){let Y=Xt.get(w)||0;if(Y>0){let G=w.split("/").slice(-2).join("/");console.log(`${$.cyan} \u21A9 Full re-read: "${G}" \u2014 test-failure recovery (${Y} remaining)${$.reset}`);let te=Y-1;te<=0?Xt.delete(w):Xt.set(w,te)}else{let G=w.split("/").slice(-2).join("/"),te=(Ns.get(w)||0)+1;if(Ns.set(w,te),te===1)K(`${$.red} \u2716 Blocked unbounded re-read: "${G}" \u2014 already in context. Use line_start/line_end for specific sections.${$.reset}`);else if(te===2){K(`${$.red} \u2716 Escalated block: "${G}" \u2014 model ignored unbounded re-read block, injecting system warning${$.reset}`);let se={role:"user",content:`[SYSTEM] read_file("${w}") 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.`};H.push(se),O.push(se)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${w}") denied \u2014 file already in context (read ${D}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:_.callId}}}_.canExecute&&Ga.set(w,(Ga.get(w)||0)+1)}if(Yn>=3)for(let _ of Ce)_.canExecute&&(_.fnName!=="read_file"&&_.fnName!=="edit_file"||(K(`${$.red} \u2716 Blocked ${_.fnName} \u2014 ${Yn} consecutive file-not-found errors, must search first${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${Yn} 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 Ce){if(!_.canExecute||_.fnName!=="bash")continue;let w=(_.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(w)&&!/npm|yarn|pnpm|make|git/.test(w)){K(`${$.red} \u2716 Blocked bash ls \u2014 use list_directory tool instead${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:'BLOCKED: bash("ls ...") denied \u2014 use the list_directory tool instead. It returns structured output and does not penalize the session score.',tool_call_id:_.callId};continue}/\bfind\s+[\S.]/.test(w)&&!/git\s|npm\s|yarn\s|-exec\s+\S|-execdir/.test(w)&&(K(`${$.red} \u2716 Blocked bash find \u2014 use glob tool with a pattern instead${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:'BLOCKED: bash("find ...") denied \u2014 use the glob tool with a pattern like "**/*.py" or "src/**/*.js" instead. It is faster and does not penalize the session score.',tool_call_id:_.callId})}for(let _ of Ce)_.canExecute&&(_.fnName!=="ssh_exec"&&_.fnName!=="bash"||/\bsed\s+-n\b/.test(_.args?.command||"")&&(K(`${$.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:'BLOCKED: sed -n is forbidden \u2014 it floods context with line ranges. Use grep -n "pattern" <file> | head -30 to read a specific section, or cat <file> for the full file.',tool_call_id:_.callId}));for(let _ of Ce){if(!_.canExecute||_.fnName!=="write_file")continue;let w=_.args?.path,ce=_.args?.content||"";if(w)try{let P=require("fs"),D=require("path").resolve(process.cwd(),w);if(P.existsSync(D)){let ae=P.statSync(D).size,W=Buffer.byteLength(ce,"utf8"),we=ae>0?W/ae:1;if(we<.6&&ae>200){let F=w.split("/").slice(-2).join("/");console.log(`${$.red} \u2716 write_file shrink guard: "${F}" would shrink to ${Math.round(we*100)}% of original \u2014 likely context loss${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: write_file("${w}") denied \u2014 new content is only ${Math.round(we*100)}% of current file size (${ae} \u2192 ${W} 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 ed=new Map;for(let _ of Ce){if(!_.canExecute||_.fnName!=="grep")continue;let w=_.args?.path;if(!w)continue;let ce=ed.get(w)||0,P=_n(Qn,w)+ce,D=_n(Ds,w)>=1,ae=D?Math.min(3,es):es;if(P>=ae){let W=w.split("/").slice(-2).join("/");K(`${$.red} \u2716 Blocked grep: "${W}" grepped ${P}\xD7 with different patterns \u2014 flood threshold exceeded${$.reset}`);let we=_n(Ds,w),F=we>=qs;if(F){let Y={role:"user",content:`[SYSTEM] Both read_file and grep are now blocked for "${w}". You have already read ${we} sections and tried ${P} grep patterns. Do NOT attempt to read or grep this file again. The content you need is already in your conversation context \u2014 scroll back to find it, or proceed with what you know.`};H.push(Y),O.push(Y),K(`${$.red} \u2716 Deadlock detected: "${W}" \u2014 both read and grep blocked, injecting deadlock-break${$.reset}`)}_.canExecute=!1,_.errorResult={role:"tool",content:F?`BLOCKED: grep("${w}") denied \u2014 ${P} patterns already tried AND reads are also exhausted. The content is already in your context. Do not attempt to read or grep this file again.`:D?`BLOCKED: grep("${w}") denied \u2014 file was already read and ${P} grep patterns tried. The content is already in your context; use it instead of searching again.`:`BLOCKED: grep("${w}") denied \u2014 ${P} patterns already tried. Work with the grep results already in your context.`,tool_call_id:_.callId}}_.canExecute&&ed.set(w,ce+1)}let cy=5,td=new Map;for(let _ of Ce){if(!_.canExecute||_.fnName!=="ssh_exec")continue;let ce=(_.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),P=td.get(ce)||0,D=_n(xe,ce)+P;D>=cy&&(K(`${$.yellow} \u26A0 Blocked ssh_exec: same command run ${D}\xD7 \u2014 result already in context${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${D} 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&&td.set(ce,P+1)}if(qt){let _=Ce.filter(P=>P.canExecute&&P.fnName==="ssh_exec"),w=Ce.some(P=>P.canExecute&&P.fnName!=="ssh_exec"),ce=v&&j<3;if(_.length>0&&!w&&ce&&ha<1)qt=!1,ha++,Vt=Math.max(0,Ao-2),K(`${$.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${ha}/1)]${$.reset}`);else for(let P of _)P.canExecute=!1,P.errorResult={role:"tool",content:ut?`BLOCKED: ssh_exec denied \u2014 SSH paused (${Ao}+ calls). Root cause is known (${At}). Edit the file now. You can still use bash("ssh user@host 'cmd'") for a single targeted lookup if essential.`:`BLOCKED: ssh_exec denied \u2014 SSH temporarily paused (${Ao}+ calls). Provide a text summary of your findings first. Do NOT ask the user to run commands. SSH re-enables after your summary. For one-off lookups use bash("ssh user@host 'cmd'") instead.`,tool_call_id:P.callId}}if(v&&j<3&&!qt){for(let _ of Ce)if(_.canExecute&&["bash","read_file","find_files"].includes(_.fnName)){j++;{let w=yt(),{messages:ce}=bn(O,w);O=ce}K(`${$.yellow} \u26A0 Server-local guard: blocking local ${_.fnName} \u2014 use ssh_exec on 94.130.37.43${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${_.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:_.callId};break}}if(!Oe&&cn&&Jt&&ln>=1){let _=["read_file","grep","search_files","glob","list_directory","find_files"];for(let w of Ce)w.canExecute&&_.includes(w.fnName)&&(K(`${$.red} \u2716 Creation hard-block: ${w.fnName} denied \u2014 cap fired, files already written${$.reset}`),w.canExecute=!1,w.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:w.callId})}if(Cs>=0){let _=Ce.filter(w=>w.canExecute).length;if(_>0&&(Cs-=_,Cs<0))if(!$a&&M.size>ga){$a=!0,Cs=5,K(`${$.green} \u2713 Post-wipe progress detected (${M.size-ga} files modified) \u2014 granting 5 bonus tool calls${$.reset}`);let w={role:"user",content:"[SYSTEM] Progress detected \u2014 5 bonus tool calls granted. Budget: 5 remaining."};H.push(w),O.push(w)}else{K(`${$.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${$.reset}`);for(let ce of Ce)ce.canExecute&&(ce.canExecute=!1,ce.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:ce.callId});let w={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."};H.push(w),O.push(w)}}let ly=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 Ce){if(!_.canExecute||ly.has(_.fnName))continue;let w=JSON.stringify(_.args||{}),ce=`${_.fnName}|${w}`,P=_n(va,ce);P>=2?(K(`${$.red} \u2716 Blocked duplicate: ${_.fnName}(${w.substring(0,80)}) \u2014 called ${P+1}\xD7 with identical args${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${_.fnName}() with these exact arguments has already been called ${P}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:_.callId}):P===1&&K(`${$.yellow} \u26A0 Duplicate tool call: ${_.fnName}(${w.substring(0,80)}) \u2014 2nd call with identical args${$.reset}`),Rs(va,ce)}let Oo=u?{skipSpinner:!0,skipSummaries:!0}:{},uy=Ce.some(_=>_.fnName==="ask_user"),nd=!Oo.skipSummaries&&!Le,Vr=null,Bs=null;nd&&!uy?(Le=!0,Oo.skipSpinner=!0,process.stdout.isTTY?(global._nexFooter&&(Bs=Math.min(global._nexFooter._lastOutputRow+1,global._nexFooter._scrollEnd)),process.stdout.write(ca(Ce,A,!1,"blink")),Vr=!0):vn||process.stdout.write(ca(Ce,A,!1)+`
|
|
1240
|
+
`)):nd&&(Le=!0,Oo.skipSpinner=!0),u&&u._paused&&u.resume();let Jr=null;if(Vr&&process.stdout.isTTY&&Ce.some(w=>w.canExecute&&(w.fnName==="bash"||w.fnName==="ssh_exec"))){let w=Date.now();Jr=setInterval(()=>{let ce=Math.round((Date.now()-w)/1e3);if(ce>=3){let P=`${ca(Ce,A,!1,"blink")} ${$.dim}[${ce}s]${$.reset}`;Bs!==null?process.stdout.write(`\x1B[${Bs};1H\x1B[2K${P}`):process.stdout.write(`\r\x1B[2K${P}`)}},1e3)}let{results:ht,summaries:dy}=await qk(Ce,!0,{...Oo,skipSummaries:!0});if(Jr&&(clearInterval(Jr),Jr=null),Vr){Vr=null;let _=ca(Ce,A,!1);Bs!==null?process.stdout.write(`\x1B[${Bs};1H\x1B[2K${_}
|
|
1237
1241
|
`):process.stdout.write(`\r\x1B[2K${_}
|
|
1238
|
-
`),
|
|
1239
|
-
`)[0],D=!P.startsWith("ERROR")&&!P.startsWith("CANCELLED")&&!P.startsWith("Command failed")&&!P.startsWith("EXIT");if(!D&&(
|
|
1240
|
-
`).map(
|
|
1241
|
-
`).map(
|
|
1242
|
-
...(truncated ${D-W} chars \u2014 per-message budget)`},
|
|
1243
|
-
${$.yellow}\u26A0 Max iterations reached.${$.reset}`),await
|
|
1244
|
-
`),await t(c,i,d)}catch(u){if(n=u,!
|
|
1245
|
-
`),await t(c,i,f)}catch(p){if(n=p,!
|
|
1242
|
+
`),Bs=null}if(!Oo.skipSummaries){let _=dy.filter((P,D)=>!(Ce[D]&&Ce[D].fnName==="ask_user"));for(let P of _)console.log(P);let w=Ce.filter(P=>P&&P.fnName!=="ask_user").map(P=>P.fnName),ce=J.record(0,w,N,M);ce&&gk(ce)}for(let _ of Ce){if(_.canExecute||!_.errorResult)continue;let w=typeof _.errorResult.content=="string"?_.errorResult.content:"";if((w.startsWith("BLOCKED:")||w.startsWith("PLAN MODE:")||w.startsWith("PLAN PHASE:"))&&(ns++,ns>=zu)){K(`${$.red} \u2716 Loop abort: ${ns} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T,{suppressHint:!0}),tt(H);return}}for(let _=0;_<Ce.length;_++){let w=Ce[_];if(!w.canExecute)continue;let ce=ht[_].content,P=ce.split(`
|
|
1243
|
+
`)[0],D=!P.startsWith("ERROR")&&!P.startsWith("CANCELLED")&&!P.startsWith("Command failed")&&!P.startsWith("EXIT");if(!D&&(w.fnName==="edit_file"||w.fnName==="patch_file")&&w.args?.path&&P.includes("old_text not found")){let F=Xt.get(w.args.path)||0;Xt.set(w.args.path,F+1)}if(!D&&w.fnName==="bash"&&Cr.size>0){let F=(w.args?.command||"").toLowerCase();if(/\b(test|jest|vitest|pytest|mocha|tsc|build|lint|eslint|check)\b/.test(F))for(let[G]of Cr)Xt.has(G)||(Xt.set(G,1),K(`${$.cyan} \u21A9 Test failure \u2014 queuing recovery re-read: "${G.split("/").pop()}"${$.reset}`))}if(!D&&(w.fnName==="read_file"||w.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(P)){if(Yn++,Yn>=2){K(`${$.yellow} \u26A0 File-not-found streak: ${Yn} consecutive misses \u2014 forcing search${$.reset}`);let F={role:"user",content:`[SYSTEM] ${Yn} 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.`};H.push(F),O.push(F)}}else D&&(w.fnName==="read_file"||w.fnName==="edit_file"||w.fnName==="search_files"||w.fnName==="glob_files")&&(Yn=0);if(D&&w.fnName==="write_file"&&w.args?.path){let F=w.args.path.split("/").pop(),Y=w.args.path.includes("/tests/")||w.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(F)&&!Y){K(`${$.yellow} \u26A0 Temp file: "${F}" \u2014 delete with bash rm when done to keep the workspace clean${$.reset}`);let te={role:"user",content:`[HINT] "${w.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${w.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};H.push(te),O.push(te)}}if(D&&["write_file","edit_file","patch_file"].includes(w.fnName)&&w.args&&w.args.path){Xt.delete(w.args.path),M.add(w.args.path);let F=Rs(ee,w.args.path),Y=w.args.path.split("/").slice(-2).join("/");if(F===ge){K(`${$.yellow} \u26A0 Loop warning: "${Y}" edited ${F}\xD7 \u2014 possible edit loop${$.reset}`);let G={role:"user",content:`[SYSTEM WARNING] "${w.args.path}" edited ${F}\xD7. One more edit max, then move on.`};H.push(G),O.push(G)}else if(F>=Se){K(`${$.red} \u2716 Loop abort: "${Y}" edited ${F}\xD7 \u2014 aborting to prevent runaway loop${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T,{suppressHint:!0}),tt(H);return}}if(D&&w.canExecute&&Oe&&(zn=0),D&&w.canExecute&&!(Oe&&Je==="plan")){let F=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];if(["write_file","edit_file","patch_file"].includes(w.fnName)){xn=0,cn=!1,Ln=0,ln++;let ue=w.args?.path||w.args?.file_path;ue&&(Fl(Gn,ue,1),Pn.delete(ue))}else F.includes(w.fnName)&&(xn++,cn&&Ln++);let G=s.postEditCap,te=Oe&&Je==="implement"?Math.min(Xu,6):Xu,se=ut?3:Jt?ln>0?2:4:ln>0?G:te,pe=3;if(!Oe&&cn&&(ut||Jt&&ln>=1||Ln>=pe)&&F.includes(w.fnName)){let ue=ut?`root cause already identified (${At})`:Ln>=pe?`${xn} consecutive reads without an edit`:`${ln} file edit(s) already made`;K(`${$.red} \u2716 Blocked read-only tool: cap fired, ${ue}${$.reset}`),w.canExecute=!1,w.errorResult={role:"tool",content:ut?`BLOCKED: root cause already identified (${At}). Use edit_file to fix the issue \u2014 do not read more files.`:Jt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":Ln>=pe?`BLOCKED: You have read ${xn} 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: ${ln} 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:w.callId}}else if(xn>=se&&!cn){if(cn=!0,K(`${$.yellow} \u26A0 Investigation cap: ${xn} read-only calls without an edit \u2014 forcing implementation${$.reset}`),Oe&&Je==="plan"){let rt=[...O].reverse().find(En=>En.role==="assistant"),Kt=typeof rt?.content=="string"?rt.content:"",Mt=wr("implement",Kt);Mt&&(H.push(Mt),O.push(Mt),ot=0,mn=Ts("implement"))}let ue;ut?ue=`[SYSTEM] Root cause was already identified (${At}). Edit the file now \u2014 do not read more files.`:qt?ue="[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.":ue="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let Xe={role:"user",content:ue};H.push(Xe),O.push(Xe)}}if((w.fnName==="bash"||w.fnName==="ssh_exec")&&w.args&&w.args.command){let F=w.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),Y=Rs(xe,F);if(Y===Ne){K(`${$.yellow} \u26A0 Loop warning: same bash command run ${Y}\xD7 \u2014 possible debug loop${$.reset}`);let G={role:"user",content:`[SYSTEM WARNING] Same bash command ${Y}\xD7. Debug loop detected \u2014 try a different approach.`};H.push(G),O.push(G)}else if(Y>=Ue){K(`${$.red} \u2716 Loop abort: same bash command run ${Y}\xD7 \u2014 aborting runaway debug loop${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T,{suppressHint:!0}),tt(H);return}}if(w.fnName==="ssh_exec"){Vt++;{let G=(ht[_]?.content??"").split(`
|
|
1244
|
+
`).map(te=>te.trim()).find(te=>te.length>0&&!te.startsWith("**")&&(te.startsWith("EXIT")||/^[\w./-]+:\s/.test(te)||te.startsWith("bash:")||te.startsWith("sh:")))??"";if(G){if(G===ya?As++:(ya=G,As=1),As===3&&!qt){K(`${$.yellow} \u26A0 SSH repeated-error: "${G.slice(0,60)}" returned ${As}\xD7 \u2014 nudging to change approach${$.reset}`);let te={role:"user",content:`[SYSTEM WARNING] The last ${As} SSH commands all failed with the same error: "${G}". 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).`};H.push(te),O.push(te)}}else ya="",As=0}if(Vt>=ay){K(`${$.red} \u2716 SSH storm abort: ${Vt} consecutive ssh_exec calls \u2014 aborting${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T,{suppressHint:!0}),tt(H);return}else if(Vt===Ao){{let G=yt(),{messages:te}=bn(O,G);O=te}qt=!0,ua++,K(`${$.yellow} \u26A0 SSH storm warning (#${ua}): ${Vt} consecutive ssh_exec calls \u2014 blocking further SSH${$.reset}`);let Y={role:"user",content:ut?`[SYSTEM WARNING] ${Vt} consecutive SSH calls. Root cause identified (${At}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Vt} 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.`};H.push(Y),O.push(Y)}}else w.canExecute&&(Vt=0);if(w.fnName==="bash"&&w.canExecute){let G=(ht[_]?.content??"").split(`
|
|
1245
|
+
`).map(te=>te.trim()).find(te=>te.length>0&&(te.startsWith("EXIT")||/^[\w./-]+:\s/.test(te)||te.startsWith("bash:")||te.startsWith("sh:")))??"";if(G){if(G===wa?Os++:(wa=G,Os=1),Os===3){K(`${$.yellow} \u26A0 Bash repeated-error: "${G.slice(0,60)}" returned ${Os}\xD7 \u2014 nudging to change approach${$.reset}`);let te={role:"user",content:`[SYSTEM WARNING] The last ${Os} bash commands all failed with the same error: "${G}". 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).`};H.push(te),O.push(te)}}else wa="",Os=0}if(w.fnName==="bash"&&w.canExecute&&!Ul&&w.args?.command){let F=ht[_]?.content??"";if(/git\s+commit\b/.test(w.args.command)&&!F.startsWith("EXIT")&&!F.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(F)||F.includes("files changed")||F.includes("file changed")||F.includes("insertions(+)")||F.includes("create mode"))){Ul=!0,yr=0,K(`${$.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${$.reset}`);let te={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."};H.push(te),O.push(te)}}if(Ul&&w.fnName==="bash"&&w.args?.command&&/git\s+(status|diff|log|show)\b/.test(w.args.command)&&(yr++,yr>2)){K(`${$.yellow} \u26A0 Post-commit git verification blocked (call ${yr})${$.reset}`);let Y={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(yr-1)+" git verification commands after committing. The commit is confirmed. Write your final summary NOW and do not make any more tool calls."};H.push(Y),O.push(Y)}if(D&&w.fnName==="grep"&&w.args&&w.args.pattern){let F=`${w.args.pattern}|${w.args.path||""}`,Y=Rs(bt,F);if(Y===qe){K(`${$.yellow} \u26A0 Loop warning: grep pattern "${w.args.pattern.slice(0,40)}" run ${Y}\xD7 \u2014 possible search loop${$.reset}`);let G={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${Y}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};H.push(G),O.push(G)}else if(Y>=Wt){K(`${$.red} \u2716 Loop abort: grep pattern run ${Y}\xD7 \u2014 aborting runaway search loop${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T,{suppressHint:!0}),tt(H);return}if(w.args.path){let G=Rs(Qn,w.args.path),te=_n(Ds,w.args.path)>=1;if(G===(te?1:Co)){let pe=w.args.path.split("/").slice(-2).join("/");K(`${$.yellow} \u26A0 Loop warning: "${pe}" grepped ${G}\xD7 with different patterns \u2014 context flood risk${$.reset}`);let ke={role:"user",content:te?`[SYSTEM NOTE] "${w.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] "${w.args.path}" grepped ${G}\xD7 \u2014 use the search results already in context instead of searching again.`};H.push(ke),O.push(ke)}}}if(D&&(w.fnName==="glob"||w.fnName==="glob_files"||w.fnName==="search_files")&&w.args){let F=w.args.pattern||w.args.query||w.args.path||"",Y=Rs(Is,F);if(Y===Kr){K(`${$.yellow} \u26A0 Loop warning: glob pattern "${F.slice(0,40)}" run ${Y}\xD7 \u2014 possible search loop${$.reset}`);let te={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${Y}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};H.push(te),O.push(te)}else if(Y>=js){K(`${$.red} \u2716 Loop abort: glob pattern run ${Y}\xD7 \u2014 aborting runaway search loop${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T,{suppressHint:!0}),tt(H);return}let G=F.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(te=>te.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(te));for(let te of G){let se=te.toLowerCase();Rr.has(se)||Rr.set(se,new Set);let pe=Rr.get(se);if(pe.add(F),pe.size===Q$){K(`${$.red} \u2716 Glob core-term block: ${pe.size} different patterns all searching for "${se}" \u2014 search loop${$.reset}`);let ke={role:"user",content:`[SYSTEM WARNING] You have searched for "${se}" using ${pe.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.`};H.push(ke),O.push(ke)}else if(pe.size===Fa){K(`${$.yellow} \u26A0 Glob core-term warning: ${pe.size} different patterns searching for "${se}"${$.reset}`);let ke={role:"user",content:`[SYSTEM WARNING] ${pe.size} different glob patterns all target "${se}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};H.push(ke),O.push(ke)}}}let ae=(w.args?.command||w.args?.cmd||w.args?.script||"").toLowerCase(),W=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(ae)||/\/(health|status|ping|ready|alive)\b/.test(ae);if(D&&(w.fnName==="bash"||w.fnName==="ssh_exec")&&W&&ce.includes('"valid":true')){{let Y=yt();if(an(O,Y).percentage>=60){let{messages:te,tokensRemoved:se}=bn(O,Y);se>0&&(O=te,console.log(`${$.dim} [pre-stop-compress \u2014 ~${se} tokens freed before STOP injection, now ${Math.round(an(O,Y).percentage)}%]${$.reset}`))}}let F={role:"user",content:'[SYSTEM STOP] Tool result contains {"valid":true}. The token/service is valid and reachable. STOP all further investigation immediately. Report to the user that the token is valid, the service is healthy, and no fix is needed. Do NOT read any more log files.'};H.push(F),O.push(F),console.log(`${$.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${$.reset}`)}if(ce.startsWith("BLOCKED:")){if(ns++,ns>=zu){K(`${$.red} \u2716 Loop abort: ${ns} consecutive blocked calls \u2014 model not heeding BLOCKED messages${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T,{suppressHint:!0}),tt(H);return}}else ns=0;if(D)ts=0,Wa=!0;else if(ts++,ts===sy){K(`${$.yellow} \u26A0 Loop warning: ${ts} consecutive tool errors \u2014 possible stuck loop${$.reset}`);let F={role:"user",content:`[SYSTEM WARNING] ${ts} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};H.push(F),O.push(F)}else if(ts>=oy){K(`${$.red} \u2716 Loop abort: ${ts} consecutive errors \u2014 aborting stuck loop${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T,{suppressHint:!0}),tt(H);return}if(D&&w.fnName==="read_file"&&w.args&&w.args.path){N.add(w.args.path);let F=Rs(Ds,w.args.path);{let se=w.args.line_start!=null&&w.args.line_start||1,pe=w.args.line_start!=null?w.args.line_end||se+350:350;Pn.has(w.args.path)||Pn.set(w.args.path,[]),Pn.get(w.args.path).push([se,pe])}if(w._scrollWarn){let{sectionCount:se,path:pe}=w._scrollWarn,ke={role:"user",content:`[SYSTEM WARNING] "${pe}" \u2014 you have now read ${se} 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.`};H.push(ke),O.push(ke),K(`${$.yellow} \u26A0 Scroll warning: "${pe.split("/").slice(-2).join("/")}" \u2014 ${se} sections read \u2014 use grep instead${$.reset}`)}let Y=w.args.path.split("/").slice(-2).join("/"),G=!w.args?.line_start&&!w.args?.line_end,te=Oe&&Je==="plan";if(!te&&G&&F===ey){{let pe=yt();if(an(O,pe).percentage>=60){let{messages:ue}=bn(O,pe);O=ue}}K(`${$.yellow} \u26A0 Loop warning: "${Y}" read unbounded ${F}\xD7 \u2014 use line_start/line_end${$.reset}`);let se={role:"user",content:`[SYSTEM WARNING] "${w.args.path}" read ${F}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};H.push(se),O.push(se)}else if(!te&&G&&F>=ty){K(`${$.red} \u2716 Loop abort: "${Y}" read unbounded ${F}\xD7 \u2014 aborting runaway read loop${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T,{suppressHint:!0}),tt(H);return}}if(w.fnName==="spawn_agents"){let F=(ce.match(/\bStatus: done\b/g)||[]).length;if((ce.match(/\bStatus: truncated\b/g)||[]).length>0&&F===0){if(ss++,ss===ry){K(`${$.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${ss}\xD7 in a row${$.reset}`);let G={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${ss}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};H.push(G),O.push(G)}else if(ss>=iy){console.log(`${$.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${ss}\xD7 \u2014 aborting stuck swarm${$.reset}`),u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T,{suppressHint:!0}),tt(H);return}}else F>0&&(ss=0)}}{let w=ht.reduce((ce,P)=>ce+(typeof P.content=="string"?P.content.length:0),0);if(w>2e5){let ce=ht.map((P,D)=>({i:D,len:typeof P.content=="string"?P.content.length:0})).sort((P,D)=>D.len-P.len);for(let{i:P,len:D}of ce){if(w<=2e5)break;let ae=w-2e5,W=Math.max(D-ae,500);W<D&&typeof ht[P].content=="string"&&(ht[P]={...ht[P],content:ht[P].content.substring(0,W)+`
|
|
1246
|
+
...(truncated ${D-W} chars \u2014 per-message budget)`},w-=D-W)}}}for(let _ of ht)H.push(_),O.push(_);if(!ut)for(let _=0;_<ht.length;_++){if(!Ce[_]||Ce[_].fnName!=="ssh_exec")continue;let w=ht[_];if(!w||typeof w.content!="string")continue;let ce=ql(w.content);if(ce){ut=!0,At=ce.slice(0,120),xn=0,cn=!1,Ln=0,K(`${$.yellow} \u26A1 Root cause detected: ${At} \u2014 fix phase (read budget: 3)${$.reset}`);let P={role:"user",content:`[SYSTEM] Root cause identified: ${At}. Read only the file that needs fixing, then edit it. Do not read other files.`};H.push(P),O.push(P);break}}for(let _=0;_<ht.length;_++){let w=Ce[_];if(!w)continue;let ce=typeof ht[_]?.content=="string"?ht[_].content:"";if(w.fnName==="create_task"){let P=ce.match(/Task #(\d+) created/),D=typeof w.args?.subject=="string"?w.args.subject:"";P&&D&&Ar.set(P[1],D)}else if((w.fnName==="write_file"||w.fnName==="edit_file")&&!ce.startsWith("BLOCKED:")&&ce.trim().length>0){let D=(typeof w.args?.path=="string"?w.args.path:typeof w.args?.file_path=="string"?w.args.file_path:"").split("/").pop().toLowerCase(),ae=D.split(/[._\-/]/).filter(W=>W.length>2);for(let[W,we]of Ar){if(Or.has(W))continue;let F=we.toLowerCase().split(/\W+/).filter(G=>G.length>3);ae.filter(G=>F.some(te=>te.includes(G)||G.includes(te))).length>=1&&(Or.add(W),K(`${$.green} \u2714 Auto-matched task #${W} to ${D}: ${we.slice(0,60)}${$.reset}`))}}}{let _=yt();if(an(O,_).percentage>=78){let{messages:ce,tokensRemoved:P}=bn(O,_);P>0&&(O=ce,console.log(`${$.dim} [auto-compressed \u2014 ~${P} tokens freed, now ${Math.round(an(O,_).percentage)}%]${$.reset}`))}}let sd=Uk();if(sd){let _={role:"user",content:`[User note mid-run]: ${sd}`};H.push(_),O.push(_),console.log(`${$.cyan} \u270E Context added${$.reset}`)}}if(ot>=mn){if(u&&(u.stop(),u=null),l(null),nt(A,I,M,N,T),tt(H),Ol(H),Oe&&Je==="plan"){let Fs=[...H].reverse().find(mt=>mt.role==="assistant"),Nt=typeof Fs?.content=="string"?Fs.content:"",Us=wr("implement",Nt);if(Us){H.push(Us),O=[{role:"system",content:await eu()},...H],mn=Ts("implement"),K(`${$.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${$.reset}`);continue e}}else if(Oe&&Je==="verify"){K(`${$.yellow} \u26A0 Verify budget exhausted \u2014 completing session${$.reset}`);break e}let{getActiveProviderName:Me}=Be();if(Me()==="ollama"&&Ba<Vu){if(M.size===0&&!Wa){console.log(`${$.yellow} \u26A0 Max iterations reached with no progress. Stopping.${$.reset}`);break e}Ba++,mn=20,console.log(`${$.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Ba}/${Vu}) \u2500\u2500${$.reset}`);continue e}if(console.log(`
|
|
1247
|
+
${$.yellow}\u26A0 Max iterations reached.${$.reset}`),await dg(" Continue for 20 more turns?")){mn=20;continue e}console.log(`${$.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${$.reset}`)}break e}}wg.exports={processInput:Qk,clearConversation:Kk,getConversationLength:Gk,getConversationMessages:zk,setConversationMessages:Xk,setAbortSignalGetter:xk,setMaxIterations:_k,invalidateSystemPromptCache:Gl,clearToolFilterCache:Ak,getCachedFilteredTools:hg,buildSystemPrompt:eu,splitSystemPrompt:Hk,SYSTEM_PROMPT_DYNAMIC_BOUNDARY:Ql,getProjectContextHash:gg,buildUserContent:pg,detectFrustration:mg,detectAndTruncateLoop:Hl,injectMidRunNote:Fk,resetSessionTracking:yg}});var Be=oe((ZR,Sg)=>{var{OllamaProvider:eE}=Ld(),{OpenAIProvider:tE}=qd(),{AnthropicProvider:nE}=Wd(),{GeminiProvider:sE}=Gd(),{LocalProvider:oE}=Vd(),{checkBudget:rE}=Qs(),cu={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"}},iu=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),_g={};for(let[t,e]of Object.entries(cu))for(let n of Object.values(e))_g[n]=t;function au(t,e){let n=_g[t];return n&&cu[n][e]||t}var dt={},Ot=null,st=null,Nr=[];function Zt(){if(Object.keys(dt).length>0)return;vo("ollama",new eE),vo("openai",new tE),vo("anthropic",new nE),vo("gemini",new sE),vo("local",new oE);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;dt[t]?(Ot=t,st=e||dt[t].defaultModel):(Ot="ollama",st="kimi-k2.5");let n=process.env.FALLBACK_CHAIN;n&&(Nr=n.split(",").map(s=>s.trim()).filter(Boolean))}function vo(t,e){dt[t]=e}function iE(t){return Zt(),dt[t]||null}function lu(){return Zt(),dt[Ot]||null}function aE(){return Zt(),Ot}function cE(){return Zt(),st}function lE(){Zt();let t=lu();if(!t)return{id:st,name:st,provider:Ot};let e=t.getModel(st);return e?{...e,provider:Ot}:{id:st,name:st,provider:Ot}}function xg(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(dt[n]||["ollama","openai","anthropic","gemini","local"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function uE(t){Zt();let{provider:e,model:n}=xg(t);if(e){let o=dt[e];return o&&(o.getModel(n)||e==="local"||e==="ollama")?(Ot=e,st=n,ka(),!0):!1}let s=lu();if(s&&s.getModel(n))return st=n,ka(),!0;for(let[o,r]of Object.entries(dt))if(r.getModel(n))return Ot=o,st=n,ka(),!0;return!1}function ka(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Ee();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Lt();t()}catch{}}function dE(){Zt();let t=new Set;for(let e of Object.values(dt))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function fE(){return Zt(),Object.entries(dt).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===Ot&&n.id===st}))}))}function pE(){Zt();let t=[];for(let[e,n]of Object.entries(dt)){let s=n.isConfigured();for(let o of Object.values(n.getModels()))t.push({spec:`${e}:${o.id}`,name:o.name,provider:e,configured:s})}return t}function mE(t){Nr=Array.isArray(t)?t:[]}function hE(){return[...Nr]}function bg(t){let e=t.message||"",n=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||n==="ECONNABORTED"||n==="ETIMEDOUT"||n==="ECONNREFUSED"||n==="ECONNRESET"||n==="EHOSTUNREACH"||n==="ENETUNREACH"||n==="EPIPE"||n==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function vg(t){let e=[Ot,...Nr.filter(r=>r!==Ot)],n,s=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],c=dt[i];if(!c||!c.isConfigured())continue;o++;let l=rE(i);if(!l.allowed){s++,n=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?au(st,i):st;return u&&d!==st&&process.stderr.write(` [fallback: ${i}:${d}]
|
|
1248
|
+
`),await t(c,i,d)}catch(u){if(n=u,!bg(u)||r>=e.length-1)throw u;if(i==="ollama"&&iu.length>0){let d=isFallback?au(st,i):st;for(let f of iu)if(f!==d)try{return process.stderr.write(` [ollama fallback: ${f}]
|
|
1249
|
+
`),await t(c,i,f)}catch(p){if(n=p,!bg(p))throw p}}continue}}throw s>0&&s===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):n||new Error("No configured provider available")}async function gE(t,e,n={}){return Zt(),vg((s,o,r)=>s.stream(t,e,{model:r,signal:n.signal,...n}))}async function $E(t,e,n={}){if(Zt(),n.provider){let s=dt[n.provider];if(!s||!s.isConfigured())throw new Error(`Provider '${n.provider}' is not available`);let o={model:n.model||st,...n};try{return await s.chat(t,e,o)}catch(r){if(typeof s.stream=="function")try{return await s.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return vg(async(s,o,r)=>{try{return await s.chat(t,e,{model:r,...n})}catch(i){if(typeof s.stream=="function")try{return await s.stream(t,e,{model:r,...n,onToken:()=>{}})}catch{}throw i}})}function yE(){Zt();let t=[];for(let[e,n]of Object.entries(dt))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function wE(){for(let t of Object.keys(dt))delete dt[t];Ot=null,st=null,Nr=[]}Sg.exports={registerProvider:vo,getProvider:iE,getActiveProvider:lu,getActiveProviderName:aE,getActiveModelId:cE,getActiveModel:lE,setActiveModel:uE,getModelNames:dE,parseModelSpec:xg,listProviders:fE,listAllModels:pE,callStream:gE,callChat:$E,getConfiguredProviders:yE,setFallbackChain:mE,getFallbackChain:hE,resolveModelForProvider:au,MODEL_EQUIVALENTS:cu,OLLAMA_FALLBACK_MODELS:iu,_reset:wE}});var uu=oe((QR,kg)=>{"use strict";var jn=require("fs"),Ea=require("path"),bE=require("readline"),Ae="\x1B[0m",Mr="\x1B[1m",wt="\x1B[2m",Ta="\x1B[33m",Ir="\x1B[36m",Pr="\x1B[32m";function _E(t){return(e,n="")=>new Promise(s=>{let o=n?` ${wt}[${n}]${Ae}`:"";t.question(` ${Ir}${e}${o}${Ae}: `,r=>s(r.trim()||n))})}function Lr(t,e){return new Promise(n=>{e&&e.pause(),process.stdout.write(` ${Ir}${t}${Ae}: `);let s=process.stdin,o=s.isRaw,r="";s.setRawMode(!0),s.resume(),s.setEncoding("utf8");let i=c=>{c==="\r"||c===`
|
|
1246
1250
|
`?(s.setRawMode(o||!1),s.removeListener("data",i),process.stdout.write(`
|
|
1247
1251
|
`),e&&e.resume(),n(r)):c===""?(process.stdout.write(`
|
|
1248
|
-
`),process.exit(0)):c==="\x7F"?r.length>0&&(r=r.slice(0,-1),process.stdout.write("\b \b")):(r+=c,process.stdout.write("*"))};s.on("data",i)})}async function
|
|
1249
|
-
`),console.log(` ${
|
|
1250
|
-
`),console.log(` ${
|
|
1251
|
-
${
|
|
1252
|
+
`),process.exit(0)):c==="\x7F"?r.length>0&&(r=r.slice(0,-1),process.stdout.write("\b \b")):(r+=c,process.stdout.write("*"))};s.on("data",i)})}async function xE({rl:t=null,force:e=!1}={}){if(!e){let p=jn.existsSync(Ea.join(process.cwd(),".env"))||jn.existsSync(Ea.join(__dirname,"..",".env")),g=process.env.ANTHROPIC_API_KEY||process.env.OPENAI_API_KEY||process.env.GEMINI_API_KEY||process.env.OPENROUTER_API_KEY,m=process.env.DEFAULT_PROVIDER||process.env.DEFAULT_MODEL;if(p||g||m)return}let n=!t,s=t||bE.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),o=_E(s),r=!e;console.log(),console.log(r?`${Ta}${Mr} \u2726 Welcome to nex-code! No configuration found.${Ae}`:`${Ir}${Mr} \u2726 nex-code \u2014 Provider & API Key Setup${Ae}`),console.log(`${wt} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${Ae}`),r&&console.log(` Let's set you up in 60 seconds.
|
|
1253
|
+
`),console.log(` ${Mr}Which AI provider do you want to use?${Ae}
|
|
1254
|
+
`),console.log(` ${Pr}1)${Ae} ${Mr}Ollama Cloud${Ae} ${wt}recommended \u2014 devstral-2:123b, no API key needed${Ae}`),console.log(` ${wt} (also works with a local Ollama server)${Ae}`),console.log(` ${wt}2) Anthropic Claude (claude-sonnet-4-6 etc.)${Ae}`),console.log(` ${wt}3) OpenAI GPT-4o, GPT-4.1 etc.${Ae}`),console.log(` ${wt}4) Gemini Google Gemini 2.x${Ae}`),console.log(` ${wt}5) Skip / Cancel${Ae}`),console.log();let i=await o("Enter number","1"),c=[];if(i==="5"){n&&s.close(),console.log(`
|
|
1255
|
+
${wt} Cancelled \u2014 no changes made.${Ae}
|
|
1252
1256
|
`);return}if(i==="1"){console.log(),console.log(`
|
|
1253
|
-
${
|
|
1254
|
-
`);let p=await
|
|
1255
|
-
${
|
|
1256
|
-
`);return}let g=await o("Default model","claude-sonnet-4-6");c.push("DEFAULT_PROVIDER=anthropic",`DEFAULT_MODEL=${g}`,`ANTHROPIC_API_KEY=${p}`),process.env.DEFAULT_PROVIDER="anthropic",process.env.DEFAULT_MODEL=g,process.env.ANTHROPIC_API_KEY=p}else if(i==="3"){console.log(),console.log(` ${
|
|
1257
|
-
${
|
|
1258
|
-
`);return}let g=await o("Default model","gpt-4o");c.push("DEFAULT_PROVIDER=openai",`DEFAULT_MODEL=${g}`,`OPENAI_API_KEY=${p}`),process.env.DEFAULT_PROVIDER="openai",process.env.DEFAULT_MODEL=g,process.env.OPENAI_API_KEY=p}else if(i==="4"){console.log(),console.log(` ${
|
|
1259
|
-
${
|
|
1260
|
-
`);return}let g=await o("Default model","gemini-2.0-flash");c.push("DEFAULT_PROVIDER=gemini",`DEFAULT_MODEL=${g}`,`GEMINI_API_KEY=${p}`),process.env.DEFAULT_PROVIDER="gemini",process.env.DEFAULT_MODEL=g,process.env.GEMINI_API_KEY=p}if(console.log(),(await o("Add Perplexity key for grounded web search? (y/N)","n")).toLowerCase()==="y"){console.log(` ${
|
|
1261
|
-
|
|
1262
|
-
`:"";
|
|
1257
|
+
${Pr}Ollama Cloud${Ae} ${wt}(recommended): uses ollama.com API \u2014 flat-rate, 47+ models.${Ae}`),console.log(` ${wt}Get your API key at: https://ollama.com/settings/api-keys${Ae}
|
|
1258
|
+
`);let p=await Lr("OLLAMA_API_KEY (leave blank for local)",t),g=p?"https://ollama.com":await o("Ollama host","http://localhost:11434"),m=await o("Default model",p?"devstral-2:123b":"qwen3-coder");c.push("DEFAULT_PROVIDER=ollama",`DEFAULT_MODEL=${m}`,`OLLAMA_HOST=${g}`),p&&c.push(`OLLAMA_API_KEY=${p}`),process.env.DEFAULT_PROVIDER="ollama",process.env.DEFAULT_MODEL=m,process.env.OLLAMA_HOST=g,p&&(process.env.OLLAMA_API_KEY=p)}else if(i==="2"){console.log(),console.log(` ${wt}Get your key: https://console.anthropic.com/settings/keys${Ae}`);let p=await Lr("ANTHROPIC_API_KEY",t);if(!p){n&&s.close(),console.log(`
|
|
1259
|
+
${Ta} No key entered \u2014 cancelled.${Ae}
|
|
1260
|
+
`);return}let g=await o("Default model","claude-sonnet-4-6");c.push("DEFAULT_PROVIDER=anthropic",`DEFAULT_MODEL=${g}`,`ANTHROPIC_API_KEY=${p}`),process.env.DEFAULT_PROVIDER="anthropic",process.env.DEFAULT_MODEL=g,process.env.ANTHROPIC_API_KEY=p}else if(i==="3"){console.log(),console.log(` ${wt}Get your key: https://platform.openai.com/api-keys${Ae}`);let p=await Lr("OPENAI_API_KEY",t);if(!p){n&&s.close(),console.log(`
|
|
1261
|
+
${Ta} No key entered \u2014 cancelled.${Ae}
|
|
1262
|
+
`);return}let g=await o("Default model","gpt-4o");c.push("DEFAULT_PROVIDER=openai",`DEFAULT_MODEL=${g}`,`OPENAI_API_KEY=${p}`),process.env.DEFAULT_PROVIDER="openai",process.env.DEFAULT_MODEL=g,process.env.OPENAI_API_KEY=p}else if(i==="4"){console.log(),console.log(` ${wt}Get your key: https://aistudio.google.com/app/apikey${Ae}`);let p=await Lr("GEMINI_API_KEY",t);if(!p){n&&s.close(),console.log(`
|
|
1263
|
+
${Ta} No key entered \u2014 cancelled.${Ae}
|
|
1264
|
+
`);return}let g=await o("Default model","gemini-2.0-flash");c.push("DEFAULT_PROVIDER=gemini",`DEFAULT_MODEL=${g}`,`GEMINI_API_KEY=${p}`),process.env.DEFAULT_PROVIDER="gemini",process.env.DEFAULT_MODEL=g,process.env.GEMINI_API_KEY=p}if(console.log(),(await o("Add Perplexity key for grounded web search? (y/N)","n")).toLowerCase()==="y"){console.log(` ${wt}Get your key: https://www.perplexity.ai/settings/api${Ae}`);let p=await Lr("PERPLEXITY_API_KEY",t);p&&(c.push(`PERPLEXITY_API_KEY=${p}`),process.env.PERPLEXITY_API_KEY=p)}console.log();let u=Ea.join(process.cwd(),".env"),d=(jn.existsSync(u),"y"),f=await o(`Save to ${u}? (Y/n)`,d);if(n&&s.close(),f.toLowerCase()!=="n"){let p=jn.existsSync(u)?jn.readFileSync(u,"utf-8").trimEnd()+`
|
|
1265
|
+
|
|
1266
|
+
`:"";jn.writeFileSync(u,p+c.join(`
|
|
1263
1267
|
`)+`
|
|
1264
|
-
`);let g=
|
|
1265
|
-
`).some(h=>h.trim()===".env")||
|
|
1268
|
+
`);let g=Ea.join(process.cwd(),".gitignore");jn.existsSync(g)&&(jn.readFileSync(g,"utf-8").split(`
|
|
1269
|
+
`).some(h=>h.trim()===".env")||jn.appendFileSync(g,`
|
|
1266
1270
|
.env
|
|
1267
1271
|
`)),console.log(`
|
|
1268
|
-
${
|
|
1269
|
-
${
|
|
1270
|
-
${
|
|
1271
|
-
`)}
|
|
1272
|
+
${Pr} \u2713 Saved to ${u}${Ae}`),c.some(m=>m.includes("API_KEY"))&&console.log(`${wt} (key stored locally \u2014 never committed)${Ae}`)}if(process.env.DEFAULT_PROVIDER)try{let{setActiveModel:p}=Be(),g=process.env.DEFAULT_MODEL?`${process.env.DEFAULT_PROVIDER}:${process.env.DEFAULT_MODEL}`:process.env.DEFAULT_PROVIDER;p(g),console.log(`${Pr} \u2713 Switched to ${g} for this session${Ae}`)}catch{}console.log(`
|
|
1273
|
+
${Pr} \u2713 Setup complete!${Ae}`),console.log(`
|
|
1274
|
+
${Ir}\u{1F4A1} Tip: Run ${Mr}/benchmark${Ae} ${Ir}to automatically find and use the best models for your tasks.${Ae}
|
|
1275
|
+
`)}kg.exports={runSetupWizard:xE}});var mu=oe((eC,Ng)=>{"use strict";var dn=require("fs"),jr=require("path"),{atomicWrite:Rg}=Tn(),vE=20,SE=3,Cg=3,kE=14400*1e3;function Dr(){return jr.join(process.cwd(),".nex","dream-logs")}function du(){return jr.join(Dr(),"_meta.json")}function EE(){let t=Dr();return dn.existsSync(t)||dn.mkdirSync(t,{recursive:!0}),t}function Ag(t){if(!Array.isArray(t)||t.length===0)return null;let e={},n={},s={},o={},r=0,i=0,c=0,l=0;for(let u of t){if(u.role==="user"&&c++,u.role==="assistant"&&l++,u.role==="assistant"&&Array.isArray(u.content)){for(let d of u.content)if(d&&d.type==="tool_use"){let f=d.name||"unknown";e[f]=(e[f]||0)+1,r++;let p=d.input||{},g=p.path||p.file_path||p.filePath||"";g&&((f==="read_file"||f==="glob"||f==="grep"||f==="search_files")&&(s[g]=(s[g]||0)+1),(f==="write_file"||f==="edit_file"||f==="patch_file")&&(o[g]=(o[g]||0)+1))}}if(u.role==="assistant"&&Array.isArray(u.tool_calls))for(let d of u.tool_calls){let f=d.function?.name||d.name||"unknown";e[f]=(e[f]||0)+1,r++}if(u.role==="tool"){let d=typeof u.content=="string"?u.content:"";if(d.includes("Error")||d.includes("error")||d.includes("FAILED")||d.includes("failed")||d.includes("not found")||d.includes("permission denied")){let f=u.name||"unknown";n[f]=(n[f]||0)+1,i++}}}return r<SE?null:{timestamp:new Date().toISOString(),userMessages:c,assistantMessages:l,totalToolCalls:r,totalErrors:i,toolCalls:e,toolErrors:n,filesAccessed:Eg(s,10),filesModified:Eg(o,10)}}function TE(t){let e=Ag(t);if(!e)return null;let n=EE(),s=`dream-${Date.now()}.json`,o=jr.join(n,s);try{return Rg(o,JSON.stringify(e,null,2)),AE(n),o}catch{return null}}function RE(){let t=du();if(!dn.existsSync(t))return!0;try{let o=JSON.parse(dn.readFileSync(t,"utf-8")),r=new Date(o.lastConsolidation||0).getTime();if(Date.now()-r<kE)return!1}catch{return!0}let e=fu(),n=pu();return e.filter(o=>!n.processed?.includes(o)).length>=Cg}function CE(){let t=fu(),e=pu(),n=t.filter(m=>!e.processed?.includes(m));if(n.length<Cg)return{insights:[],memoriesWritten:0};let s=[];for(let m of n)try{let h=JSON.parse(dn.readFileSync(jr.join(Dr(),m),"utf-8"));s.push(h)}catch{}if(s.length===0)return{insights:[],memoriesWritten:0};let o=[],r=0,i={},c={},l={};for(let m of s){for(let[h,y]of Object.entries(m.toolCalls||{}))i[h]=(i[h]||0)+y;for(let[h,y]of Object.entries(m.toolErrors||{}))c[h]=(c[h]||0)+y;for(let[h,y]of Object.entries(m.filesAccessed||{}))l[h]=(l[h]||0)+y}let u=[];for(let[m,h]of Object.entries(c)){let y=i[m]||h,b=h/y;b>.3&&h>=3&&u.push({tool:m,errors:h,calls:y,rate:Math.round(b*100)})}if(u.length>0){let m=u.sort((b,S)=>S.rate-b.rate).map(b=>`- ${b.tool}: ${b.rate}% error rate (${b.errors}/${b.calls} calls)`).join(`
|
|
1272
1276
|
`),h=`High-error tools detected across ${s.length} sessions:
|
|
1273
|
-
${m}`;o.push(h)
|
|
1277
|
+
${m}`;o.push(h),Tg("dream-error-prone-tools","Tools with high error rates across recent sessions",h)&&r++}let d=s.length,f={};for(let m of s){let h=new Set;for(let y of Object.keys(m.filesAccessed||{}))h.has(y)||(f[y]=(f[y]||0)+1,h.add(y))}let p=Object.entries(f).filter(([m,h])=>h>d*.5&&(l[m]||0)>5).map(([m,h])=>({file:m,sessions:h,reads:l[m]||0})).sort((m,h)=>h.sessions-m.sessions).slice(0,10);if(p.length>0){let m=p.map(b=>`- ${b.file}: accessed in ${b.sessions}/${d} sessions (${b.reads} total reads)`).join(`
|
|
1274
1278
|
`),h=`Frequently accessed files across ${d} sessions:
|
|
1275
|
-
${m}`;o.push(h)
|
|
1276
|
-
`))}function
|
|
1277
|
-
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,s=>`<${s.charCodeAt(0).toString(16).padStart(2,"0")}>`);
|
|
1278
|
-
`)}function
|
|
1279
|
-
`)&&!m.includes("\r"))return
|
|
1280
|
-
`);for(let k=0;k<
|
|
1281
|
-
`)&&!/\x1b\[\d+A/.test(m)&&n._cursorOnInputRow&&(n.drawFooter(),n._origWrite(n._goto(n._rowInput)+"\x1B[2K")),y},this._origLog=console.log,this._origError=console.error;function o(...m){if(!n._active){n._origLog(...m);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origLog(...m),n.drawFooter(),s(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}function r(...m){if(!n._active){n._origError(...m);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origError(...m),n.drawFooter(),s(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}console.log=o,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(m){n._origSetPr(m),n._active&&n.drawFooter(m)},this._origPrompt=e.prompt.bind(e),e.prompt=function(m){if(!n._active)return n._origPrompt(m);
|
|
1282
|
-
`);process.stdout.write(`\x1B[${p}A`)}let
|
|
1279
|
+
${m}`;o.push(h),Tg("dream-hot-files","Files accessed frequently across multiple sessions",h)&&r++}let g=s.map(m=>m.userMessages===0?null:m.totalToolCalls/m.userMessages).filter(Boolean);if(g.length>=3){let m=g.reduce((y,b)=>y+b,0)/g.length,h=s.reduce((y,b)=>y+(b.totalErrors||0),0)/s.length;if(m>15){let y=`High tool-call density: avg ${m.toFixed(1)} tool calls per user message across ${s.length} sessions. Consider more targeted investigation.`;o.push(y)}if(h>5){let y=`High error rate: avg ${h.toFixed(1)} errors per session across ${s.length} sessions.`;o.push(y)}}return Og({lastConsolidation:new Date().toISOString(),processed:[...e.processed||[],...n],totalConsolidations:(e.totalConsolidations||0)+1}),{insights:o,memoriesWritten:r}}function Eg(t,e=10){return Object.fromEntries(Object.entries(t).sort(([,n],[,s])=>s-n).slice(0,e))}function fu(){let t=Dr();if(!dn.existsSync(t))return[];try{return dn.readdirSync(t).filter(e=>e.startsWith("dream-")&&e.endsWith(".json")).sort()}catch{return[]}}function AE(t){try{let e=dn.readdirSync(t).filter(n=>n.startsWith("dream-")&&n.endsWith(".json")).sort();for(;e.length>vE;){let n=e.shift();dn.unlinkSync(jr.join(t,n))}}catch{}}function pu(){let t=du();if(!dn.existsSync(t))return{};try{return JSON.parse(dn.readFileSync(t,"utf-8"))}catch{return{}}}function Og(t){try{Rg(du(),JSON.stringify(t,null,2))}catch{}}function Tg(t,e,n){try{let{saveMemory:s}=tn();return s("feedback",t,n,e).ok}catch{return!1}}Ng.exports={extractSessionStats:Ag,writeDreamLog:TE,shouldConsolidate:RE,consolidate:CE,_getDreamDir:Dr,_listDreamLogs:fu,_readMeta:pu,_writeMeta:Og}});var Ig=oe((tC,Lg)=>{"use strict";var Ra=require("fs"),{T:fn,isDark:OE}=os(),Ft="\x1B[0m",NE=!OE,ME=process.env.FOOTER_DEBUG==="1"||process.env.FOOTER_DEBUG==="2",PE=process.env.FOOTER_DEBUG==="2",So=null;function Xn(...t){ME&&(So||(So=Ra.openSync("/tmp/footer-debug.log","w")),Ra.writeSync(So,t.join(" ")+`
|
|
1280
|
+
`))}function Mg(t,e){if(!PE||typeof e!="string")return;So||(So=Ra.openSync("/tmp/footer-debug.log","w"));let n=e.replace(/\x1b\[([^a-zA-Z]*)([a-zA-Z])/g,(s,o,r)=>`<ESC[${o}${r}>`).replace(/\x1b([^[])/g,(s,o)=>`<ESC${o}>`).replace(/\r/g,"<CR>").replace(/\n/g,`<LF>
|
|
1281
|
+
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,s=>`<${s.charCodeAt(0).toString(16).padStart(2,"0")}>`);Ra.writeSync(So,`${t}: ${n}
|
|
1282
|
+
`)}function Pg(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var hu=class{constructor(){this._active=!1,this._rl=null,this._origWrite=null,this._origPrompt=null,this._origSetPr=null,this._origRefreshLine=null,this._origLog=null,this._origError=null,this._origStderrWrite=null,this._drawing=!1,this._offResize=null,this._cursorOnInputRow=!1,this._inRefreshLine=!1,this._lastOutputRow=1,this._prevTermRows=0,this._prevTermCols=0,this._consistencyTimer=null,this._dirty=!1,this._statusModel="",this._statusBranch="",this._statusProject="",this._statusMode=""}setStatusInfo({model:e,branch:n,project:s,mode:o}={}){e!==void 0&&(this._statusModel=e),n!==void 0&&(this._statusBranch=n),s!==void 0&&(this._statusProject=s),o!==void 0&&(this._statusMode=o),this._active&&this.drawFooter()}get _rows(){return process.stdout.rows||24}get _cols(){return process.stdout.columns||80}get _scrollEnd(){return this._rows-2}get _rowStatus(){return this._rows-1}get _rowInput(){return this._rows}_goto(e,n=1){return`\x1B[${e};${n}H`}_statusLine(){let e=this._cols,n=this._statusModel,s=this._statusBranch,o=this._statusProject,r=this._statusMode;if(!n)return fn.footer_sep+"\u2500".repeat(e)+Ft;let i=` ${fn.footer_divider}\xB7${Ft} `,c=[];n&&c.push(`${fn.footer_model}${n}${Ft}`),s&&c.push(`${fn.footer_branch}${s}${Ft}`),o&&c.push(`${fn.footer_project}${o}${Ft}`);let l=c.join(i),u=[n,s,o].filter(Boolean).join(" \xB7 ").length,d="\u2500 ";if(r){let g=r.length,m=Math.max(0,e-d.length-u-1-1-g-3),h="\u2500".repeat(m);return`${fn.footer_sep}${d}${Ft}${l}${fn.footer_sep} ${h} ${Ft}${fn.footer_mode}${r}${Ft}${fn.footer_sep} \u2500\u2500${Ft}`}let f=Math.max(0,e-d.length-u-2),p="\u2500".repeat(f);return`${fn.footer_sep}${d}${Ft}${l}${fn.footer_sep} ${p}${Ft}`}drawFooter(e){!this._origWrite||this._drawing||(this._drawing=!0,this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K"+this._statusLine(e)+"\x1B8"),this._drawing=!1)}_setScrollRegion(){if(NE)return;let e=Math.max(1,this._scrollEnd);this._origWrite(`\x1B[1;${e}r`)}_clearScrollRegion(){this._origWrite&&this._origWrite("\x1B[r")}_eraseStatus(){this._origWrite&&this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K\x1B8")}rawWrite(e){return Mg("RAW",e),this._origWrite?this._origWrite(e):process.stdout.write(e)}_relayout(e){if(!this._origWrite)return;let n=this._origWrite,s=this._rows,o=this._cols,r=Math.max(1,s-2);Xn("RELAYOUT:",e,"rows="+s,"cols="+o,"scrollEnd="+r,"cursorOnInput="+this._cursorOnInputRow),this._prevTermRows=s,this._prevTermCols=o;let i=Math.min(this._lastOutputRow+1,r+1),c="";for(let l=i;l<=s;l++)c+=this._goto(l)+"\x1B[2K";n(c),this._setScrollRegion(),this._lastOutputRow=Math.min(this._lastOutputRow,r),this.drawFooter(),this._cursorOnInputRow&&this._rl&&this._rl.prompt(!0),this._dirty=!1}activate(e){if(!process.stdout.isTTY)return;this._rl=e,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._prevTermRows=this._rows,this._prevTermCols=this._cols,this._origWrite("\x1B[r"),this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let n=this,s=process.stdout.write.bind(process.stdout);this._origWrite=s,process.stdout.write=function(m,...h){if(Mg("PATCH",m),!n._active||typeof m!="string")return s(m,...h);if(n._inRefreshLine){let k=m.replace(/\n/g,"");return k?s(k,...h):!0}if(n._cursorOnInputRow){if(m.length<=4&&!m.includes(`
|
|
1283
|
+
`)&&!m.includes("\r"))return Xn("STDOUT: input-row intercept:",JSON.stringify(m)),n._origRefreshLine&&n._doRefreshLine(),!0;Xn("STDOUT: non-echo on input row, anchoring to workspace, data="+JSON.stringify(m).slice(0,100)),n._cursorOnInputRow=!1,s(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd)))}let y=n._cols||80,b=0,S=m.split(`
|
|
1284
|
+
`);for(let k=0;k<S.length;k++){let x=Pg(S[k]);x>0&&(b+=Math.floor((x-1)/y))}let C=S.length-1;return C+b>0&&(n._lastOutputRow=Math.min(n._lastOutputRow+C+b,n._scrollEnd)),s(m,...h)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(m,...h){if(!n._active)return n._origStderrWrite(m,...h);if(typeof m=="string"&&m.includes("\r")){let b=Math.min(n._lastOutputRow+1,n._scrollEnd);if(n._cursorOnInputRow){n._origWrite("\x1B7"),n._origWrite(n._goto(b));let S=n._origStderrWrite(m,...h);return n._origWrite("\x1B8"),S}n._origWrite(n._goto(b))}let y=n._origStderrWrite(m,...h);return typeof m=="string"&&m.includes(`
|
|
1285
|
+
`)&&!/\x1b\[\d+A/.test(m)&&n._cursorOnInputRow&&(n.drawFooter(),n._origWrite(n._goto(n._rowInput)+"\x1B[2K")),y},this._origLog=console.log,this._origError=console.error;function o(...m){if(!n._active){n._origLog(...m);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origLog(...m),n.drawFooter(),s(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}function r(...m){if(!n._active){n._origError(...m);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origError(...m),n.drawFooter(),s(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}console.log=o,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(m){n._origSetPr(m),n._active&&n.drawFooter(m)},this._origPrompt=e.prompt.bind(e),e.prompt=function(m){if(!n._active)return n._origPrompt(m);Xn("PROMPT: goto rowInput="+n._rowInput),e.prevRows=0,s(n._goto(n._rowInput)+Ft+"\x1B[2K"),n._cursorOnInputRow=!0,n._origPrompt(m)};let i=e.question.bind(e);e.question=function(m,h){if(!n._active)return i(m,h);s(n._goto(n._rowInput)+"\x1B[2K"),e.prevRows=0,n._cursorOnInputRow=!0,i(m,y=>{s(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!1,n.drawFooter(),h(y)})};let c=Object.getPrototypeOf(e),l=Object.getOwnPropertySymbols(c).find(m=>m.toString()==="Symbol(_refreshLine)"),u=l?c[l].bind(e):e._refreshLine?e._refreshLine.bind(e):null;if(this._origRefreshLine=u,this._doRefreshLine=function(){if(!n._active||!u)return;if(n._rows!==n._prevTermRows||n._cols!==n._prevTermCols){n._dirty=!0;return}e.prevRows=0,s(n._goto(n._rowInput)+Ft+"\x1B[2K");let m=n._cols,h=e._prompt||"",y=Pg(h),b=m-y-1;n._inRefreshLine=!0;try{if(e.line.length<=b){Xn("REFRESH: short line, len="+e.line.length),u();return}Xn("REFRESH: long line, len="+e.line.length+", max="+b);let S=e.line,C=e.cursor,k=Math.max(1,b-1),x=Math.max(0,C-k),E=(x>0?"\xAB":"")+S.slice(x,x+k+(x>0?0:1));e.line=E,e.cursor=E.length,u(),e.line=S,e.cursor=C}finally{n._inRefreshLine=!1}},u){let m=this._doRefreshLine;l&&Object.defineProperty(e,l,{value:m,writable:!0,configurable:!0}),e._refreshLine=m}e.on("line",()=>{n._active&&(Xn("LINE: leaving input row"),n._cursorOnInputRow=!1,s(n._goto(n._rowInput)+"\x1B[2K"),s(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n.drawFooter())});let d=null,f=null,p=()=>{d=null,n._relayout("resize"),f&&clearTimeout(f),f=setTimeout(()=>{f=null,n._relayout("resize-cleanup")},300)},g=()=>{n._dirty=!0,d&&clearTimeout(d),d=setTimeout(p,80)};process.stdout.on("resize",g),this._offResize=()=>{process.stdout.off("resize",g),d&&(clearTimeout(d),d=null),f&&(clearTimeout(f),f=null)},this._consistencyTimer=setInterval(()=>{if(!n._active)return;let m=n._rows,h=n._cols;(n._dirty||m!==n._prevTermRows||h!==n._prevTermCols)&&(Xn("CONSISTENCY: dirty="+n._dirty+" rows="+m+"/"+n._prevTermRows+" cols="+h+"/"+n._prevTermCols),n._relayout("consistency"))},800)}deactivate(){if(this._active){if(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._consistencyTimer&&(clearInterval(this._consistencyTimer),this._consistencyTimer=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine)){let e=Object.getOwnPropertySymbols(Object.getPrototypeOf(this._rl)).find(n=>n.toString()==="Symbol(_refreshLine)");e&&delete this._rl[e],delete this._rl._refreshLine,this._origRefreshLine=null}this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null}}};Lg.exports={StickyFooter:hu}});var qg=oe((nC,Dg)=>{var{C:ze}=Ke(),{listProviders:LE,getActiveProviderName:IE,getActiveModelId:jE,setActiveModel:DE}=Be();function jg(t,e,n={}){let{title:s="Select",hint:o="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=n;return new Promise(r=>{let i=e.map((b,S)=>b.isHeader?-1:S).filter(b=>b>=0);if(i.length===0){r(null);return}let c=e.findIndex(b=>b.isCurrent),l=c>=0?i.indexOf(c):0;l<0&&(l=0);let u=process.stdout.rows?Math.max(process.stdout.rows-6,5):20,d=0;function f(){let b=i[l];return b<d?d=b:b>=d+u&&(d=b-u+1),{start:d,end:Math.min(e.length,d+u)}}let p=0;function g(){if(p>0){process.stdout.write(`\x1B[${p}A`);for(let x=0;x<p;x++)process.stdout.write(`\x1B[2K
|
|
1286
|
+
`);process.stdout.write(`\x1B[${p}A`)}let b=[];b.push(` ${ze.bold}${ze.cyan}${s}${ze.reset}`),b.push(` ${ze.dim}${o}${ze.reset}`),b.push("");let{start:S,end:C}=f();S>0&&b.push(` ${ze.dim}\u2191 more${ze.reset}`);for(let x=S;x<C;x++){let E=e[x];if(E.isHeader){b.push(` ${ze.bold}${ze.dim}${E.label}${ze.reset}`);continue}let B=i[l]===x,q=B?`${ze.cyan}> `:" ",re=E.isCurrent?` ${ze.yellow}<current>${ze.reset}`:"";B?b.push(`${q}${ze.bold}${E.label}${ze.reset}${re}`):b.push(`${q}${ze.dim}${E.label}${ze.reset}${re}`)}C<e.length&&b.push(` ${ze.dim}\u2193 more${ze.reset}`);let k=b.join(`
|
|
1283
1287
|
`);process.stdout.write(k+`
|
|
1284
|
-
`),p=
|
|
1288
|
+
`),p=b.length}t.pause();let m=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function h(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&m!==void 0&&process.stdin.setRawMode(m),t.resume()}function y(b,S){if(S){if(S.name==="up"||S.ctrl&&S.name==="p"){l>0&&(l--,g());return}if(S.name==="down"||S.ctrl&&S.name==="n"){l<i.length-1&&(l++,g());return}if(S.name==="return"){let C=e[i[l]];h(),r(C?C.value:null);return}if(S.name==="escape"||S.ctrl&&S.name==="c"){h(),r(null);return}}}process.stdin.on("keypress",y),g()})}async function qE(t){let e=LE(),n=IE(),s=jE(),o=[];for(let i of e)if(i.models.length!==0){o.push({label:i.provider,value:null,isHeader:!0});for(let c of i.models){let l=i.provider===n&&c.id===s;o.push({label:` ${c.name} (${i.provider}:${c.id})`,value:`${i.provider}:${c.id}`,isCurrent:l})}}let r=await jg(t,o,{title:"Select Model"});return r?(DE(r),console.log(`${ze.green}Switched to ${r}${ze.reset}`),!0):(console.log(`${ze.dim}Cancelled${ze.reset}`),!1)}Dg.exports={pickFromList:jg,showModelPicker:qE}});var $u=oe((oC,Gg)=>{var Fg=require("fs"),FE=require("path"),{atomicWrite:UE,withFileLockSync:BE}=Tn(),{callChat:Ug}=Be(),{remember:WE,listMemories:sC,recall:HE}=tn(),gu=4,KE=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
1285
1289
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
1286
1290
|
|
|
1287
1291
|
Return ONLY valid JSON in this exact format:
|
|
@@ -1307,15 +1311,15 @@ Rules:
|
|
|
1307
1311
|
- value: concise actionable instruction, max 120 chars
|
|
1308
1312
|
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
1309
1313
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
1310
|
-
- Return ONLY the JSON, no markdown, no explanation`;function
|
|
1314
|
+
- Return ONLY the JSON, no markdown, no explanation`;function Bg(t){return t.filter(e=>(e.role==="user"||e.role==="assistant")&&typeof e.content=="string"&&e.content.trim().length>10).slice(-40).map(e=>`[${e.role.toUpperCase()}]: ${e.content.substring(0,700)}`).join(`
|
|
1311
1315
|
|
|
1312
|
-
`)}async function
|
|
1316
|
+
`)}async function Wg(t){if(t.filter(o=>o.role==="user").length<gu)return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=Bg(t);if(!n.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=[{role:"system",content:KE},{role:"user",content:`Conversation to analyze:
|
|
1313
1317
|
|
|
1314
|
-
${n}`}];try{let i=((await
|
|
1318
|
+
${n}`}];try{let i=((await Ug(s,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let c=JSON.parse(i[0]);return{memories:Array.isArray(c.memories)?c.memories:[],nex_additions:Array.isArray(c.nex_additions)?c.nex_additions:[],summary:typeof c.summary=="string"?c.summary:null}}catch(o){return{memories:[],nex_additions:[],summary:null,error:o.message}}}function Hg(t){let e=[];for(let{key:n,value:s}of t||[]){if(!n||!s||typeof n!="string"||typeof s!="string")continue;let o=n.trim().replace(/\s+/g,"-").substring(0,60),r=s.trim().substring(0,200);if(!o||!r)continue;let i=HE(o);i!==r&&(WE(o,r),e.push({key:o,value:r,action:i?"updated":"added"}))}return e}function Kg(t){if(!t||t.length===0)return[];let e=FE.join(process.cwd(),"NEX.md");return BE(e,()=>{let n="";try{Fg.existsSync(e)&&(n=Fg.readFileSync(e,"utf-8"))}catch{}let s=[],o=n;for(let r of t){if(!r||typeof r!="string")continue;let i=r.trim();if(!i)continue;let c=i.substring(0,35).toLowerCase();n.toLowerCase().includes(c)||(s.push(i),o=o?o.endsWith(`
|
|
1315
1319
|
`)?o+i:o+`
|
|
1316
1320
|
`+i:i)}return s.length>0&&(o.endsWith(`
|
|
1317
1321
|
`)||(o+=`
|
|
1318
|
-
`),
|
|
1322
|
+
`),UE(e,o)),s})}async function YE(t){let e=await Wg(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let n=Hg(e.memories),s=Kg(e.nex_additions);return{applied:n,nexAdded:s,summary:e.summary}}var GE=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
1319
1323
|
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
1320
1324
|
|
|
1321
1325
|
Return ONLY valid JSON in this exact format:
|
|
@@ -1349,43 +1353,43 @@ Rules:
|
|
|
1349
1353
|
---
|
|
1350
1354
|
- Maximum 3 documents per session. Quality over quantity.
|
|
1351
1355
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
1352
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function
|
|
1356
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function Yg(t){if(t.filter(o=>o.role==="user").length<gu)return{documents:[],skip_reason:"Session too short"};let n=Bg(t);if(!n.trim())return{documents:[],skip_reason:"No usable content"};let s=[{role:"system",content:GE},{role:"user",content:`Conversation to analyze:
|
|
1353
1357
|
|
|
1354
|
-
${n}`}];try{let i=((await
|
|
1358
|
+
${n}`}];try{let i=((await Ug(s,[],{temperature:0,maxTokens:2e3})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{documents:[],error:"No JSON in response"};let c=JSON.parse(i[0]);return{documents:Array.isArray(c.documents)?c.documents:[],skip_reason:c.skip_reason}}catch(o){return{documents:[],error:o.message}}}async function zE(t){let e=await Yg(t);if(e.error)return{written:[],skipped:[],error:e.error};if(!e.documents||e.documents.length===0)return{written:[],skipped:[],skip_reason:e.skip_reason};let{writeDocument:n,readDocument:s}=Qo(),o=[],r=[];for(let i of e.documents){if(!i.name||!i.content)continue;let c=i.name.trim().replace(/\.md$/,"").replace(/[^a-z0-9-]/g,"-").substring(0,60);if(!c)continue;let l=s(c);if(l.content){let d=`
|
|
1355
1359
|
|
|
1356
1360
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
1357
1361
|
|
|
1358
|
-
${i.content}`;n(c,l.content+d),o.push({name:c,reason:i.reason||"",action:"updated"})}else n(c,i.content),o.push({name:c,reason:i.reason||"",action:"created"})}return{written:o,skipped:r}}
|
|
1362
|
+
${i.content}`;n(c,l.content+d),o.push({name:c,reason:i.reason||"",action:"updated"})}else n(c,i.content),o.push({name:c,reason:i.reason||"",action:"created"})}return{written:o,skipped:r}}Gg.exports={learnFromSession:YE,learnBrainFromSession:zE,reflectOnSession:Wg,reflectBrain:Yg,applyMemories:Hg,applyNexAdditions:Kg,LEARN_MIN_MESSAGES:gu}});var Vn=oe((rC,zg)=>{var{C:je}=Ke();function XE(t){return t.tree&&t.tree.branches?t.tree:{branches:{main:{messages:t.messages||[],parentBranch:null,forkIndex:0}},activeBranch:"main"}}function VE(t){let e=t.branches[t.activeBranch];return e?e.messages:[]}function JE(t,e){let n=t.branches[t.activeBranch];n&&(n.messages=e)}function ZE(t,e,n){let s=t.activeBranch,o=t.branches[s].messages;if(e<0||e>=o.length)throw new Error(`Fork index ${e} out of range (0-${o.length-1})`);return n||(n=`branch-${Object.keys(t.branches).filter(c=>c.startsWith("branch-")).reduce((c,l)=>{let u=parseInt(l.replace("branch-",""),10);return isNaN(u)?c:Math.max(c,u)},0)+1}`),t.branches[n]={messages:o.slice(0,e+1),parentBranch:s,forkIndex:e},t.activeBranch=n,{tree:t,branchName:n}}function QE(t,e){if(!t.branches[e])throw new Error(`Branch "${e}" not found. Available: ${Object.keys(t.branches).join(", ")}`);return t.activeBranch=e,t}function eT(t,e){let n=t.branches[t.activeBranch];if(!n)throw new Error("No active branch");if(e<0||e>=n.messages.length)throw new Error(`Index ${e} out of range (0-${n.messages.length-1})`);let s=n.messages.length-(e+1);return n.messages=n.messages.slice(0,e+1),{tree:t,truncated:s}}function tT(t,e){if(e==="main")throw new Error('Cannot delete the "main" branch');if(e===t.activeBranch)throw new Error("Cannot delete the active branch. Switch to another branch first.");if(!t.branches[e])throw new Error(`Branch "${e}" not found`);return delete t.branches[e],t}function nT(t){let e=[];e.push(`${je.bold}${je.cyan}Session Tree${je.reset}
|
|
1359
1363
|
`);let n=Object.keys(t.branches);for(let s of n){let o=t.branches[s],r=s===t.activeBranch,i=r?`${je.green}* `:" ",c=r?`${je.green}${je.bold}${s}${je.reset}`:`${je.cyan}${s}${je.reset}`,l=o.messages.length,u=o.parentBranch?` ${je.dim}(forked from ${o.parentBranch}@${o.forkIndex})${je.reset}`:"";e.push(`${i}${c} \u2014 ${l} messages${u}`);let f=o.messages.filter(p=>p.role==="user").slice(-2);for(let p of f){let g=typeof p.content=="string"?p.content.substring(0,60):"[multimodal]";e.push(` ${je.dim}> ${g}${g.length>=60?"...":""}${je.reset}`)}}return e.join(`
|
|
1360
|
-
`)}function
|
|
1364
|
+
`)}function sT(t,e=20){let n=t.branches[t.activeBranch];if(!n)return"No active branch.";let s=n.messages,o=[];o.push(`${je.bold}${je.cyan}Timeline: ${t.activeBranch}${je.reset} (${s.length} messages)
|
|
1361
1365
|
`);let r=Math.max(0,s.length-e);for(let i=r;i<s.length;i++){let c=s[i],l=c.role,u=l==="user"?je.green:l==="assistant"?je.cyan:l==="system"?je.yellow:je.dim,d="";if(typeof c.content=="string")d=c.content.substring(0,70).replace(/\n/g," ");else if(Array.isArray(c.content)){let p=c.content.find(g=>g.type==="text"||g.type==="tool_result");d=p?(p.text||p.content||"").substring(0,70):"[blocks]"}d.length>=70&&(d+="...");let f=c.tool_calls&&c.tool_calls.length>0?` ${je.dim}[${c.tool_calls.length} tool calls]${je.reset}`:"";o.push(` ${je.dim}${String(i).padStart(3)}${je.reset} ${u}${l.padEnd(9)}${je.reset} ${d}${f}`)}return r>0&&o.splice(1,0,` ${je.dim}... ${r} earlier messages not shown${je.reset}`),o.join(`
|
|
1362
|
-
`)}
|
|
1366
|
+
`)}zg.exports={initTree:XE,getActiveMessages:VE,setActiveMessages:JE,createBranch:ZE,switchBranch:QE,gotoMessage:eT,deleteBranch:tT,renderTree:nT,renderTimeline:sT}});var e$=oe((iC,Qg)=>{var{spawn:oT}=require("child_process"),Xg=require("path"),Vg=require("fs"),rT=require("os"),Jn=new Map;function Jg(t){return typeof t!="string"?t:t.replace(/\$\{([^}]+)\}/g,(e,n)=>process.env[n]!==void 0?process.env[n]:"")}function Zg(t){let e=t||process.env.NEX_MCP_CONFIG||null,n=e?[e]:[Xg.join(process.cwd(),".nex","mcp.json"),Xg.join(rT.homedir(),".nex","mcp.json")];for(let s of n)if(Vg.existsSync(s))try{return JSON.parse(Vg.readFileSync(s,"utf-8"))}catch{}return{servers:{}}}function Ca(t,e,n={},s=1e4){return new Promise((o,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:n})+`
|
|
1363
1367
|
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},s);function d(p){l+=p.toString();let g=l.split(`
|
|
1364
|
-
`);for(let m of g)if(m.trim())try{let h=JSON.parse(m);if(h.id===i){f(),h.error?r(new Error(`MCP error: ${h.error.message||JSON.stringify(h.error)}`)):o(h.result);return}}catch{}l=g[g.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(p){f(),r(new Error(`MCP write failed: ${p.message}`))}})}async function
|
|
1365
|
-
`):JSON.stringify(o)}function
|
|
1368
|
+
`);for(let m of g)if(m.trim())try{let h=JSON.parse(m);if(h.id===i){f(),h.error?r(new Error(`MCP error: ${h.error.message||JSON.stringify(h.error)}`)):o(h.result);return}}catch{}l=g[g.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(p){f(),r(new Error(`MCP write failed: ${p.message}`))}})}async function iT(t){let n=Zg(t).servers||{},s=[];for(let[o,r]of Object.entries(n)){if(Jn.has(o)){let d=Jn.get(o);s.push({name:o,tools:d.tools.length});continue}let i={};for(let[d,f]of Object.entries(r.env||{}))i[d]=Jg(f);let c=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],l={};for(let d of c)process.env[d]!==void 0&&(l[d]=process.env[d]);let u;try{u=oT(r.command,r.args||[],{stdio:["pipe","pipe","pipe"],env:{...l,...i}})}catch(d){console.warn(`[mcp-client] Failed to spawn '${o}': ${d.message}`),s.push({name:o,tools:0,error:d.message});continue}try{await Ca(u,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.4.8"}});let d=await Ca(u,"tools/list",{}),f=d&&d.tools||[];Jn.set(o,{name:o,proc:u,tools:f,config:r}),s.push({name:o,tools:f.length})}catch(d){console.warn(`[mcp-client] Server '${o}' failed to initialize: ${d.message}`);try{u.kill()}catch{}s.push({name:o,tools:0,error:d.message})}}return s}async function aT(t,e,n={}){let s=Jn.get(t);if(!s)throw new Error(`MCP server not connected: ${t}`);let o=await Ca(s.proc,"tools/call",{name:e,arguments:n});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
1369
|
+
`):JSON.stringify(o)}function cT(){let t=[];for(let[e,n]of Jn)for(let s of n.tools)t.push({type:"function",function:{name:`mcp_${e}_${s.name}`,description:`[MCP:${e}] ${s.description||""}`,parameters:s.inputSchema||{type:"object",properties:{}}}});return t}function lT(){for(let[t,e]of Jn){try{e.proc.kill()}catch{}Jn.delete(t)}}function uT(){let t=[];for(let[e,n]of Jn)t.push({name:e,connected:!0,toolCount:n.tools.length});return t}Qg.exports={loadMcpServers:iT,callMcpTool:aT,getMcpTools:cT,shutdownMcpServers:lT,listMcpServers:uT,_interpolateEnv:Jg,_readConfig:Zg,_sendRequest:Ca}});var o$=oe((cC,s$)=>{var St=require("fs"),Eo=require("path"),aC=require("os"),dT=require("readline"),{C:de}=Ke(),t$=".nex",yu=null;function fT(t){yu=t}function kt(t,e=""){let n=e?` ${de.dim}[${e}]${de.reset}`:"",s=` ${de.cyan}${t}${n}${de.reset}: `;return new Promise(o=>{let r=i=>{let c=i.trim()||e;o(c)};if(yu)yu.question(s,r);else{let i=dT.createInterface({input:process.stdin,output:process.stdout});i.question(s,c=>{i.close(),r(c)})}})}function ko(t,e=!0){return kt(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(s=>s.toLowerCase()!=="n"&&s.toLowerCase()!=="no")}async function wu(t,e,n){let s=e.map((c,l)=>`${de.dim}${l+1})${de.reset} ${c}`).join(" ");console.log(` ${de.cyan}${t}${de.reset}`),console.log(` ${s}`);let o=n?e.indexOf(n)+1:1,r=await kt("Enter number",String(o)),i=parseInt(r,10)-1;return e[Math.max(0,Math.min(i,e.length-1))]}async function pT(){let t=Eo.join(process.cwd(),t$),e=Eo.join(t,"servers.json"),n={};if(St.existsSync(e))try{n=JSON.parse(St.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
1366
1370
|
${de.bold}${de.cyan}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557${de.reset}`),console.log(`${de.bold}${de.cyan}\u2551 nex-code Server Setup Wizard \u2551${de.reset}`),console.log(`${de.bold}${de.cyan}\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${de.reset}
|
|
1367
|
-
`);let s=Object.keys(n);if(s.length>0&&(console.log(`${de.dim}Existing profiles: ${s.join(", ")}${de.reset}`),!await
|
|
1371
|
+
`);let s=Object.keys(n);if(s.length>0&&(console.log(`${de.dim}Existing profiles: ${s.join(", ")}${de.reset}`),!await ko("Add or update a server profile?",!0))){console.log(`${de.dim}No changes made.${de.reset}
|
|
1368
1372
|
`);return}let o={...n},r=!0;for(;r;){console.log(`
|
|
1369
|
-
${de.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${de.reset}`);let l=await
|
|
1370
|
-
${de.green}\u2713${de.reset} Profile "${l}" added: ${d}@${u}${p!==22?`:${p}`:""}${m!=="other"?` [${m}]`:""}`),r=await
|
|
1371
|
-
Add another server?`,!1)}
|
|
1373
|
+
${de.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${de.reset}`);let l=await kt("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${de.red} Name is required.${de.reset}`);continue}let u=await kt("Host / IP address");if(!u){console.log(`${de.red} Host is required.${de.reset}`);continue}let d=await kt("SSH user","root"),f=await kt("SSH port","22"),p=parseInt(f,10)||22,g=await kt("SSH key path (leave empty for SSH agent)",""),m=await wu("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),h=await ko("Allow sudo commands?",!0),y={host:u,user:d};p!==22&&(y.port=p),g&&(y.key=g),m!=="other"&&(y.os=m),h&&(y.sudo=!0),o[l]=y,console.log(`
|
|
1374
|
+
${de.green}\u2713${de.reset} Profile "${l}" added: ${d}@${u}${p!==22?`:${p}`:""}${m!=="other"?` [${m}]`:""}`),r=await ko(`
|
|
1375
|
+
Add another server?`,!1)}St.existsSync(t)||St.mkdirSync(t,{recursive:!0}),St.writeFileSync(e,JSON.stringify(o,null,2)+`
|
|
1372
1376
|
`,"utf-8"),console.log(`
|
|
1373
|
-
${de.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${de.reset}`);let i=
|
|
1377
|
+
${de.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${de.reset}`);let i=Eo.join(process.cwd(),".gitignore");St.existsSync(i)&&(St.readFileSync(i,"utf-8").includes(".nex/")||await ko("Add .nex/ to .gitignore?",!0)&&(St.appendFileSync(i,`
|
|
1374
1378
|
# nex-code server profiles
|
|
1375
1379
|
.nex/
|
|
1376
|
-
`),console.log(`${de.green}\u2713 Added .nex/ to .gitignore${de.reset}`))),await
|
|
1377
|
-
Set up deploy configs (.nex/deploy.json)?`,!1)&&await
|
|
1380
|
+
`),console.log(`${de.green}\u2713 Added .nex/ to .gitignore${de.reset}`))),await ko(`
|
|
1381
|
+
Set up deploy configs (.nex/deploy.json)?`,!1)&&await n$(o,t),console.log(`
|
|
1378
1382
|
${de.dim}Use /servers to list profiles, /servers ping to check connectivity.${de.reset}
|
|
1379
|
-
`)}async function
|
|
1383
|
+
`)}async function n$(t,e){let n=e||Eo.join(process.cwd(),t$),s=Eo.join(n,"deploy.json"),o={};if(St.existsSync(s))try{o=JSON.parse(St.readFileSync(s,"utf-8"))}catch{}if(!t){let u=Eo.join(n,"servers.json");if(St.existsSync(u))try{t=JSON.parse(St.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
1380
1384
|
${de.bold}${de.cyan}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557${de.reset}`),console.log(`${de.bold}${de.cyan}\u2551 Deploy Config Wizard \u2551${de.reset}`),console.log(`${de.bold}${de.cyan}\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${de.reset}
|
|
1381
1385
|
`);let i=Object.keys(o);i.length>0&&console.log(`${de.dim}Existing deploy configs: ${i.join(", ")}${de.reset}`);let c={...o},l=!0;for(;l;){console.log(`
|
|
1382
|
-
${de.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${de.reset}`);let u=await
|
|
1383
|
-
${de.green}\u2713${de.reset} Deploy config "${u}": [${f}] ${C}`),y&&console.log(` ${de.dim} Then: ${y}${de.reset}`),
|
|
1384
|
-
Add another deploy config?`,!1)}
|
|
1386
|
+
${de.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${de.reset}`);let u=await kt("Config name (e.g. prod, staging)");if(!u){console.log(`${de.red} Name is required.${de.reset}`);continue}let d;r.length>0?d=await wu("Target server",r,r[0]):d=await kt("Target server (profile name or user@host)");let f=await wu("Deploy method",["rsync","git"],"rsync"),p="",g=[],m="";if(f==="rsync"){p=await kt("Local path to sync (e.g. dist/ or ./build)","dist/");let k=await kt("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env");g=k?k.split(",").map(x=>x.trim()).filter(Boolean):[]}else m=await kt("Branch to pull (leave empty for current remote branch)","main");let h=await kt(f==="git"?"Remote repo path (e.g. /home/deploy/my-app)":"Remote destination path (e.g. /var/www/app)");if(!h){console.log(`${de.red} Remote path is required.${de.reset}`);continue}let y=await kt("Command to run on remote after deploy (leave empty to skip)",""),b=await kt("Health check URL or remote command (leave empty to skip)",""),S={server:d,method:f,remote_path:h};f==="rsync"?(S.local_path=p,g.length>0&&(S.exclude=g)):m&&(S.branch=m),y&&(S.deploy_script=y),b&&(S.health_check=b),c[u]=S;let C=f==="git"?`${d}:${h}${m?` (${m})`:""}`:`${p.endsWith("/")?p:p+"/"} \u2192 ${d}:${h}`;console.log(`
|
|
1387
|
+
${de.green}\u2713${de.reset} Deploy config "${u}": [${f}] ${C}`),y&&console.log(` ${de.dim} Then: ${y}${de.reset}`),b&&console.log(` ${de.dim} Health: ${b}${de.reset}`),l=await ko(`
|
|
1388
|
+
Add another deploy config?`,!1)}St.existsSync(n)||St.mkdirSync(n,{recursive:!0}),St.writeFileSync(s,JSON.stringify(c,null,2)+`
|
|
1385
1389
|
`,"utf-8"),console.log(`
|
|
1386
1390
|
${de.green}\u2713 Saved .nex/deploy.json (${Object.keys(c).length} config${Object.keys(c).length!==1?"s":""})${de.reset}`),console.log(`${de.dim}Use: deploy prod (or with explicit params)${de.reset}
|
|
1387
|
-
`)}
|
|
1388
|
-
`);return`${
|
|
1391
|
+
`)}s$.exports={runServerWizard:pT,runDeployWizard:n$,setWizardRL:fT}});var To=oe((lC,a$)=>{"use strict";var Na=require("os"),qr=require("path"),ft=require("fs"),mT=require("axios"),hT=require("https"),Aa=qr.join(Na.homedir(),".nex-code","known-models.json"),gT="https://ollama.com/api/tags",$T=60,yT={"qwen3-coder:480b":131072,"devstral-2:123b":131072,"devstral-small-2:24b":131072,"kimi-k2:1t":262144,"kimi-k2.5":262144,"kimi-k2-thinking":262144,"minimax-m2.7:cloud":2e5,"minimax-m2.7":2e5,"minimax-m2.5":131072,"minimax-m2.1":2e5,"minimax-m2":2e5,"qwen3.5:397b":262144,"qwen3.5:35b-a3b":262144,"deepseek-v3.2":131072,"deepseek-v3.1:671b":131072,"cogito-2.1:671b":131072,"glm-5":128e3,"glm-5:cloud":128e3,"glm-4.7":128e3,"glm-4.6":128e3,"qwen3-vl:235b":131072,"qwen3-vl:235b-instruct":131072,"qwen3-coder-next":262144,"qwen3-next:80b":131072,"mistral-large-3:675b":131072,"ministral-3:14b":131072,"ministral-3:8b":131072,"ministral-3:3b":32768,"nemotron-3-nano:30b":131072,"nemotron-3-super":262144,"rnj-1:8b":131072,"gpt-oss:120b":131072,"gpt-oss:20b":131072,"gemma3:4b":131072,"gemma3:12b":131072,"gemma3:27b":131072,"gemini-3-flash-preview":131072};function bu(){try{if(ft.existsSync(Aa))return JSON.parse(ft.readFileSync(Aa,"utf-8"))}catch{}return{benchmarked:[],lastChecked:null}}function wT(t){let e=qr.dirname(Aa);ft.existsSync(e)||ft.mkdirSync(e,{recursive:!0}),ft.writeFileSync(Aa,JSON.stringify(t,null,2))}function bT(t){let e=bu(),n=new Set(e.benchmarked);for(let s of t)n.add(s);e.benchmarked=[...n],e.lastChecked=new Date().toISOString(),wT(e)}async function r$(){let t=process.env.OLLAMA_API_KEY;if(!t)throw new Error("OLLAMA_API_KEY not set");let e=new hT.Agent({keepAlive:!0});return((await mT.get(gT,{headers:{Authorization:`Bearer ${t}`},timeout:15e3,httpsAgent:e})).data?.models||[]).map(s=>(s.name||s.model||"").replace(/:latest$/,"")).filter(Boolean)}async function _T(){let t=await r$(),e=bu(),n=new Set(e.benchmarked),s=t.filter(o=>!n.has(o));return{allCloud:t,newModels:s,store:e}}var _u="<!-- nex-benchmark-start -->",Oa="<!-- nex-benchmark-end -->",xT={"qwen3-vl:235b":"Overall #1 \u2014 frontier tool selection, data + agentic tasks","qwen3-vl:235b-instruct":"Best latency/score balance \u2014 recommended default","devstral-2:123b":"Sysadmin + SSH tasks, reliable coding","devstral-small-2:24b":"Fast sub-agents, simple lookups","ministral-3:8b":"Fastest strong model \u2014 2.2s latency, 70+ score","qwen3-coder:480b":"Heavy coding sessions, large context","kimi-k2:1t":"Large repos (>100K tokens)","kimi-k2.5":"Large repos \u2014 faster than k2:1t","minimax-m2.7:cloud":"Complex swarm / multi-agent sessions","minimax-m2.5":"Multi-agent, large context","qwen3.5:35b-a3b":"Fast MoE with 256K context","gpt-oss:20b":"Fast small model, good overall score"};function vT(t){return t?t>=25e4?"256K":t>=19e4?"200K":t>=128e3?"131K":t>=64e3?"64K":`${Math.round(t/1024)}K`:"?"}function i$(t,e){let n=["\u{1F947}","\u{1F948}","\u{1F949}"],s=(e||new Date().toISOString()).split("T")[0],o=t.filter(r=>r.score>=$T).map((r,i)=>{let c=n[i]||"\u2014",l=vT(yT[r.model]),u=xT[r.model]||"\u2014",d=`${(r.avgLatency/1e3).toFixed(1)}s`,f=i===0?`**${r.score}**`:String(r.score);return`| ${c} | \`${r.model}\` | ${f} | ${d} | ${l} | ${u} |`}).join(`
|
|
1392
|
+
`);return`${_u}
|
|
1389
1393
|
<!-- Updated: ${s} \u2014 run \`/benchmark --discover\` after new Ollama Cloud releases -->
|
|
1390
1394
|
|
|
1391
1395
|
| Rank | Model | Score | Avg Latency | Context | Best For |
|
|
@@ -1394,21 +1398,21 @@ ${o}
|
|
|
1394
1398
|
|
|
1395
1399
|
> Rankings are nex-code-specific: tool name accuracy, argument validity, schema compliance.
|
|
1396
1400
|
> Toolathon (Minimax SOTA) measures different task types \u2014 run \`/benchmark --discover\` after model releases.
|
|
1397
|
-
${
|
|
1401
|
+
${Oa}`}function ST(t,e){if(!ft.existsSync(e))return!1;let n=ft.readFileSync(e,"utf-8"),s=n.indexOf(_u),o=n.indexOf(Oa);if(s===-1||o===-1)return!1;let r=n.slice(0,s),i=n.slice(o+Oa.length),c=i$(t);return ft.writeFileSync(e,r+c+i),!0}function kT(t){let e=qr.join(Na.homedir(),".nex-code","models.env");if(!ft.existsSync(e)||t.length===0)return{updated:!1,reason:"models.env not found or empty summary"};let n=t[0],s=ft.readFileSync(e,"utf-8"),r=s.match(/^DEFAULT_MODEL=(\S+)/m)?.[1];if(r===n.model)return{updated:!1,reason:"winner unchanged"};let i=t.find(l=>l.model===r);if(i&&n.score-i.score<5)return{updated:!1,reason:`margin ${(n.score-i.score).toFixed(1)}pts < 5pts threshold`};let c=new Date().toISOString().split("T")[0];return s=s.replace(/^DEFAULT_MODEL=\S+/m,`DEFAULT_MODEL=${n.model}`).replace(/^# Last reviewed:.*$/m,`# Last reviewed: ${c} (after /benchmark, ${n.model} wins nex-code tasks)`),ft.writeFileSync(e,s),{updated:!0,previousModel:r,newModel:n.model}}function ET(t){let{saveRoutingConfig:e}=Kn(),n=qr.join(Na.homedir(),".nex-code","models.env"),s=[],o=Object.entries(t).filter(([,c])=>c.score>0);if(o.length===0)return{saved:!1,envUpdated:!1,changes:[]};let r={};for(let[c,l]of o)r[c]=l.model,s.push(`${c}: ${l.model} (${l.score}/100)`);e(r);let i=!1;if(ft.existsSync(n)){let c=ft.readFileSync(n,"utf-8"),u=Object.entries({coding:"NEX_ROUTE_CODING",frontend:"NEX_ROUTE_FRONTEND",sysadmin:"NEX_ROUTE_SYSADMIN",data:"NEX_ROUTE_DATA",agentic:"NEX_ROUTE_AGENTIC"}).filter(([p])=>t[p]&&t[p].score>0).map(([p,g])=>`${g}=${t[p].model} # ${p} score: ${t[p].score}/100`).join(`
|
|
1398
1402
|
`),d="# \u2500\u2500 Task-type routing (auto-updated by /benchmark) \u2500\u2500",f="# \u2500\u2500 end routing \u2500\u2500";if(c.includes(d)){let p=c.indexOf(d),g=c.indexOf(f);g!==-1&&(c=c.slice(0,p)+`${d}
|
|
1399
1403
|
${u}
|
|
1400
1404
|
${f}`+c.slice(g+f.length))}else c+=`
|
|
1401
1405
|
${d}
|
|
1402
1406
|
${u}
|
|
1403
1407
|
${f}
|
|
1404
|
-
`;
|
|
1408
|
+
`;ft.writeFileSync(n,c),i=!0}return{saved:!0,envUpdated:i,changes:s}}var TT=/thinking|reasoning|instruct|planner|orchestrat/i;function RT(t){return TT.test(t)}function CT(t){if(!t||t.length===0)return{updated:!1};let e=qr.join(Na.homedir(),".nex-code","models.env");if(!ft.existsSync(e))return{updated:!1};let n=ft.readFileSync(e,"utf-8"),s=n.match(/^NEX_ORCHESTRATOR_MODEL=(.+)$/m),o=s?s[1].trim():null,i=[...t].sort((d,f)=>f.overall-d.overall)[0],c=o?t.find(d=>d.model===o):null,l=c?c.overall:0;if(i.model===o)return{updated:!1};if(l>0&&i.overall<l*1.05)return{updated:!1};let u=`NEX_ORCHESTRATOR_MODEL=${i.model}`;return s?n=n.replace(/^NEX_ORCHESTRATOR_MODEL=.+$/m,u):n+=`
|
|
1405
1409
|
${u}
|
|
1406
|
-
`,dt.writeFileSync(e,n),{updated:!0,previousModel:o,newModel:i.model}}Jg.exports={findNewModels:sT,fetchCloudModels:Xg,loadKnownModels:$u,markBenchmarked:nT,updateReadme:iT,updateModelsEnv:aT,updateRoutingConfig:cT,generateBenchmarkBlock:Vg,checkOrchestratorCandidate:uT,updateOrchestratorModel:dT,SENTINEL_START:yu,SENTINEL_END:Ra}});var Jn=ne((jR,a$)=>{"use strict";var{C:G}=Ke(),fT=Be(),{TOOL_DEFINITIONS:Zg}=Zt(),{saveRoutingConfig:pT}=Hn(),_u=[{id:"read-package",category:"file-ops",prompt:"Read the file package.json and show me its contents.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"write-file",category:"file-ops",prompt:'Create a file at /tmp/nex-bench-test.txt with the content "benchmark run".',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&typeof t.content=="string"},{id:"edit-file",category:"file-ops",prompt:'In the file src/config.js, replace the string "debug: false" with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.old_string!==void 0&&t.new_string!==void 0||t.path&&Array.isArray(t.patches)&&t.patches.length>0)},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".js")},{id:"read-partial",category:"file-ops",prompt:"Read only lines 20 to 40 of src/index.js \u2014 I need to see that specific range.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("index")&&(typeof t.line_start=="number"||typeof t.start_line=="number")},{id:"glob-ts-defs",category:"file-ops",prompt:"Find all TypeScript type definition files (*.d.ts) anywhere in the project.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".d.ts")},{id:"write-gitignore",category:"file-ops",prompt:"Create a .gitignore file at the project root that ignores node_modules/ and dist/.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".gitignore")&&typeof t.content=="string"&&t.content.includes("node_modules")},{id:"edit-version-bump",category:"file-ops",prompt:'In package.json, change the version field from "1.0.0" to "1.1.0".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.path.includes("package"))},{id:"grep-with-filter",category:"search",prompt:"Search for all calls to require() but only inside .js files in the cli/ directory.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("require")},{id:"no-tool-http-port",category:"reasoning",prompt:"What is the default port used by the HTTP protocol?",expectedTool:null,validateArgs:()=>!0},{id:"bash-node-version",category:"shell",prompt:"Check which version of Node.js is currently installed on this system.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("node")&&(t.command.includes("--version")||t.command.includes("-v"))},{id:"search-constant",category:"search",prompt:'Search for the string "DEFAULT_MODEL" across all files in the project.',expectedTool:["search_files","grep"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("DEFAULT_MODEL")},{id:"grep-function-def",category:"search",prompt:'Find where the function "callStream" is defined in the codebase.',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:t=>JSON.stringify(t).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git")},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git status")},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let n=e?.function?.parameters||{},s=n.required||[],o=Object.keys(n.properties||{});return s.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>o.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"What is the current version of this project? Check the source files.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"multi-step-count",category:"multi-step",prompt:"How many JavaScript files are in the cli/ directory? Count them.",expectedTool:["bash","glob","list_directory"],validateArgs:t=>!!(typeof t.command=="string"&&t.command.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli")||typeof t.path=="string"&&t.path.includes("cli"))},{id:"no-tool-reasoning",category:"reasoning",prompt:'What does the acronym "API" stand for?',expectedTool:null,validateArgs:()=>!0},{id:"frontend-find-hook",category:"frontend",prompt:"Find all files that import useState from React.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("useState")},{id:"frontend-create-component",category:"frontend",prompt:"Create a React functional component called Button that accepts a label prop and renders a styled button element. Save it to src/components/Button.jsx.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".jsx")||t.path.includes(".tsx")||t.path.includes(".js"))&&typeof t.content=="string"},{id:"frontend-edit-css",category:"frontend",prompt:'In the file src/styles.css, change the background-color value from "blue" to "red".',expectedTool:["edit_file","patch_file"],validateArgs:t=>t.path&&t.old_string!==void 0?t.path.includes(".css")||t.old_string.includes("blue")||t.old_string.includes("background"):!!(t.path&&Array.isArray(t.patches))},{id:"frontend-glob-components",category:"frontend",prompt:"Find all JSX and TSX component files in the components/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&(t.pattern.includes(".jsx")||t.pattern.includes(".tsx")||t.pattern.includes("{jsx,tsx}"))},{id:"frontend-list-assets",category:"frontend",prompt:"List all files in the src/assets/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("assets")||typeof t.pattern=="string"&&t.pattern.includes("assets"))},{id:"sysadmin-port-check",category:"sysadmin",prompt:"Which process is currently listening on port 3000?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("lsof")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("3000"))},{id:"sysadmin-nginx-config",category:"sysadmin",prompt:"Create an nginx server block that proxies requests to localhost:3000. Save it to /etc/nginx/sites-available/myapp.",expectedTool:["write_file","bash"],validateArgs:t=>!!(t.path&&(t.path.includes("nginx")||t.path.includes("sites-available"))||t.command&&t.command.includes("nginx"))},{id:"sysadmin-service-status",category:"sysadmin",prompt:"Check the status of the nginx service and show if it is running.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("systemctl")||t.command.includes("service")||t.command.includes("nginx"))},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("journalctl")||t.command.includes("nginx"))},{id:"sysadmin-docker-compose",category:"sysadmin",prompt:"Create a docker-compose.yml file for a Node.js application with a PostgreSQL database.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("docker-compose")&&typeof t.content=="string"},{id:"data-sql-query",category:"data",prompt:"Write a SQL query to find all users who have not logged in for more than 30 days. Save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".sql")||t.path.includes("quer"))&&typeof t.content=="string"},{id:"data-find-json-key",category:"data",prompt:'Find all JSON files in the project that contain the key "userId".',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("userId")},{id:"data-python-csv",category:"data",prompt:'Write a Python script that reads data.csv and calculates the average of the "price" column. Save it to scripts/average_price.py.',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".py")&&typeof t.content=="string"},{id:"data-find-migrations",category:"data",prompt:"Find all database migration files in this project.",expectedTool:["glob","search_files","grep"],validateArgs:t=>JSON.stringify(t).toLowerCase().includes("migrat")},{id:"data-find-schema",category:"data",prompt:"Find where the database schema or models are defined in this project.",expectedTool:["grep","glob"],validateArgs:t=>!!(t.pattern&&/schema|model|migration/i.test(t.pattern)||t.pattern&&/schema|model|migration/i.test(t.pattern))},{id:"data-write-query",category:"data",prompt:"Write a SQL query to find all users who registered in the last 30 days and save it to queries/recent-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".sql")},{id:"data-read-env",category:"data",prompt:"Read the .env file to find the database connection string.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/\.env|env\./i.test(t.path)},{id:"resilience-edit-failed",category:"resilience",prompt:"Your edit_file call on server.js failed: old_string 'const PORT = 3000' was not found in the file. What do you do next to recover?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("server")},{id:"resilience-file-not-found",category:"resilience",prompt:"read_file returned 'file not found' for src/utils/helpers.js. You need to find where the helper functions are now. What tool do you use?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("src")||e.includes("helper")||e.includes("util")||e.includes("*.js")}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. What is the most efficient tool to use \u2014 read_file or bash with grep?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("awk"))},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. What tool do you use to find the new location?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("config")||e.includes("*.ts")||e.includes("*.js")||e.includes("find")}},{id:"resilience-bash-error-recover",category:"resilience",prompt:"The command 'npm test' failed with exit code 1. The output contains 'SyntaxError: Unexpected token' in src/parser.js:45. What is your next action?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("parser")},{id:"resilience-grep-no-match",category:"resilience",prompt:"grep returned zero matches for 'getUserById' in src/. The function exists but may have been renamed. What bash command finds all exported function names in src/ to identify the current name?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("src"))},{id:"ssh-exec-log",category:"ssh",prompt:'Show the last 50 lines of /var/log/nginx/error.log on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("log"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-service",category:"ssh",prompt:'Restart the nginx service on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("nginx")||t.command.includes("systemctl")||t.command.includes("restart"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-port",category:"ssh",prompt:'Check if port 8080 is listening on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("8080")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("lsof"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-processes",category:"ssh",prompt:'Show the top CPU-consuming processes on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("top")||t.command.includes("ps")||t.command.includes("htop"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"git-diff-staged",category:"git",prompt:"Show all staged changes before committing.",expectedTool:["git_diff","bash"],validateArgs:t=>!!(t.staged===!0||t.staged==="true"||typeof t.command=="string"&&t.command.includes("diff"))},{id:"git-log-recent",category:"git",prompt:"Show the last 5 commit messages with their hashes.",expectedTool:["git_log","bash"],validateArgs:t=>!!(typeof t.limit=="number"||typeof t.n=="number"||typeof t.command=="string"&&t.command.includes("log"))},{id:"git-status-check",category:"git",prompt:"Check if there are any uncommitted changes in the repository.",expectedTool:["git_status","bash"],validateArgs:t=>t.path===void 0&&t.command===void 0?!1:(typeof t.command=="string"&&t.command.includes("status"),!0)},{id:"agentic-test-first",category:"agentic",prompt:"Run the full test suite. If any tests fail, identify the failing test file and read it to understand the issue.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("test")||t.command.includes("jest")||t.command.includes("npm"))},{id:"agentic-read-then-act",category:"agentic",prompt:"Read the project README.md, find the TODO section, and list which items are completed.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("README")},{id:"agentic-build-deploy",category:"agentic",prompt:"Build the project with npm run build, then verify the output exists in the dist/ directory.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("build")||t.command.includes("npm"))},{id:"agentic-spawn-parallel",category:"agentic",prompt:"Search for all TODO comments and all FIXME comments across the codebase in parallel using multiple agents.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2},{id:"agentic-multi-investigate",category:"agentic",prompt:"The app is crashing on startup. Spawn parallel agents to check: (1) recent git changes, (2) npm dependency issues, (3) the main entry file for syntax errors.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2}],Qg=[{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)}],Na=[..._u,...Qg],wu=["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 mT(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return wu;let s=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(s)||s.length===0?wu:s.filter(o=>typeof o.score=="number"&&o.score>=60).sort((o,r)=>r.score-o.score).slice(0,12).map(o=>o.model)}catch{return wu}}var xu=mT(),hT=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],e$=(()=>{let t=xu.slice(0,3);return t.length>=3?t:hT})(),gT=14,Aa={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},$T="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 bu(t,e){let n={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},s=[{role:"system",content:$T},{role:"user",content:t.prompt}],o=Date.now();try{let r=await fT.callChat(s,Zg,{provider:"ollama",model:e,temperature:0,timeout:9e4});n.latencyMs=Date.now()-o;let i=r.tool_calls||[];if(t.expectedTool===null){let c=i.length===0;n.producedToolCall=c,n.correctTool=c,n.validArgs=!0,n.schemaCompliant=!0}else if(i.length>0){let c=i[0],l=c.function?.name||"unknown",u=c.function?.arguments||{};n.producedToolCall=!0,n.toolCalled=l;let d=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(n.correctTool=d.includes(l),n.correctTool){let f=Zg.find(p=>p.function?.name===l);if(n.validArgs=!!t.validateArgs(u,f),f){let p=f.function?.parameters||{},g=p.required||[],m=Object.keys(p.properties||{});n.schemaCompliant=g.every(h=>u[h]!==void 0)&&Object.keys(u).every(h=>m.includes(h))}}}}catch(r){n.latencyMs=Date.now()-o,n.error=r.message.slice(0,120)}return n}function To(t){return t.error?0:((t.producedToolCall?Aa.producedToolCall:0)+(t.correctTool?Aa.correctTool:0)+(t.validArgs?Aa.validArgs:0)+(t.schemaCompliant?Aa.schemaCompliant:0))*100}var t$={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 vu(t){return Object.entries(t).map(([e,n])=>{let s=n.map(To),o=s.reduce((c,l)=>c+l,0)/s.length,r=c=>Math.round(n.filter(c).length/n.length*100),i={};for(let c of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let l=n.filter(d=>t$[d.category]===c);if(l.length===0)continue;let u=l.map(To).reduce((d,f)=>d+f,0)/l.length;i[c]=Math.round(u*10)/10}return{model:e,score:Math.round(o*10)/10,toolCallRate:r(c=>!c.error&&(c.producedToolCall||c.category==="reasoning")),correctRate:r(c=>c.correctTool),validArgsRate:r(c=>c.validArgs),schemaRate:r(c=>c.schemaCompliant),avgLatency:Math.round(n.reduce((c,l)=>c+l.latencyMs,0)/n.length),errorCount:n.filter(c=>c.error).length,categoryScores:i,results:n}}).sort((e,n)=>n.score-e.score)}function n$(t){let e={};for(let c of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let l=t.filter(h=>h.categoryScores[c]!==void 0&&h.score>=65).sort((h,y)=>y.categoryScores[c]-h.categoryScores[c]);if(l.length===0)continue;let d=(l[0]?.results||[]).filter(h=>t$[h.category]===c).length;if(d<4)continue;let f=l[0],p=l[1];if(f.categoryScores[c]>=95&&d<8&&p&&f.categoryScores[c]-p.categoryScores[c]<15){let y=t.filter(w=>w.categoryScores[c]!==void 0).find(w=>w.categoryScores[c]<95);y&&(e[c]={model:y.model,score:y.categoryScores[c],avgLatency:y.avgLatency,_flukePrevented:!0});continue}let m=l.filter(h=>f.categoryScores[c]-h.categoryScores[c]<=5).sort((h,y)=>h.avgLatency-y.avgLatency)[0];e[c]={model:m.model,score:m.categoryScores[c],avgLatency:m.avgLatency}}return e}function s$(t,e){let n=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,s=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],o=s.reduce((d,f)=>d+f.width+1,0)+1,r="\u2500".repeat(o);console.log(`
|
|
1407
|
-
${
|
|
1408
|
-
${
|
|
1409
|
-
${
|
|
1410
|
-
${
|
|
1411
|
-
${
|
|
1410
|
+
`,ft.writeFileSync(e,n),{updated:!0,previousModel:o,newModel:i.model}}a$.exports={findNewModels:_T,fetchCloudModels:r$,loadKnownModels:bu,markBenchmarked:bT,updateReadme:ST,updateModelsEnv:kT,updateRoutingConfig:ET,generateBenchmarkBlock:i$,checkOrchestratorCandidate:RT,updateOrchestratorModel:CT,SENTINEL_START:_u,SENTINEL_END:Oa}});var Zn=oe((uC,$$)=>{"use strict";var{C:z}=Ke(),AT=Be(),{TOOL_DEFINITIONS:c$}=en(),{saveRoutingConfig:OT}=Kn(),Su=[{id:"read-package",category:"file-ops",prompt:"Read the file package.json and show me its contents.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"write-file",category:"file-ops",prompt:'Create a file at /tmp/nex-bench-test.txt with the content "benchmark run".',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&typeof t.content=="string"},{id:"edit-file",category:"file-ops",prompt:'In the file src/config.js, replace the string "debug: false" with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.old_string!==void 0&&t.new_string!==void 0||t.path&&Array.isArray(t.patches)&&t.patches.length>0)},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".js")},{id:"read-partial",category:"file-ops",prompt:"Read only lines 20 to 40 of src/index.js \u2014 I need to see that specific range.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("index")&&(typeof t.line_start=="number"||typeof t.start_line=="number")},{id:"glob-ts-defs",category:"file-ops",prompt:"Find all TypeScript type definition files (*.d.ts) anywhere in the project.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".d.ts")},{id:"write-gitignore",category:"file-ops",prompt:"Create a .gitignore file at the project root that ignores node_modules/ and dist/.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".gitignore")&&typeof t.content=="string"&&t.content.includes("node_modules")},{id:"edit-version-bump",category:"file-ops",prompt:'In package.json, change the version field from "1.0.0" to "1.1.0".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.path.includes("package"))},{id:"grep-with-filter",category:"search",prompt:"Search for all calls to require() but only inside .js files in the cli/ directory.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("require")},{id:"no-tool-http-port",category:"reasoning",prompt:"What is the default port used by the HTTP protocol?",expectedTool:null,validateArgs:()=>!0},{id:"bash-node-version",category:"shell",prompt:"Check which version of Node.js is currently installed on this system.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("node")&&(t.command.includes("--version")||t.command.includes("-v"))},{id:"search-constant",category:"search",prompt:'Search for the string "DEFAULT_MODEL" across all files in the project.',expectedTool:["search_files","grep"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("DEFAULT_MODEL")},{id:"grep-function-def",category:"search",prompt:'Find where the function "callStream" is defined in the codebase.',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:t=>JSON.stringify(t).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git")},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git status")},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let n=e?.function?.parameters||{},s=n.required||[],o=Object.keys(n.properties||{});return s.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>o.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"What is the current version of this project? Check the source files.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"multi-step-count",category:"multi-step",prompt:"How many JavaScript files are in the cli/ directory? Count them.",expectedTool:["bash","glob","list_directory"],validateArgs:t=>!!(typeof t.command=="string"&&t.command.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli")||typeof t.path=="string"&&t.path.includes("cli"))},{id:"no-tool-reasoning",category:"reasoning",prompt:'What does the acronym "API" stand for?',expectedTool:null,validateArgs:()=>!0},{id:"frontend-find-hook",category:"frontend",prompt:"Find all files that import useState from React.",expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("useState")},{id:"frontend-create-component",category:"frontend",prompt:"Create a React functional component called Button that accepts a label prop and renders a styled button element. Save it to src/components/Button.jsx.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".jsx")||t.path.includes(".tsx")||t.path.includes(".js"))&&typeof t.content=="string"},{id:"frontend-edit-css",category:"frontend",prompt:'In the file src/styles.css, change the background-color value from "blue" to "red".',expectedTool:["edit_file","patch_file"],validateArgs:t=>t.path&&t.old_string!==void 0?t.path.includes(".css")||t.old_string.includes("blue")||t.old_string.includes("background"):!!(t.path&&Array.isArray(t.patches))},{id:"frontend-glob-components",category:"frontend",prompt:"Find all JSX and TSX component files in the components/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&(t.pattern.includes(".jsx")||t.pattern.includes(".tsx")||t.pattern.includes("{jsx,tsx}"))},{id:"frontend-list-assets",category:"frontend",prompt:"List all files in the src/assets/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("assets")||typeof t.pattern=="string"&&t.pattern.includes("assets"))},{id:"sysadmin-port-check",category:"sysadmin",prompt:"Which process is currently listening on port 3000?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("lsof")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("3000"))},{id:"sysadmin-nginx-config",category:"sysadmin",prompt:"Create an nginx server block that proxies requests to localhost:3000. Save it to /etc/nginx/sites-available/myapp.",expectedTool:["write_file","bash"],validateArgs:t=>!!(t.path&&(t.path.includes("nginx")||t.path.includes("sites-available"))||t.command&&t.command.includes("nginx"))},{id:"sysadmin-service-status",category:"sysadmin",prompt:"Check the status of the nginx service and show if it is running.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("systemctl")||t.command.includes("service")||t.command.includes("nginx"))},{id:"sysadmin-error-log",category:"sysadmin",prompt:"Show the last 100 lines of the nginx error log.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("journalctl")||t.command.includes("nginx"))},{id:"sysadmin-docker-compose",category:"sysadmin",prompt:"Create a docker-compose.yml file for a Node.js application with a PostgreSQL database.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("docker-compose")&&typeof t.content=="string"},{id:"data-sql-query",category:"data",prompt:"Write a SQL query to find all users who have not logged in for more than 30 days. Save it to queries/inactive-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&(t.path.includes(".sql")||t.path.includes("quer"))&&typeof t.content=="string"},{id:"data-find-json-key",category:"data",prompt:'Find all JSON files in the project that contain the key "userId".',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("userId")},{id:"data-python-csv",category:"data",prompt:'Write a Python script that reads data.csv and calculates the average of the "price" column. Save it to scripts/average_price.py.',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".py")&&typeof t.content=="string"},{id:"data-find-migrations",category:"data",prompt:"Find all database migration files in this project.",expectedTool:["glob","search_files","grep"],validateArgs:t=>JSON.stringify(t).toLowerCase().includes("migrat")},{id:"data-find-schema",category:"data",prompt:"Find where the database schema or models are defined in this project.",expectedTool:["grep","glob"],validateArgs:t=>!!(t.pattern&&/schema|model|migration/i.test(t.pattern)||t.pattern&&/schema|model|migration/i.test(t.pattern))},{id:"data-write-query",category:"data",prompt:"Write a SQL query to find all users who registered in the last 30 days and save it to queries/recent-users.sql.",expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes(".sql")},{id:"data-read-env",category:"data",prompt:"Read the .env file to find the database connection string.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&/\.env|env\./i.test(t.path)},{id:"resilience-edit-failed",category:"resilience",prompt:"Your edit_file call on server.js failed: old_string 'const PORT = 3000' was not found in the file. What do you do next to recover?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("server")},{id:"resilience-file-not-found",category:"resilience",prompt:"read_file returned 'file not found' for src/utils/helpers.js. You need to find where the helper functions are now. What tool do you use?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("src")||e.includes("helper")||e.includes("util")||e.includes("*.js")}},{id:"resilience-large-file-nav",category:"resilience",prompt:"The file src/api.js is 2800 lines. You need to locate the authenticateUser function. What is the most efficient tool to use \u2014 read_file or bash with grep?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("awk"))},{id:"resilience-broken-import",category:"resilience",prompt:"TypeScript reports: Cannot find module './config'. The file was recently renamed. What tool do you use to find the new location?",expectedTool:["glob_files","bash"],validateArgs:t=>{let e=JSON.stringify(t).toLowerCase();return e.includes("config")||e.includes("*.ts")||e.includes("*.js")||e.includes("find")}},{id:"resilience-bash-error-recover",category:"resilience",prompt:"The command 'npm test' failed with exit code 1. The output contains 'SyntaxError: Unexpected token' in src/parser.js:45. What is your next action?",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("parser")},{id:"resilience-grep-no-match",category:"resilience",prompt:"grep returned zero matches for 'getUserById' in src/. The function exists but may have been renamed. What bash command finds all exported function names in src/ to identify the current name?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("grep")||t.command.includes("rg")||t.command.includes("src"))},{id:"ssh-exec-log",category:"ssh",prompt:'Show the last 50 lines of /var/log/nginx/error.log on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("tail")||t.command.includes("log"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-service",category:"ssh",prompt:'Restart the nginx service on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("nginx")||t.command.includes("systemctl")||t.command.includes("restart"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-port",category:"ssh",prompt:'Check if port 8080 is listening on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("8080")||t.command.includes("ss")||t.command.includes("netstat")||t.command.includes("lsof"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"ssh-exec-processes",category:"ssh",prompt:'Show the top CPU-consuming processes on server "prod-1".',expectedTool:"ssh_exec",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("top")||t.command.includes("ps")||t.command.includes("htop"))&&(typeof t.host=="string"||typeof t.profile=="string")},{id:"git-diff-staged",category:"git",prompt:"Show all staged changes before committing.",expectedTool:["git_diff","bash"],validateArgs:t=>!!(t.staged===!0||t.staged==="true"||typeof t.command=="string"&&t.command.includes("diff"))},{id:"git-log-recent",category:"git",prompt:"Show the last 5 commit messages with their hashes.",expectedTool:["git_log","bash"],validateArgs:t=>!!(typeof t.limit=="number"||typeof t.n=="number"||typeof t.command=="string"&&t.command.includes("log"))},{id:"git-status-check",category:"git",prompt:"Check if there are any uncommitted changes in the repository.",expectedTool:["git_status","bash"],validateArgs:t=>t.path===void 0&&t.command===void 0?!1:(typeof t.command=="string"&&t.command.includes("status"),!0)},{id:"agentic-test-first",category:"agentic",prompt:"Run the full test suite. If any tests fail, identify the failing test file and read it to understand the issue.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("test")||t.command.includes("jest")||t.command.includes("npm"))},{id:"agentic-read-then-act",category:"agentic",prompt:"Read the project README.md, find the TODO section, and list which items are completed.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("README")},{id:"agentic-build-deploy",category:"agentic",prompt:"Build the project with npm run build, then verify the output exists in the dist/ directory.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&(t.command.includes("build")||t.command.includes("npm"))},{id:"agentic-spawn-parallel",category:"agentic",prompt:"Search for all TODO comments and all FIXME comments across the codebase in parallel using multiple agents.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2},{id:"agentic-multi-investigate",category:"agentic",prompt:"The app is crashing on startup. Spawn parallel agents to check: (1) recent git changes, (2) npm dependency issues, (3) the main entry file for syntax errors.",expectedTool:"spawn_agents",validateArgs:t=>Array.isArray(t.agents)&&t.agents.length>=2}],l$=[{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)}],La=[...Su,...l$],xu=["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 NT(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return xu;let s=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(s)||s.length===0?xu:s.filter(o=>typeof o.score=="number"&&o.score>=60).sort((o,r)=>r.score-o.score).slice(0,12).map(o=>o.model)}catch{return xu}}var ku=NT(),MT=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],u$=(()=>{let t=ku.slice(0,3);return t.length>=3?t:MT})(),PT=14,Ma={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},LT="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 vu(t,e){let n={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},s=[{role:"system",content:LT},{role:"user",content:t.prompt}],o=Date.now();try{let r=await AT.callChat(s,c$,{provider:"ollama",model:e,temperature:0,timeout:9e4});n.latencyMs=Date.now()-o;let i=r.tool_calls||[];if(t.expectedTool===null){let c=i.length===0;n.producedToolCall=c,n.correctTool=c,n.validArgs=!0,n.schemaCompliant=!0}else if(i.length>0){let c=i[0],l=c.function?.name||"unknown",u=c.function?.arguments||{};n.producedToolCall=!0,n.toolCalled=l;let d=Array.isArray(t.expectedTool)?t.expectedTool:[t.expectedTool];if(n.correctTool=d.includes(l),n.correctTool){let f=c$.find(p=>p.function?.name===l);if(n.validArgs=!!t.validateArgs(u,f),f){let p=f.function?.parameters||{},g=p.required||[],m=Object.keys(p.properties||{});n.schemaCompliant=g.every(h=>u[h]!==void 0)&&Object.keys(u).every(h=>m.includes(h))}}}}catch(r){n.latencyMs=Date.now()-o,n.error=r.message.slice(0,120)}return n}function Ro(t){return t.error?0:((t.producedToolCall?Ma.producedToolCall:0)+(t.correctTool?Ma.correctTool:0)+(t.validArgs?Ma.validArgs:0)+(t.schemaCompliant?Ma.schemaCompliant:0))*100}var d$={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 Eu(t){return Object.entries(t).map(([e,n])=>{let s=n.map(Ro),o=s.reduce((c,l)=>c+l,0)/s.length,r=c=>Math.round(n.filter(c).length/n.length*100),i={};for(let c of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let l=n.filter(d=>d$[d.category]===c);if(l.length===0)continue;let u=l.map(Ro).reduce((d,f)=>d+f,0)/l.length;i[c]=Math.round(u*10)/10}return{model:e,score:Math.round(o*10)/10,toolCallRate:r(c=>!c.error&&(c.producedToolCall||c.category==="reasoning")),correctRate:r(c=>c.correctTool),validArgsRate:r(c=>c.validArgs),schemaRate:r(c=>c.schemaCompliant),avgLatency:Math.round(n.reduce((c,l)=>c+l.latencyMs,0)/n.length),errorCount:n.filter(c=>c.error).length,categoryScores:i,results:n}}).sort((e,n)=>n.score-e.score)}function f$(t){let e={};for(let c of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let l=t.filter(h=>h.categoryScores[c]!==void 0&&h.score>=65).sort((h,y)=>y.categoryScores[c]-h.categoryScores[c]);if(l.length===0)continue;let d=(l[0]?.results||[]).filter(h=>d$[h.category]===c).length;if(d<4)continue;let f=l[0],p=l[1];if(f.categoryScores[c]>=95&&d<8&&p&&f.categoryScores[c]-p.categoryScores[c]<15){let y=t.filter(b=>b.categoryScores[c]!==void 0).find(b=>b.categoryScores[c]<95);y&&(e[c]={model:y.model,score:y.categoryScores[c],avgLatency:y.avgLatency,_flukePrevented:!0});continue}let m=l.filter(h=>f.categoryScores[c]-h.categoryScores[c]<=5).sort((h,y)=>h.avgLatency-y.avgLatency)[0];e[c]={model:m.model,score:m.categoryScores[c],avgLatency:m.avgLatency}}return e}function p$(t,e){let n=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,s=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],o=s.reduce((d,f)=>d+f.width+1,0)+1,r="\u2500".repeat(o);console.log(`
|
|
1411
|
+
${z.bold}${n}${z.reset}`),console.log(r);let i=s.map(d=>d.label.padEnd(d.width)).join(" ");if(console.log(`${z.dim}${i}${z.reset}`),console.log(r),t.forEach((d,f)=>{let p=String(f+1).padEnd(s[0].width),g=d.model.slice(0,s[1].width).padEnd(s[1].width),m=String(d.score).padEnd(s[2].width),h=`${d.toolCallRate}%`.padEnd(s[3].width),y=`${d.correctRate}%`.padEnd(s[4].width),b=`${d.validArgsRate}%`.padEnd(s[5].width),S=`${d.schemaRate}%`.padEnd(s[6].width),C=`${(d.avgLatency/1e3).toFixed(1)}s`.padEnd(s[7].width),k=d.errorCount>0?`${z.red}${d.errorCount}${z.reset}`:`${z.dim}0${z.reset}`,x=d.score>=80?z.green:d.score>=60?z.yellow:z.red,E=f===0?`${z.yellow}${p}${z.reset}`:`${z.dim}${p}${z.reset}`;console.log(`${E} ${x}${g}${z.reset} ${z.bold}${x}${m}${z.reset} ${h} ${y} ${b} ${S} ${z.dim}${C}${z.reset} ${k}`)}),console.log(r),t.length>0){let d=t[0];if(console.log(`
|
|
1412
|
+
${z.bold}${z.green}Winner: ${d.model}${z.reset} score ${d.score}/100`),t.length>1){let f=(d.score-t[1].score).toFixed(1);console.log(`${z.dim}+${f} pts over ${t[1].model}${z.reset}`)}}let c=t.filter(d=>d.results.some(f=>!f.error&&(!f.correctTool||!f.validArgs)));if(c.length>0){console.log(`${z.bold}Failing tasks:${z.reset}`);for(let d of c){let f=d.results.filter(m=>!m.error&&(!m.correctTool||!m.validArgs));if(f.length===0)continue;let p=d.model.slice(0,22),g=f.map(m=>{if(!m.correctTool){let h=m.toolCalled||"(none)";return`${z.dim}${m.taskId}${z.reset} ${z.red}\u2192${h}${z.reset}`}return`${z.dim}${m.taskId}${z.reset} ${z.yellow}bad-args${z.reset}`});console.log(` ${z.dim}${p.padEnd(22)}${z.reset} ${g.join(" ")}`)}console.log()}let l=["coding","frontend","sysadmin","data","agentic"];if(t.some(d=>Object.keys(d.categoryScores).length>1)){console.log(`
|
|
1413
|
+
${z.bold}Best model per task type:${z.reset}`);for(let d of l){let f=t.filter(h=>h.categoryScores[d]!==void 0).sort((h,y)=>y.categoryScores[d]-h.categoryScores[d]);if(f.length===0)continue;let p=f[0],g=p.categoryScores[d],m=g>=80?z.green:g>=60?z.yellow:z.red;console.log(` ${z.dim}${d.padEnd(10)}${z.reset} ${m}${p.model}${z.reset} ${z.dim}${g}/100${z.reset}`)}}console.log()}function m$(t){if(!(!t||t.length<2))try{let e=f$(t),{loadRoutingConfig:n}=Kn(),s=n(),o={...s},r=[],i=new Set(["plan","verify"]);for(let[c,{model:l,score:u}]of Object.entries(e)){let d=i.has(c),f=d?s.phases&&s.phases[c]:s[c];f&&f!==l&&!t.find(g=>g.model===f)||(d?(o.phases||(o.phases={}),o.phases[c]!==l&&(o.phases[c]=l,r.push(`phase:${c}\u2192${l}`))):o[c]!==l&&(o[c]=l,r.push(`${c}\u2192${l}`)))}r.length>0&&(OT(o),console.log(`
|
|
1414
|
+
${z.dim} Routing updated: ${r.join(", ")}${z.reset}`),console.log(`
|
|
1415
|
+
${z.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will be automatically used by nex-code from now on.${z.reset}`))}catch{}}async function IT({models:t,quick:e=!1,onProgress:n,parallelModels:s=1}={}){let o=e?Su.slice(0,PT):La,r=t?.length>0?t:e?u$:ku,i={};for(let l of r)i[l]=[];if(s<=1)for(let l of r)for(let u of o){n?.({model:l,task:u.id,done:!1});let d=await vu(u,l);i[l].push(d),n?.({model:l,task:u.id,done:!0,score:Ro(d),error:d.error})}else{let l=Math.min(s,r.length),u=[...r],d=Array.from({length:l},async()=>{for(;u.length>0;){let f=u.shift();if(!f)break;for(let p of o){n?.({model:f,task:p.id,done:!1});let g=await vu(p,f);i[f].push(g),n?.({model:f,task:p.id,done:!0,score:Ro(g),error:g.error})}}});await Promise.all(d)}let c=Eu(i);return p$(c,o.length),m$(c),c}async function jT({newModels:t,existingRanking:e=[],onProgress:n}={}){if(!t||t.length===0)return e;let s={};for(let i of t){s[i]=[];for(let c of La){n?.({model:i,task:c.id,done:!1});let l=await vu(c,i);s[i].push(l),n?.({model:i,task:c.id,done:!0,score:Ro(l),error:l.error})}}let r=[...Eu(s)];for(let i of e)r.find(c=>c.model===i.model)||r.push(i);return r.sort((i,c)=>c.score-i.score),p$(r,La.length),m$(r),r}var Pa=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function h$(t){let e=require("fs"),s=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(s))return console.log(`${z.yellow}No scenarios configured.${z.reset} Create ${z.dim}.nex/benchmark-config.json${z.reset} to define your benchmark scenarios.
|
|
1412
1416
|
Example:
|
|
1413
1417
|
{
|
|
1414
1418
|
"scenarios": [
|
|
@@ -1421,28 +1425,28 @@ ${G.green}\u{1F4A1} The best models have been saved to ~/.nex-code/.env and will
|
|
|
1421
1425
|
}
|
|
1422
1426
|
]
|
|
1423
1427
|
}
|
|
1424
|
-
`),
|
|
1425
|
-
`),
|
|
1426
|
-
`),
|
|
1428
|
+
`),Pa;try{let o=JSON.parse(e.readFileSync(s,"utf-8"));return!Array.isArray(o.scenarios)||o.scenarios.length===0?(console.log(`${z.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${z.reset}
|
|
1429
|
+
`),Pa):o.scenarios}catch(o){return console.log(`${z.yellow}Failed to parse benchmark-config.json: ${o.message}${z.reset}
|
|
1430
|
+
`),Pa}}function g$(t,e){let{scoreMessages:n,_extractToolCalls:s,_getLastAssistantText:o}=ta(),r=n(t),i=r.score,c=[],l=o(t).toLowerCase();e.successCriteria.every(p=>l.includes(p.toLowerCase()))&&(i=Math.min(10,i+1),c.push("+1.0 all success criteria met"));let d=s(t);d.length<e.maxTurns/2&&(i=Math.min(10,i+.5),c.push(`+0.5 efficient (${d.length} tool calls < ${e.maxTurns/2})`)),i=Math.round(i*10)/10;let f=i>=9?"A":i>=8?"B":i>=7?"C":i>=6?"D":"F";return{score:i,grade:f,issues:r.issues,summary:r.summary,bonuses:c}}async function DT(t,e={}){let{spawn:n}=require("child_process"),s=require("fs"),o=require("path"),r=require("os"),i=o.join(r.tmpdir(),`nex-bench-${t.id}-${Date.now()}.txt`);s.writeFileSync(i,t.prompt,"utf-8");let c=o.resolve(__dirname,"..","bin","nex-code.js"),l=e.cwd||process.cwd(),u=[c,"--prompt-file",i,"--delete-prompt-file","--auto","--max-turns",String(t.maxTurns)];return e.model&&u.push("--model",e.model),new Promise(d=>{let f=n(process.execPath,u,{cwd:l,stdio:["ignore","pipe","pipe"],env:{...process.env}}),p=t.maxTurns*60*1e3,g=!1,m=setTimeout(()=>{g=!0;try{f.kill("SIGTERM")}catch{}},p);f.on("close",h=>{clearTimeout(m);try{s.unlinkSync(i)}catch{}let y=o.join(l,".nex","sessions","_autosave.json"),b=[];if(s.existsSync(y))try{b=JSON.parse(s.readFileSync(y,"utf-8")).messages||[]}catch{}d({messages:b,exitCode:h||0,timedOut:g})}),f.stdout.resume(),f.stderr.resume()})}function qT(t,e,n){let s=t.length>0?Math.round(t.reduce((l,u)=>l+u.score,0)/t.length*10)/10:0,o=s>=9?"A":s>=8?"B":s>=7?"C":s>=6?"D":"F",r=57,i="\u2500".repeat(r);console.log(`
|
|
1427
1431
|
\u250C\u2500 Benchmark Results ${"\u2500".repeat(r-19)}\u2510`);for(let l of t){let u=l.id.padEnd(20),d=l.name.substring(0,26).padEnd(26),f=`${l.score}/10`.padStart(6),p=l.grade.padStart(2);console.log(`\u2502 ${u} ${d} ${f} ${p} \u2502`)}console.log(`\u2502 ${" ".repeat(r-2)} \u2502`);let c=`Overall: ${s}/10 (${o}) \xB7 v${e} \xB7 ${n}`;console.log(`\u2502 ${c.substring(0,r-4).padEnd(r-4)} \u2502`),console.log(`\u2514${"\u2500".repeat(r+1)}\u2518
|
|
1428
|
-
`)}function
|
|
1429
|
-
`);return}let o=[];try{o=JSON.parse(e.readFileSync(s,"utf-8"))}catch{o=[]}if(!Array.isArray(o)||o.length===0){console.log(`${
|
|
1432
|
+
`)}function FT(t=10){let e=require("fs"),s=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(s)){console.log(`${z.yellow}No score history yet. Run a session first.${z.reset}
|
|
1433
|
+
`);return}let o=[];try{o=JSON.parse(e.readFileSync(s,"utf-8"))}catch{o=[]}if(!Array.isArray(o)||o.length===0){console.log(`${z.yellow}Score history is empty.${z.reset}
|
|
1430
1434
|
`);return}let r=o.slice(-t);console.log(`
|
|
1431
|
-
${
|
|
1432
|
-
${
|
|
1433
|
-
`);for(let l of r)console.log(` ${
|
|
1434
|
-
${
|
|
1435
|
+
${z.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${z.reset}`);for(let i of r){let c=(i.date||"").replace("T"," ").substring(0,16),l=(i.version||"?").padEnd(8),u=(i.model||"?").substring(0,12).padEnd(12),d=`${i.score}/10`.padStart(6),f=i.grade||"?",p=i.issues&&i.issues.length>0?`${z.yellow}\u26A0 ${i.issues.slice(0,2).map(m=>m.substring(0,30)).join(", ")}${z.reset}`:`${z.green}\u2713${z.reset}`,g=i.score>=8?z.green:i.score>=6?z.yellow:z.red;console.log(` ${z.dim}${c}${z.reset} ${z.dim}v${l}${z.reset} ${z.dim}${u}${z.reset} ${g}${d} ${f}${z.reset} ${p}`)}console.log()}async function UT({dryRun:t=!1,model:e,cwd:n,onProgress:s}={}){let o=Hs(),r=h$(n);if(t){console.log(`
|
|
1436
|
+
${z.bold}Scenario Benchmark \u2014 Scenarios (dry-run):${z.reset}
|
|
1437
|
+
`);for(let l of r)console.log(` ${z.cyan}${l.id.padEnd(20)}${z.reset} ${z.dim}${l.name}${z.reset} maxTurns=${l.maxTurns}`),console.log(` ${z.dim}${l.prompt.substring(0,80)}${z.reset}`);return console.log(),[]}let i=(()=>{if(e)return typeof e=="object"?e.id||"unknown":e;try{let{getActiveModel:l}=eo(),u=l?l():null;return u?typeof u=="object"?u.id||"unknown":u:"unknown"}catch{return"unknown"}})(),c=[];for(let l of r){s?.({id:l.id,name:l.name,done:!1}),console.log(`
|
|
1438
|
+
${z.dim}Running scenario: ${l.name}...${z.reset}`);let{messages:u,timedOut:d}=await DT(l,{model:i,cwd:n}),f;d||u.length===0?f={score:0,grade:"F",issues:[d?"Scenario timed out":"No messages produced"],summary:"No output",bonuses:[]}:f=g$(u,l);let p={id:l.id,name:l.name,score:f.score,grade:f.grade,issues:f.issues,bonuses:f.bonuses};c.push(p),s?.({id:l.id,name:l.name,done:!0,score:f.score,grade:f.grade});try{let{appendScoreHistory:g}=ta();g(f.score,{version:o.version,model:i,sessionName:`bench:${l.id}`,issues:f.issues})}catch{}}return qT(c,o.version,i),c}$$.exports={runBenchmark:IT,runDiscoverBenchmark:jT,buildSummary:Eu,buildCategoryWinners:f$,TASKS:Su,PHASE_TASKS:l$,ALL_TASKS:La,scoreResult:Ro,DEFAULT_MODELS:ku,QUICK_MODELS:u$,runScenarioBenchmark:UT,showScoreTrend:FT,loadScenarios:h$,DEFAULT_SCENARIOS:Pa,scoreScenario:g$}});var E$=oe((dC,k$)=>{"use strict";var BT=require("os"),b$=require("path"),Tu=require("fs"),{callWithRetry:y$}=Bi(),{parseModelSpec:WT}=Be(),{extractJSON:w$,DECOMPOSE_PROMPT:HT,SYNTHESIZE_PROMPT:KT}=$r(),{C:Ut}=Ke(),Ia=b$.join(BT.homedir(),".nex-code","orchestrator-bench.json"),_$=[{id:"decompose_multi_bug",type:"decompose",prompt:"Fix 4 bugs: (1) 500 error on SmartThings API call, (2) invalid time format on Sunday schedule, (3) Google Auth callback fails with CORS, (4) contact search returns empty",expectedSubTasks:4,maxSubTasks:5},{id:"decompose_feature_mix",type:"decompose",prompt:"Add dark mode toggle to settings page, fix the broken login redirect, improve search performance by adding an index, update API docs for the new endpoints",expectedSubTasks:4,maxSubTasks:5},{id:"decompose_overlapping",type:"decompose",prompt:"Refactor auth.js to use JWT instead of sessions, update all tests that import auth.js, and add rate limiting to the login endpoint in auth.js",expectedSubTasks:3,maxSubTasks:4},{id:"decompose_single",type:"decompose",prompt:"Fix the broken CSS on the login page \u2014 the submit button is not aligned",expectedSubTasks:1,maxSubTasks:4},{id:"synthesize_clean",type:"synthesize",prompt:"Fix login and search bugs",subResults:[{task:"Fix login redirect",status:"done",result:"Changed auth.js line 42: fixed redirect URL to use req.originalUrl instead of hardcoded /",toolsUsed:["read_file","edit_file"]},{task:"Fix search index",status:"done",result:"Added index on users.email column in migration 20260323. Updated search.js to use indexed query.",toolsUsed:["write_file","edit_file"]}],expectedConflicts:0},{id:"synthesize_conflicts",type:"synthesize",prompt:"Fix config loading and add env validation",subResults:[{task:"Fix config loading",status:"done",result:"Modified config.js: changed loadConfig() to handle missing .env gracefully",toolsUsed:["edit_file"]},{task:"Add env validation",status:"done",result:"Modified config.js: added validateEnv() function that throws on missing required vars",toolsUsed:["edit_file"]}],expectedConflicts:1}];function x$(t,e){if(!Array.isArray(t))return 0;let n=0;n+=1.5;let s=Math.abs(t.length-e.expectedSubTasks);s===0?n+=3:s===1&&(n+=1.5),t.every(l=>l.task&&typeof l.task=="string"&&l.task.length>0)&&(n+=2);let r=t.flatMap(l=>Array.isArray(l.scope)?l.scope:[]),i=new Set(r);return r.length===i.size&&(n+=2),t.every(l=>typeof l.estimatedCalls=="number"||typeof l.estimatedSshCalls=="number")&&(n+=1.5),Math.min(10,Math.round(n*10)/10)}function v$(t,e){if(!t||typeof t!="object")return 0;let n=0;n+=1.5,t.summary&&t.summary.length>10&&(n+=2),t.commitMessage&&t.commitMessage.length>5&&(n+=2);let s=Array.isArray(t.conflicts)?t.conflicts:[];return e.expectedConflicts===0&&s.length===0||e.expectedConflicts>0&&s.length>0?n+=2.5:e.expectedConflicts>0&&s.length===0&&(n+=0),Array.isArray(t.filesChanged)&&t.filesChanged.length>0&&(n+=2),Math.min(10,Math.round(n*10)/10)}async function S$(t,e){let n={};if(e){let o=WT(e);o.provider&&(n.provider=o.provider),o.model&&(n.model=o.model)}let s=Date.now();try{if(t.type==="decompose"){let o=HT.replace("{maxSubTasks}",String(t.maxSubTasks)).replace("{prompt}",t.prompt),r=await y$([{role:"system",content:o},{role:"user",content:t.prompt}],[],n),i=w$(r.content||""),c=Date.now()-s;return{score:x$(i,t),latencyMs:c}}if(t.type==="synthesize"){let o=t.subResults.map((d,f)=>{let p=d.status==="done"?"SUCCESS":"FAILED";return`--- Agent ${f+1} [${p}] ---
|
|
1435
1439
|
Task: ${d.task}
|
|
1436
1440
|
Result: ${d.result}
|
|
1437
1441
|
Tools: ${d.toolsUsed.join(", ")}`}).join(`
|
|
1438
1442
|
|
|
1439
|
-
`),r=
|
|
1440
|
-
${
|
|
1441
|
-
`);let e=` ${"Model".padEnd(25)} ${"Decompose".padEnd(10)} ${"Synthesize".padEnd(11)} ${"Speed".padEnd(8)} ${"Score".padEnd(8)}`;console.log(`${
|
|
1442
|
-
${
|
|
1443
|
-
`))}
|
|
1443
|
+
`),r=KT.replace("{prompt}",t.prompt).replace("{results}",o),i=await y$([{role:"system",content:r},{role:"user",content:"Synthesize the sub-agent results above."}],[],n),c=w$(i.content||""),l=Date.now()-s;return{score:v$(c,t),latencyMs:l}}return{score:0,latencyMs:0,error:`Unknown scenario type: ${t.type}`}}catch(o){return{score:0,latencyMs:Date.now()-s,error:o.message}}}async function YT(t={}){let e=t.models||["kimi-k2.5","qwen3.5:397b","minimax-m2.7:cloud"],n=t.onProgress||(()=>{}),s=[];for(let r of e){let i={model:r,scores:[],latencies:[]},c=[],l=[];for(let g of _$){n({model:r,scenario:g.id,done:!1});let m=await S$(g,r);i.scores.push(m.score),i.latencies.push(m.latencyMs),g.type==="decompose"&&c.push(m.score),g.type==="synthesize"&&l.push(m.score),n({model:r,scenario:g.id,done:!0,score:m.score,error:m.error})}let u=c.length>0?c.reduce((g,m)=>g+m,0)/c.length:0,d=l.length>0?l.reduce((g,m)=>g+m,0)/l.length:0,f=i.latencies.reduce((g,m)=>g+m,0)/i.latencies.length,p=u*.6+d*.4;s.push({model:r,decompose:Math.round(u*10)/10,synthesize:Math.round(d*10)/10,avgLatency:Math.round(f),overall:Math.round(p*10)/10})}s.sort((r,i)=>i.overall-r.overall);let o=b$.dirname(Ia);return Tu.existsSync(o)||Tu.mkdirSync(o,{recursive:!0}),Tu.writeFileSync(Ia,JSON.stringify({date:new Date().toISOString().slice(0,10),results:s},null,2)),s}function GT(t){console.log(`
|
|
1444
|
+
${Ut.bold}${Ut.cyan}Orchestrator Model Benchmark${Ut.reset}
|
|
1445
|
+
`);let e=` ${"Model".padEnd(25)} ${"Decompose".padEnd(10)} ${"Synthesize".padEnd(11)} ${"Speed".padEnd(8)} ${"Score".padEnd(8)}`;console.log(`${Ut.dim}${e}${Ut.reset}`),console.log(` ${Ut.dim}${"\u2500".repeat(65)}${Ut.reset}`);for(let n of t){let s=t.indexOf(n)===0?"\u{1F947}":t.indexOf(n)===1?"\u{1F948}":t.indexOf(n)===2?"\u{1F949}":" ",o=`${(n.avgLatency/1e3).toFixed(1)}s`;console.log(`${s} ${n.model.padEnd(25)} ${(n.decompose+"/10").padEnd(10)} ${(n.synthesize+"/10").padEnd(11)} ${o.padEnd(8)} ${Ut.bold}${n.overall}/10${Ut.reset}`)}t.length>0&&(console.log(`
|
|
1446
|
+
${Ut.green}Best orchestrator: ${t[0].model} (${t[0].overall}/10)${Ut.reset}`),console.log(` ${Ut.dim}Saved to ${Ia}${Ut.reset}
|
|
1447
|
+
`))}k$.exports={runOrchestratorBenchmark:YT,ORCHESTRATOR_SCENARIOS:_$,scoreDecompose:x$,scoreSynthesize:v$,runScenario:S$,printResults:GT,RESULTS_PATH:Ia}});var C$=oe((fC,R$)=>{var zT=require("axios"),Fr=require("fs"),T$=require("path"),XT="nex-code",Ru=T$.join(process.cwd(),".nex"),Cu=T$.join(Ru,"last-version-check");Fr.existsSync(Ru)||Fr.mkdirSync(Ru,{recursive:!0});async function VT(){try{let t=ZT(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};QT(e);let n=JT(),o=(await zT.get(`https://registry.npmjs.org/${XT}/latest`,{timeout:5e3})).data.version,r=e1(o,n);return{hasNewVersion:r,latestVersion:r?o:void 0,currentVersion:r?n:void 0}}catch{return{hasNewVersion:!1}}}function JT(){return Hs().version}function ZT(){try{if(Fr.existsSync(Cu)){let t=Fr.readFileSync(Cu,"utf8");return parseInt(t,10)}}catch{}return null}function QT(t){try{Fr.writeFileSync(Cu,t.toString())}catch{}}function e1(t,e){try{let n=t.split(".").map(Number),s=e.split(".").map(Number);return n[0]>s[0]?!0:n[0]<s[0]?!1:n[1]>s[1]?!0:n[1]<s[1]?!1:n[2]>s[2]}catch{return!1}}R$.exports={checkForNewVersion:VT}});var Du=oe((mC,F$)=>{var t1=require("readline"),pt=require("fs"),at=require("path"),{C:a,banner:n1,cleanupTerminal:A$}=Ke(),{isDark:s1}=os(),{listProviders:Nu,getActiveProviderName:Ms,listAllModels:pC,setFallbackChain:o1,getFallbackChain:r1,getProvider:i1}=Be(),{flushAutoSave:O$}=on(),{writeDreamLog:a1,shouldConsolidate:c1,consolidate:l1}=mu(),{getActiveModel:Dn,setActiveModel:Mu}=eo(),{printContext:N$}=Qi(),{loadAllSkills:u1,getSkillCommands:Da,handleSkillCommand:d1}=Cn(),{setReadlineInterface:f1,setAutoConfirm:p1,getAutoConfirm:Au,setAllowAlwaysHandler:m1}=$t(),{StickyFooter:h1}=Ig(),Qt=process.cwd(),De=null,pn=null;function M$(){return pn?.signal??null}var Hr=[{cmd:"/help",desc:"Show full help"},{cmd:"/model",desc:"Show/switch model"},{cmd:"/providers",desc:"List providers and models"},{cmd:"/fallback",desc:"Show/set fallback chain"},{cmd:"/tokens",desc:"Token usage and context budget"},{cmd:"/costs",desc:"Session token costs"},{cmd:"/budget",desc:"Show/set cost limits per provider"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/context",desc:"Show project context"},{cmd:"/tree [depth]",desc:"Show project file tree (default depth 3)"},{cmd:"/autoconfirm",desc:"Toggle auto-confirm"},{cmd:"/save",desc:"Save session"},{cmd:"/load",desc:"Load a saved session"},{cmd:"/sessions",desc:"List saved sessions"},{cmd:"/resume",desc:"Resume last session"},{cmd:"/branches",desc:"Show session tree (all branches)"},{cmd:"/timeline",desc:"Show message timeline of current branch"},{cmd:"/goto <index>",desc:"Jump to a message index (truncates after)"},{cmd:"/fork [index]",desc:"Create branch at index (default: current)"},{cmd:"/switch-branch <name>",desc:"Switch to a different conversation branch"},{cmd:"/delete-branch <name>",desc:"Delete a conversation branch"},{cmd:"/remember",desc:"Save a memory"},{cmd:"/forget",desc:"Delete a memory"},{cmd:"/memory",desc:"Show all memories"},{cmd:"/brain",desc:"Manage knowledge base"},{cmd:"/brain add",desc:"Add document: /brain add <name> [content]"},{cmd:"/brain list",desc:"List all brain documents"},{cmd:"/brain search",desc:"Search brain: /brain search <query>"},{cmd:"/brain show",desc:"Show document: /brain show <name>"},{cmd:"/brain remove",desc:"Remove document: /brain remove <name>"},{cmd:"/brain rebuild",desc:"Rebuild keyword index"},{cmd:"/brain embed",desc:"Build/rebuild embedding index"},{cmd:"/brain status",desc:"Show brain status (docs, index, embeddings)"},{cmd:"/brain review",desc:"Review pending brain changes (git diff)"},{cmd:"/brain undo",desc:"Undo last brain write"},{cmd:"/learn",desc:"Reflect on session and update memory"},{cmd:"/optimize",desc:"Show optimization opportunities"},{cmd:"/permissions",desc:"Show tool permissions"},{cmd:"/allow",desc:"Auto-allow a tool"},{cmd:"/deny",desc:"Block a tool"},{cmd:"/plan",desc:"Plan mode (analyze before executing)"},{cmd:"/plan edit",desc:"Open current plan in $EDITOR"},{cmd:"/plans",desc:"List saved plans"},{cmd:"/auto",desc:"Set autonomy level"},{cmd:"/commit",desc:"Smart commit (diff + message)"},{cmd:"/diff",desc:"Show current diff"},{cmd:"/review [--strict] [file]",desc:"Deep code review with score table and diff suggestions (--strict: force \u22653 critical findings)"},{cmd:"/branch",desc:"Create feature branch"},{cmd:"/mcp",desc:"MCP servers and tools"},{cmd:"/mcp list",desc:"List connected MCP servers and their tools"},{cmd:"/mcp status",desc:"Show which MCP servers are running"},{cmd:"/hooks",desc:"Show configured hooks"},{cmd:"/skills",desc:"List, enable, disable skills"},{cmd:"/install-skill <url>",desc:"Install a skill from git URL or user/repo"},{cmd:"/search-skill <query>",desc:"Search for skills on GitHub"},{cmd:"/remove-skill <name>",desc:"Remove an installed skill"},{cmd:"/tasks",desc:"Show task list"},{cmd:"/servers",desc:"List server profiles / ping"},{cmd:"/docker",desc:"List containers across all servers"},{cmd:"/deploy",desc:"List deploy configs / run named deploy"},{cmd:"/benchmark [--quick] [--models=a,b]",desc:"Rank Ollama Cloud models on nex-code tool-calling tasks (--history for nightly log)"},{cmd:"/bench [--dry-run] [--model=<spec>]",desc:"Run scenario benchmark (5 agentic tasks)"},{cmd:"/trend [n]",desc:"Show score history trend (default: last 10 sessions)"},{cmd:"/init",desc:"Interactive setup wizard (.nex/)"},{cmd:"/setup",desc:"Configure provider and API keys"},{cmd:"/retry [--model <id>]",desc:"Retry last user turn (optionally with a different model)"},{cmd:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/snapshot [name]",desc:"Create a named git snapshot of current changes"},{cmd:"/restore [name|last]",desc:"Restore a previously created snapshot"},{cmd:"/orchestrate <prompt>",desc:"Decompose prompt into parallel sub-tasks, run, synthesize"},{cmd:"/bench-orchestrator",desc:"Benchmark models for orchestrator role"},{cmd:"/audit",desc:"Show tool execution audit log"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function P$(){let t=Da(),e=[...Hr,...t],n=Math.max(...e.map(s=>s.cmd.length));console.log("");for(let{cmd:s,desc:o}of Hr)console.log(` ${a.cyan}${s.padEnd(n+2)}${a.reset}${a.dim}${o}${a.reset}`);for(let{cmd:s,desc:o}of t)console.log(` ${a.cyan}${s.padEnd(n+2)}${a.reset}${a.dim}${o} ${a.yellow}[skill]${a.reset}`);console.log(`
|
|
1444
1448
|
${a.dim}Type /help for detailed usage${a.reset}
|
|
1445
|
-
`)}function
|
|
1449
|
+
`)}function L$(t){try{let e,n;t.endsWith("/")||t.endsWith(at.sep)?(e=t,n=""):(e=at.dirname(t),n=at.basename(t)),e.startsWith("~")&&(e=at.join(require("os").homedir(),e.slice(1)));let s=at.isAbsolute(e)?e:at.resolve(Qt,e);if(!pt.existsSync(s)||!pt.statSync(s).isDirectory())return[];let o=pt.readdirSync(s,{withFileTypes:!0}),r=[];for(let i of o){if(i.name.startsWith(".")||i.name==="node_modules"||n&&!i.name.startsWith(n))continue;let c=t.endsWith("/")||t.endsWith(at.sep)?t:at.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?i.name:c+i.name;r.push(i.isDirectory()?l+"/":l)}return r}catch{return[]}}function I$(t){if(t.startsWith("/")){let s=[...Hr,...Da()],o=s.map(r=>r.cmd).filter(r=>r.startsWith(t));return[o.length?o:s.map(r=>r.cmd),t]}let e=t.split(/\s+/),n=e[e.length-1]||"";return n&&(n.includes("/")||n.startsWith("./")||n.startsWith("../")||n.startsWith("~"))?[L$(n),n]:[[],t]}function j$(){console.log(`
|
|
1446
1450
|
${a.bold}${a.cyan}Commands:${a.reset}
|
|
1447
1451
|
${a.cyan}/help${a.reset} ${a.dim}Show this help${a.reset}
|
|
1448
1452
|
${a.cyan}/model [spec]${a.reset} ${a.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${a.reset}
|
|
@@ -1515,60 +1519,60 @@ ${a.bold}${a.cyan}Undo / Redo:${a.reset}
|
|
|
1515
1519
|
${a.cyan}/benchmark --all --parallel=N${a.reset}${a.dim} Override concurrency (default 3)${a.reset}
|
|
1516
1520
|
|
|
1517
1521
|
${a.cyan}/exit${a.reset} ${a.dim}Quit${a.reset}
|
|
1518
|
-
`)}function
|
|
1519
|
-
${a.bold}${a.cyan}Providers:${a.reset}`);for(let s of t){let o=s.provider===e,r=s.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,i=o?` ${a.cyan}(active)${a.reset}`:"";console.log(` ${r} ${a.bold}${s.provider}${a.reset}${i}`);for(let c of s.models){let l=c.id===n.id&&o?` ${a.yellow}\u25C4${a.reset}`:"";console.log(` ${a.dim}${c.id}${a.reset} \u2014 ${c.name}${l}`)}}console.log()}async function
|
|
1520
|
-
${a.bold}${a.cyan}Token Usage:${a.reset}`),console.log(` ${a.dim}Model:${a.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${a.dim}Used:${a.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f=
|
|
1521
|
-
${a.dim}Breakdown:${a.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:r}=
|
|
1522
|
+
`)}function D$(t){let n=Math.round(t/100*30),s=30-n;return` ${t>80?a.red:t>50?a.yellow:a.green}${"\u2588".repeat(n)}${a.dim}${"\u2591".repeat(s)}${a.reset} ${t}%`}function Ou(){let t=Nu(),e=Ms(),n=Dn();console.log(`
|
|
1523
|
+
${a.bold}${a.cyan}Providers:${a.reset}`);for(let s of t){let o=s.provider===e,r=s.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,i=o?` ${a.cyan}(active)${a.reset}`:"";console.log(` ${r} ${a.bold}${s.provider}${a.reset}${i}`);for(let c of s.models){let l=c.id===n.id&&o?` ${a.yellow}\u25C4${a.reset}`:"";console.log(` ${a.dim}${c.id}${a.reset} \u2014 ${c.name}${l}`)}}console.log()}async function Wr(t,e){let[n,...s]=t.split(/\s+/);switch(n){case"/help":return j$(),!0;case"/model":{let o=s.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=qg();await r(e)}else{let r=Dn(),i=Ms();console.log(`${a.bold}${a.cyan}Active model:${a.reset} ${a.dim}${i}:${r.id} (${r.name})${a.reset}`),console.log(`${a.gray}Use /model <provider:model> to switch. /providers to see all.${a.reset}`)}return!0}if(o==="list")return Ou(),!0;if(Mu(o)){let r=Dn(),i=Ms();console.log(`${a.green}Switched to ${i}:${r.id} (${r.name})${a.reset}`)}else console.log(`${a.red}Unknown model: ${o}${a.reset}`),console.log(`${a.gray}Use /providers to see available models${a.reset}`);return!0}case"/providers":return Ou(),!0;case"/fallback":{let o=s.join(" ").trim();if(!o){let i=r1();return i.length===0?(console.log(`${a.dim}No fallback chain configured${a.reset}`),console.log(`${a.dim}Use /fallback anthropic,openai,local to set${a.reset}`)):console.log(`${a.bold}${a.cyan}Fallback chain:${a.reset} ${i.join(" \u2192 ")}`),!0}let r=o.split(",").map(i=>i.trim()).filter(Boolean);return o1(r),console.log(`${a.green}Fallback chain: ${r.join(" \u2192 ")}${a.reset}`),!0}case"/tokens":{let{getConversationMessages:o}=Ee(),{getUsage:r}=Lt(),{TOOL_DEFINITIONS:i}=en(),c=o(),l=r(c,i),u=Dn(),d=Ms();console.log(`
|
|
1524
|
+
${a.bold}${a.cyan}Token Usage:${a.reset}`),console.log(` ${a.dim}Model:${a.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${a.dim}Used:${a.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f=D$(l.percentage);return console.log(` ${f}`),console.log(`
|
|
1525
|
+
${a.dim}Breakdown:${a.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:r}=Qs();return s.join(" ").trim()==="reset"?(r(),console.log(`${a.green}Cost tracking reset${a.reset}`),!0):(console.log(`
|
|
1522
1526
|
${o()}
|
|
1523
|
-
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=
|
|
1524
|
-
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let h=!1;for(let y of m){let
|
|
1527
|
+
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=Qs(),d=s[0];if(!d){let g=o(),m=Nu();console.log(`
|
|
1528
|
+
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let h=!1;for(let y of m){let b=r(y.provider),S=g[y.provider];if(S!==void 0){h=!0;let C=Math.min(100,Math.round(b/S*100)),k=10,x=Math.round(C/100*k),E=k-x,q=`${C>=100?a.red:C>=80?a.yellow:a.green}${"\u2588".repeat(x)}${a.dim}${"\u2591".repeat(E)}${a.reset}`;console.log(` ${a.bold}${y.provider}:${a.reset} $${b.toFixed(2)} / $${S.toFixed(2)} (${C}%) ${q}`)}else y.provider==="ollama"||y.provider==="local"?console.log(` ${a.bold}${y.provider}:${a.reset} ${a.dim}free (no limit)${a.reset}`):b>0&&console.log(` ${a.bold}${y.provider}:${a.reset} $${b.toFixed(2)} ${a.dim}(no limit)${a.reset}`)}return h||console.log(` ${a.dim}No limits set. Use /budget <provider> <amount> to set one.${a.reset}`),console.log(),!0}let f=s[1];if(!f){let g=i(d);return g.limit!==null?console.log(`${a.bold}${d}:${a.reset} $${g.spent.toFixed(2)} / $${g.limit.toFixed(2)} ($${g.remaining.toFixed(2)} remaining)`):console.log(`${a.bold}${d}:${a.reset} $${g.spent.toFixed(2)} ${a.dim}(no limit)${a.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return c(d),l(),console.log(`${a.green}Removed cost limit for ${d}${a.reset}`),!0;let p=parseFloat(f);return isNaN(p)||p<=0?(console.log(`${a.red}Invalid amount: ${f}. Use a positive number or 'off'.${a.reset}`),!0):(u(d,p),l(),console.log(`${a.green}Set ${d} budget limit: $${p.toFixed(2)}${a.reset}`),!0)}case"/clear":{let{clearConversation:o,getConversationMessages:r}=Ee(),{clearHistory:i}=Rn(),c=r();if(c.filter(d=>d.role==="user").length>=4){process.stdout.write(`${a.dim}Reflecting on session...${a.reset} `);let{learnFromSession:d}=$u();d(c).then(f=>{if(!f.skipped&&!f.error&&(f.applied.length>0||f.nexAdded.length>0)){let p=f.applied.length+f.nexAdded.length;process.stdout.write(`${a.green}${p} learning(s) saved${a.reset}
|
|
1525
1529
|
`)}else process.stdout.write(`${a.dim}nothing new${a.reset}
|
|
1526
1530
|
`)}).catch(()=>process.stdout.write(`
|
|
1527
|
-
`))}o(),i(),De=null;let{deleteSession:u}=
|
|
1528
|
-
`):p=String(f.content),r(c.slice(0,l));let{resetSessionTracking:g}=Ee();g();let m=d||"current model";return console.log(`${a.cyan}Retrying with ${m}...${a.reset}`),await i(p),!0}case"/context":return await
|
|
1531
|
+
`))}o(),i(),De=null;let{deleteSession:u}=on();return u("_autosave"),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/retry":{let{getConversationMessages:o,setConversationMessages:r,processInput:i}=Ee(),c=o(),l=c.map(h=>h.role).lastIndexOf("user");if(l===-1)return console.log(`${a.yellow}Nothing to retry \u2014 no user message found.${a.reset}`),!0;let u=s.indexOf("--model"),d=u!==-1&&s[u+1]?s[u+1]:null;if(d){let{setActiveModel:h}=Be();if(!h(d))return console.log(`${a.red}Unknown model: ${d}. Use /providers to see available models.${a.reset}`),!0;console.log(`${a.cyan}Switched to model: ${d}${a.reset}`)}let f=c[l],p;typeof f.content=="string"?p=f.content:Array.isArray(f.content)?p=f.content.filter(h=>h&&h.type==="text").map(h=>h.text).join(`
|
|
1532
|
+
`):p=String(f.content),r(c.slice(0,l));let{resetSessionTracking:g}=Ee();g();let m=d||"current model";return console.log(`${a.cyan}Retrying with ${m}...${a.reset}`),await i(p),!0}case"/context":return await N$(Qt),!0;case"/tree":{let{generateFileTree:o}=Qi(),r=parseInt(s.join(" ").trim(),10),i=!isNaN(r)&&r>0?Math.min(r,8):3,c=o(Qt,{maxDepth:i,maxFiles:300});return console.log(`
|
|
1529
1533
|
${a.bold}${a.cyan}Project tree${a.reset}${a.dim} (depth ${i})${a.reset}
|
|
1530
1534
|
`),console.log(`${a.dim}${c}${a.reset}
|
|
1531
|
-
`),!0}case"/autoconfirm":{let o=!
|
|
1532
|
-
${a.bold}${a.cyan}Sessions:${a.reset}`);for(let i of r){let c=i.updatedAt?new Date(i.updatedAt).toLocaleString():"?",l=i.name==="_autosave"?` ${a.dim}(auto)${a.reset}`:"",u=i.score!=null?` \xB7 score ${i.score}/10${i.scoreGrade?` (${i.scoreGrade})`:""}`:"";console.log(` ${a.cyan}${i.name}${a.reset}${l} \u2014 ${i.messageCount} msgs, ${c}${a.dim}${u}${a.reset}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=
|
|
1533
|
-
${a.bold}${a.cyan}Memory:${a.reset}`);for(let i of r)console.log(` ${a.cyan}${i.key}${a.reset} = ${i.value}`);return console.log(),!0}case"/brain":{let{listDocuments:o,readDocument:r,writeDocument:i,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=
|
|
1535
|
+
`),!0}case"/autoconfirm":{let o=!Au();return p1(o),console.log(`${a.green}Auto-confirm: ${o?"ON":"OFF"}${a.reset}`),o&&console.log(`${a.yellow} \u26A0 File changes will be applied without confirmation${a.reset}`),Ur(),!0}case"/save":{let{saveSession:o}=on(),{getConversationMessages:r}=Ee(),i=s.join(" ").trim()||`session-${Date.now()}`,c=r();if(c.length===0)return console.log(`${a.yellow}No conversation to save${a.reset}`),!0;let l=Dn(),u=Ms();return o(i,c,{model:l.id,provider:u}),console.log(`${a.green}Session saved: ${i} (${c.length} messages)${a.reset}`),!0}case"/load":{let{loadSession:o}=on(),{setConversationMessages:r}=Ee(),i=s.join(" ").trim();if(!i)return console.log(`${a.red}Usage: /load <name>${a.reset}`),!0;let c=o(i);return c?(r(c.messages),console.log(`${a.green}Loaded session: ${c.name} (${c.messageCount} messages)${a.reset}`),!0):(console.log(`${a.red}Session not found: ${i}${a.reset}`),!0)}case"/sessions":{let{listSessions:o}=on(),r=o();if(r.length===0)return console.log(`${a.dim}No saved sessions${a.reset}`),!0;console.log(`
|
|
1536
|
+
${a.bold}${a.cyan}Sessions:${a.reset}`);for(let i of r){let c=i.updatedAt?new Date(i.updatedAt).toLocaleString():"?",l=i.name==="_autosave"?` ${a.dim}(auto)${a.reset}`:"",u=i.score!=null?` \xB7 score ${i.score}/10${i.scoreGrade?` (${i.scoreGrade})`:""}`:"";console.log(` ${a.cyan}${i.name}${a.reset}${l} \u2014 ${i.messageCount} msgs, ${c}${a.dim}${u}${a.reset}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=on(),{setConversationMessages:r}=Ee(),i=o();return i?(r(i.messages),console.log(`${a.green}Resumed: ${i.name} (${i.messageCount} messages)${a.reset}`),!0):(console.log(`${a.yellow}No session to resume${a.reset}`),!0)}case"/branches":{let{initTree:o,renderTree:r}=Vn(),{getConversationMessages:i}=Ee(),c=i();return c.length===0?(console.log(`${a.yellow}No conversation yet${a.reset}`),!0):(De||(De=o({messages:c})),console.log(r(De)),console.log(),!0)}case"/timeline":{let{initTree:o,renderTimeline:r}=Vn(),{getConversationMessages:i}=Ee(),c=i();if(c.length===0)return console.log(`${a.yellow}No conversation yet${a.reset}`),!0;De||(De=o({messages:c})),Vn().setActiveMessages(De,c);let u=parseInt(s[0],10)||20;return console.log(r(De,u)),console.log(),!0}case"/goto":{let o=Vn(),{getConversationMessages:r,setConversationMessages:i}=Ee(),c=r();if(c.length===0)return console.log(`${a.yellow}No conversation yet${a.reset}`),!0;let l=parseInt(s[0],10);if(isNaN(l))return console.log(`${a.red}Usage: /goto <message-index>${a.reset}`),console.log(`${a.dim}Use /timeline to see message indices${a.reset}`),!0;De||(De=o.initTree({messages:c})),o.setActiveMessages(De,c);try{let{truncated:u}=o.gotoMessage(De,l),d=o.getActiveMessages(De);i(d),console.log(`${a.green}Jumped to message ${l}. Removed ${u} later messages.${a.reset}`),console.log(`${a.dim}Conversation now has ${d.length} messages. Continue chatting from here.${a.reset}`)}catch(u){console.log(`${a.red}${u.message}${a.reset}`)}return!0}case"/fork":{let o=Vn(),{getConversationMessages:r,setConversationMessages:i}=Ee(),c=r();if(c.length===0)return console.log(`${a.yellow}No conversation yet${a.reset}`),!0;De||(De=o.initTree({messages:c})),o.setActiveMessages(De,c);let l=s[0]?parseInt(s[0],10):c.length-1,u=s[1]||void 0;if(isNaN(l))return console.log(`${a.red}Usage: /fork [message-index] [branch-name]${a.reset}`),!0;try{let{branchName:d}=o.createBranch(De,l,u),f=o.getActiveMessages(De);i(f),console.log(`${a.green}Created branch "${d}" forking at message ${l}${a.reset}`),console.log(`${a.dim}Now on branch "${d}" with ${f.length} messages. Continue chatting.${a.reset}`)}catch(d){console.log(`${a.red}${d.message}${a.reset}`)}return!0}case"/switch-branch":{let o=Vn(),{getConversationMessages:r,setConversationMessages:i}=Ee();if(!De){let l=r();De=o.initTree({messages:l})}o.setActiveMessages(De,r());let c=s.join(" ").trim();if(!c)return console.log(`${a.red}Usage: /switch-branch <name>${a.reset}`),console.log(`${a.dim}Available: ${Object.keys(De.branches).join(", ")}${a.reset}`),!0;try{o.switchBranch(De,c);let l=o.getActiveMessages(De);i(l),console.log(`${a.green}Switched to branch "${c}" (${l.length} messages)${a.reset}`)}catch(l){console.log(`${a.red}${l.message}${a.reset}`)}return!0}case"/delete-branch":{let o=Vn();if(!De){let{getConversationMessages:i}=Ee();De=o.initTree({messages:i()})}let r=s.join(" ").trim();if(!r)return console.log(`${a.red}Usage: /delete-branch <name>${a.reset}`),!0;try{o.deleteBranch(De,r),console.log(`${a.green}Deleted branch "${r}"${a.reset}`)}catch(i){console.log(`${a.red}${i.message}${a.reset}`)}return!0}case"/remember":{let{remember:o}=tn(),r=s.join(" ").trim();if(!r)return console.log(`${a.red}Usage: /remember <key>=<value> or /remember <text>${a.reset}`),!0;let i=r.indexOf("="),c,l;return i>0?(c=r.substring(0,i).trim(),l=r.substring(i+1).trim()):(c=r.substring(0,40).replace(/\s+/g,"-"),l=r),o(c,l),console.log(`${a.green}Remembered: ${c}${a.reset}`),!0}case"/forget":{let{forget:o}=tn(),r=s.join(" ").trim();return r?(o(r)?console.log(`${a.green}Forgotten: ${r}${a.reset}`):console.log(`${a.red}Memory not found: ${r}${a.reset}`),!0):(console.log(`${a.red}Usage: /forget <key>${a.reset}`),!0)}case"/memory":{let{listMemories:o}=tn(),r=o();if(r.length===0)return console.log(`${a.dim}No memories saved${a.reset}`),!0;console.log(`
|
|
1537
|
+
${a.bold}${a.cyan}Memory:${a.reset}`);for(let i of r)console.log(` ${a.cyan}${i.key}${a.reset} = ${i.value}`);return console.log(),!0}case"/brain":{let{listDocuments:o,readDocument:r,writeDocument:i,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=Qo(),p=s[0],g=s.slice(1).join(" ").trim();switch(p){case"add":{if(!g)return console.log(`${a.red}Usage: /brain add <name> [content]${a.reset}`),console.log(`${a.dim} /brain add api-notes \u2014 creates empty file${a.reset}`),console.log(`${a.dim} /brain add api-notes This is content \u2014 writes directly${a.reset}`),!0;let m=g.indexOf(" ");if(m<0){i(g,`# ${g}
|
|
1534
1538
|
|
|
1535
1539
|
`);let h=require("path").join(process.cwd(),".nex","brain",`${g}.md`);console.log(`${a.green}Created .nex/brain/${g}.md${a.reset}`),console.log(`${a.dim}Edit it directly at: ${h}${a.reset}`)}else{let h=g.substring(0,m),y=g.substring(m+1);i(h,y),console.log(`${a.green}Added to brain: ${h}${a.reset}`)}return!0}case"list":{let m=o();if(m.length===0)return console.log(`${a.dim}No brain documents yet. Use /brain add <name> to create one.${a.reset}`),!0;console.log(`
|
|
1536
|
-
${a.bold}${a.cyan}Brain Documents:${a.reset}`);let h=Math.max(8,...m.map(
|
|
1540
|
+
${a.bold}${a.cyan}Brain Documents:${a.reset}`);let h=Math.max(8,...m.map(b=>b.name.length)),y=20;console.log(` ${"Name".padEnd(h+2)}${"Tags".padEnd(y)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(h+2)}${"-".repeat(y)}${"-".repeat(7)} --------`);for(let b of m){let{frontmatter:S}=r(b.name),C=Array.isArray(S.tags)?S.tags.join(", "):"",k=b.size<1024?`${b.size}B`:`${(b.size/1024).toFixed(1)}K`,x=b.modified.toLocaleDateString();console.log(` ${a.cyan}${b.name.padEnd(h+2)}${a.reset}${a.dim}${C.substring(0,y-1).padEnd(y)}${k.padStart(7)} ${x}${a.reset}`)}return console.log(),!0}case"search":{if(!g)return console.log(`${a.red}Usage: /brain search <query>${a.reset}`),!0;let m=await f(g,{topK:5});if(m.length===0)return console.log(`${a.dim}No matching brain documents for: ${g}${a.reset}`),!0;console.log(`
|
|
1537
1541
|
${a.bold}${a.cyan}Brain Search: "${g}"${a.reset}`);for(let h of m){let y=typeof h.score=="number"?h.score.toFixed(2):h.score;console.log(`
|
|
1538
1542
|
${a.cyan}${h.name}${a.reset} ${a.dim}(score: ${y})${a.reset}`),console.log(` ${a.dim}${h.excerpt||""}${a.reset}`)}return console.log(),!0}case"show":{if(!g)return console.log(`${a.red}Usage: /brain show <name>${a.reset}`),!0;let m=r(g);return m.content?(console.log(`
|
|
1539
1543
|
${a.bold}${a.cyan}${g}.md${a.reset}
|
|
1540
|
-
`),console.log(m.content),!0):(console.log(`${a.red}Document not found: ${g}${a.reset}`),!0)}case"remove":{if(!g)return console.log(`${a.red}Usage: /brain remove <name>${a.reset}`),!0;let{confirm:m}
|
|
1541
|
-
${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${m.length}`),console.log(` Index: ${h.existsSync(
|
|
1544
|
+
`),console.log(m.content),!0):(console.log(`${a.red}Document not found: ${g}${a.reset}`),!0)}case"remove":{if(!g)return console.log(`${a.red}Usage: /brain remove <name>${a.reset}`),!0;let{confirm:m}=$t();if(!await m(`Remove brain document "${g}"?`))return console.log(`${a.dim}Cancelled${a.reset}`),!0;let y=c(g);return console.log(y?`${a.green}Removed: ${g}.md${a.reset}`:`${a.red}Document not found: ${g}${a.reset}`),!0}case"rebuild":{let m=l(),h=Object.keys(m.documents).length;return console.log(`${a.green}Index rebuilt: ${h} document(s)${a.reset}`),!0}case"embed":{if(!await d())return console.log(`${a.yellow}Ollama embedding model not available.${a.reset}`),console.log(`${a.dim}Set NEX_EMBED_MODEL env var (default: nomic-embed-text) and ensure Ollama is running.${a.reset}`),!0;console.log(`${a.dim}Building embedding index...${a.reset}`);try{let h=await u(),y=Object.keys(h.documents||{}).length;console.log(`${a.green}Embedding index built: ${y} document(s)${a.reset}`)}catch(h){console.log(`${a.red}Embedding failed: ${h.message}${a.reset}`)}return!0}case"status":{let m=o(),h=require("fs"),y=require("path"),b=y.join(process.cwd(),".nex","brain",".brain-index.json"),S=y.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
|
|
1545
|
+
${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${m.length}`),console.log(` Index: ${h.existsSync(b)?a.green+"present"+a.reset:a.dim+"not built"+a.reset}`),console.log(` Embeddings: ${h.existsSync(S)?a.green+"present"+a.reset:a.dim+"not built (run /brain embed)"+a.reset}`),m.length>0){let C=m.reduce((k,x)=>k+x.size,0);console.log(` Total size: ${C<1024?C+"B":(C/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:m}=require("child_process"),{promisify:h}=require("util"),y=h(m);try{let{stdout:b}=await y("git diff .nex/brain/",{cwd:process.cwd()});b.trim()?(console.log(`
|
|
1542
1546
|
${a.bold}${a.cyan}Brain Changes (git diff):${a.reset}
|
|
1543
|
-
`),console.log(
|
|
1547
|
+
`),console.log(b)):console.log(`${a.dim}No pending brain changes (clean git state)${a.reset}`)}catch{console.log(`${a.dim}Not a git repo or no brain dir${a.reset}`)}return!0}case"undo":{let m=require("fs"),y=require("path").join(process.cwd(),".nex","brain");if(!m.existsSync(y))return console.log(`${a.dim}No brain directory found${a.reset}`),!0;let b=o();if(b.length===0)return console.log(`${a.dim}No brain documents to undo${a.reset}`),!0;let S=b[0],{exec:C}=require("child_process"),{promisify:k}=require("util"),x=k(C);try{await x(`git checkout -- ".nex/brain/${S.name}.md"`,{cwd:process.cwd()}),l(),console.log(`${a.green}Undone: restored ${S.name}.md from git${a.reset}`)}catch{console.log(`${a.red}Could not undo \u2014 not tracked in git or no prior version${a.reset}`)}return!0}default:{let m=o();if(m.length===0)console.log(`
|
|
1544
1548
|
${a.bold}${a.cyan}Brain Knowledge Base${a.reset}`),console.log(`${a.dim}No documents yet. Create with /brain add <name>${a.reset}`),console.log(`
|
|
1545
1549
|
${a.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${a.reset}
|
|
1546
1550
|
`);else{console.log(`
|
|
1547
|
-
${a.bold}${a.cyan}Brain: ${m.length} document(s)${a.reset}`);for(let h of m){let{frontmatter:y}=r(h.name),
|
|
1551
|
+
${a.bold}${a.cyan}Brain: ${m.length} document(s)${a.reset}`);for(let h of m){let{frontmatter:y}=r(h.name),b=Array.isArray(y.tags)?` [${y.tags.join(", ")}]`:"";console.log(` ${a.cyan}${h.name}${a.reset}${a.dim}${b}${a.reset}`)}console.log(`
|
|
1548
1552
|
${a.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${a.reset}
|
|
1549
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}
|
|
1553
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=$u(),{getConversationMessages:i}=Ee(),c=i(),l=c.filter(u=>u.role==="user").length;if(l<4)return console.log(`${a.yellow}Session too short to learn from (need 4+ user messages, have ${l})${a.reset}`),!0;console.log(`${a.dim}Analyzing session for learnings...${a.reset}`);try{let[u,d]=await Promise.all([o(c),r(c)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${a.dim}Session too short${a.reset}`),!0;u.error&&console.log(`${a.red}Reflection error: ${u.error}${a.reset}`),console.log(""),u.summary&&(console.log(`${a.bold}Session:${a.reset} ${a.dim}${u.summary}${a.reset}`),console.log(""));let f=u.applied&&u.applied.length>0,p=u.nexAdded&&u.nexAdded.length>0,g=d.written&&d.written.length>0;if(!f&&!p&&!g)console.log(`${a.dim}No new learnings extracted from this session${a.reset}`);else{if(f){console.log(`${a.bold}${a.cyan}Memory updates:${a.reset}`);for(let{key:m,value:h,action:y}of u.applied){let b=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${b} ${a.bold}${m}${a.reset} = ${h}`)}}if(p){console.log(`${a.bold}${a.cyan}Added to NEX.md:${a.reset}`);for(let m of u.nexAdded)console.log(` ${a.green}+${a.reset} ${m}`)}if(g){console.log(`${a.bold}${a.cyan}Brain documents:${a.reset}`);for(let{name:m,reason:h,action:y}of d.written){let b=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${b} ${a.bold}${m}.md${a.reset}${h?a.dim+" \u2014 "+h+a.reset:""}`)}}}console.log("")}catch(u){console.log(`${a.red}Learn failed: ${u.message}${a.reset}`)}return!0}case"/optimize":{let{getConversationMessages:o}=Ee(),{getUsage:r}=Lt(),{TOOL_DEFINITIONS:i}=en(),{listMemories:c}=tn(),l=o(),u=r(l,i),d=Dn(),f=Ms(),p=c();console.log(`
|
|
1550
1554
|
${a.bold}${a.cyan}Optimization Report${a.reset}
|
|
1551
1555
|
`);let g=u.percentage>80?a.red:u.percentage>50?a.yellow:a.green;if(console.log(`${a.bold}Context Window:${a.reset} ${g}${u.percentage}%${a.reset} used (${u.used.toLocaleString()} / ${u.limit.toLocaleString()} tokens)`),u.percentage>75?console.log(` ${a.yellow}\u2192 Tip: Use /clear to free context (auto-learns first)${a.reset}`):u.percentage>50?console.log(` ${a.dim}\u2192 Context is filling up, consider /clear soon${a.reset}`):console.log(` ${a.green}\u2192 Context healthy${a.reset}`),console.log(`
|
|
1552
|
-
${a.bold}Memory:${a.reset} ${p.length} entries`),p.length===0)console.log(` ${a.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${a.reset}`);else{let C=[...p].sort((
|
|
1553
|
-
${a.bold}Active Model:${a.reset} ${f}:${d.id}`);let m=d.contextWindow||d.maxTokens||0;m>0&&m<32e3&&l.length>10?console.log(` ${a.yellow}\u2192 Small context window (${(m/1e3).toFixed(0)}k). Consider /model for larger context${a.reset}`):m>=128e3&&console.log(` ${a.green}\u2192 Large context window (${(m/1e3).toFixed(0)}k) \u2014 good for long sessions${a.reset}`);let h=l.filter(
|
|
1554
|
-
${a.bold}Session:${a.reset} ${h} turns, ${l.length} messages total`),h>=4&&h%10===0&&console.log(` ${a.cyan}\u2192 Good time to /learn and capture session insights${a.reset}`);let y=[],
|
|
1555
|
-
${a.bold}Quick Wins:${a.reset}`);for(let
|
|
1556
|
+
${a.bold}Memory:${a.reset} ${p.length} entries`),p.length===0)console.log(` ${a.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${a.reset}`);else{let C=[...p].sort((E,B)=>new Date(B.updatedAt)-new Date(E.updatedAt))[0],k=C?Math.round((Date.now()-new Date(C.updatedAt))/6e4):null,x=k!==null?k<60?`${k}m ago`:`${Math.round(k/60)}h ago`:"?";console.log(` ${a.dim}Latest update: ${x}${a.reset}`),p.length>30&&console.log(` ${a.yellow}\u2192 Many memories (${p.length}) \u2014 consider pruning with /forget${a.reset}`)}console.log(`
|
|
1557
|
+
${a.bold}Active Model:${a.reset} ${f}:${d.id}`);let m=d.contextWindow||d.maxTokens||0;m>0&&m<32e3&&l.length>10?console.log(` ${a.yellow}\u2192 Small context window (${(m/1e3).toFixed(0)}k). Consider /model for larger context${a.reset}`):m>=128e3&&console.log(` ${a.green}\u2192 Large context window (${(m/1e3).toFixed(0)}k) \u2014 good for long sessions${a.reset}`);let h=l.filter(S=>S.role==="user").length;console.log(`
|
|
1558
|
+
${a.bold}Session:${a.reset} ${h} turns, ${l.length} messages total`),h>=4&&h%10===0&&console.log(` ${a.cyan}\u2192 Good time to /learn and capture session insights${a.reset}`);let y=[],b=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync(b)||y.push("Create NEX.md in project root to give nex-code project-specific instructions"),y.length>0){console.log(`
|
|
1559
|
+
${a.bold}Quick Wins:${a.reset}`);for(let S of y)console.log(` ${a.cyan}\u2192${a.reset} ${S}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:r,startExecution:i,setPlanMode:c,getPlanContent:l,getPlanContent:u,formatPlan:d,extractStepsFromText:f,createPlan:p}=rn(),{invalidateSystemPromptCache:g}=Ee(),m=s.join(" ").trim();if(m==="status"){let h=o();return console.log(d(h)),!0}if(m==="edit"){let h=l();if(!h)return console.log(`${a.yellow}No plan to edit. Generate a plan first with /plan${a.reset}`),!0;let y=require("os"),b=require("path").join(y.tmpdir(),`nex-plan-${Date.now()}.md`);require("fs").writeFileSync(b,h,"utf-8");let S=process.env.EDITOR||process.env.VISUAL||"nano",{spawnSync:C}=require("child_process");if(console.log(`${a.dim}Opening plan in ${S}... (save and close to update)${a.reset}`),C(S,[b],{stdio:"inherit"}).status===0){let{setPlanContent:x}=rn(),E=require("fs").readFileSync(b,"utf-8");x(E);let B=f(E);if(B.length>0){let re=o()?.task||"Task";p(re,B),console.log(`${a.green}Plan updated \u2014 ${B.length} steps extracted.${a.reset}`)}else console.log(`${a.green}Plan updated.${a.reset}`)}else console.log(`${a.yellow}Editor exited with error \u2014 plan unchanged.${a.reset}`);try{require("fs").unlinkSync(b)}catch{}return!0}if(m==="approve"){let h=l();if(r()){i(),c(!1),Ur(),g();let b=o()?.steps?.length||0,S=b>0?` (${b} steps)`:"";if(console.log(`${a.green}${a.bold}Plan approved!${a.reset}${S} Executing...`),console.log(`${a.dim}Plan mode disabled \u2014 all tools now available.${a.reset}`),h){let{processInput:C}=Ee(),k=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1556
1560
|
|
|
1557
1561
|
Implement the following plan step by step. All tools are now available.
|
|
1558
1562
|
|
|
1559
|
-
${h}`;try{await C(k)}catch(
|
|
1560
|
-
`)[0]}${a.reset}`)}}}else console.log(`${a.red}No plan to approve. Enter plan mode first with /plan${a.reset}`);return!0}return c(!0),
|
|
1563
|
+
${h}`;try{await C(k)}catch(x){console.log(`${a.red}Error: ${x.message?.split(`
|
|
1564
|
+
`)[0]}${a.reset}`)}}}else console.log(`${a.red}No plan to approve. Enter plan mode first with /plan${a.reset}`);return!0}return c(!0),Ur(),g(),console.log(`
|
|
1561
1565
|
${a.cyan}${a.bold}\u250C\u2500 PLAN MODE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510${a.reset}
|
|
1562
1566
|
${a.cyan}${a.bold}\u2502${a.reset} Analysis only \u2014 no file changes until approved ${a.cyan}${a.bold}\u2502${a.reset}
|
|
1563
1567
|
${a.cyan}${a.bold}\u2502${a.reset} ${a.dim}Read-only tools only \xB7 /plan approve to execute${a.reset} ${a.cyan}${a.bold}\u2502${a.reset}
|
|
1564
|
-
${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),m&&console.log(`${a.dim}Task: ${m}${a.reset}`),!0}case"/plans":{let{listPlans:o}=
|
|
1565
|
-
${a.bold}${a.cyan}Plans:${a.reset}`);for(let i of r){let c=i.status==="completed"?`${a.green}\u2713`:i.status==="executing"?`${a.blue}\u2192`:`${a.dim}\u25CB`;console.log(` ${c} ${a.reset}${a.bold}${i.name}${a.reset} \u2014 ${i.task||"?"} (${i.steps} steps, ${i.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:o,setAutonomyLevel:r,AUTONOMY_LEVELS:i}=
|
|
1568
|
+
${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),m&&console.log(`${a.dim}Task: ${m}${a.reset}`),!0}case"/plans":{let{listPlans:o}=rn(),r=o();if(r.length===0)return console.log(`${a.dim}No saved plans${a.reset}`),!0;console.log(`
|
|
1569
|
+
${a.bold}${a.cyan}Plans:${a.reset}`);for(let i of r){let c=i.status==="completed"?`${a.green}\u2713`:i.status==="executing"?`${a.blue}\u2192`:`${a.dim}\u25CB`;console.log(` ${c} ${a.reset}${a.bold}${i.name}${a.reset} \u2014 ${i.task||"?"} (${i.steps} steps, ${i.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:o,setAutonomyLevel:r,AUTONOMY_LEVELS:i}=rn(),c=s.join(" ").trim();return c?(r(c)?(console.log(`${a.green}Autonomy: ${c}${a.reset}`),Ur()):console.log(`${a.red}Unknown level: ${c}. Use: ${i.join(", ")}${a.reset}`),!0):(console.log(`${a.bold}${a.cyan}Autonomy:${a.reset} ${o()}`),console.log(`${a.dim}Levels: ${i.join(", ")}${a.reset}`),!0)}case"/permissions":{let{listPermissions:o}=hr(),r=o();console.log(`
|
|
1566
1570
|
${a.bold}${a.cyan}Tool Permissions:${a.reset}`);for(let i of r){let c=i.mode==="allow"?`${a.green}\u2713`:i.mode==="deny"?`${a.red}\u2717`:`${a.yellow}?`;console.log(` ${c} ${a.reset}${a.bold}${i.tool}${a.reset} ${a.dim}(${i.mode})${a.reset}`)}return console.log(`
|
|
1567
1571
|
${a.dim}Use /allow <tool> or /deny <tool> to change${a.reset}
|
|
1568
|
-
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=
|
|
1572
|
+
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=hr(),i=s.join(" ").trim();return i?(o(i,"allow"),r(),console.log(`${a.green}${i}: allow${a.reset}`),!0):(console.log(`${a.red}Usage: /allow <tool>${a.reset}`),!0)}case"/deny":{let{setPermission:o,savePermissions:r}=hr(),i=s.join(" ").trim();return i?(o(i,"deny"),r(),console.log(`${a.red}${i}: deny${a.reset}`),!0):(console.log(`${a.red}Usage: /deny <tool>${a.reset}`),!0)}case"/audit":{let{getAuditSummary:o,isAuditEnabled:r}=il();if(!r())return console.log(`${a.yellow}Audit logging is disabled (set NEX_AUDIT=true to enable)${a.reset}`),!0;let i=parseInt(s.join(" ").trim())||1,c=o(i);if(console.log(`
|
|
1569
1573
|
${a.bold}${a.cyan}Audit Summary (${i} day${i>1?"s":""})${a.reset}
|
|
1570
1574
|
`),console.log(` Total tool calls: ${a.bold}${c.totalCalls}${a.reset}`),console.log(` Avg duration: ${a.dim}${c.avgDuration}ms${a.reset}`),console.log(` Success rate: ${c.successRate>=.95?a.green:a.yellow}${Math.round(c.successRate*100)}%${a.reset}`),Object.keys(c.byTool).length>0){console.log(`
|
|
1571
|
-
${a.dim}Tool${" ".repeat(25)}Count${a.reset}`),console.log(` ${a.dim}${"\u2500".repeat(35)}${a.reset}`);let l=Object.entries(c.byTool).sort((u,d)=>d[1]-u[1]);for(let[u,d]of l.slice(0,15))console.log(` ${u.padEnd(30)}${d}`)}return console.log(),!0}case"/commit":{let{isGitRepo:o,commit:r,analyzeDiff:i,formatDiffSummary:c}=
|
|
1575
|
+
${a.dim}Tool${" ".repeat(25)}Count${a.reset}`),console.log(` ${a.dim}${"\u2500".repeat(35)}${a.reset}`);let l=Object.entries(c.byTool).sort((u,d)=>d[1]-u[1]);for(let[u,d]of l.slice(0,15))console.log(` ${u.padEnd(30)}${d}`)}return console.log(),!0}case"/commit":{let{isGitRepo:o,commit:r,analyzeDiff:i,formatDiffSummary:c}=Bn(),{confirm:l}=$t();if(!o())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let u=s.join(" ").trim();if(u){let m=await r(u);return console.log(m?`${a.green}Committed: ${m} \u2014 ${u}${a.reset}`:`${a.red}Commit failed${a.reset}`),!0}if(!i())return console.log(`${a.yellow}No changes to commit${a.reset}`),!0;let f=await c();if(console.log(f),!await l(" Commit changes?"))return!0;let g=await r("nex-code update");return g&&console.log(`${a.green} \u2713 Committed: ${g}${a.reset}`),!0}case"/diff":{let{isGitRepo:o,formatDiffSummary:r}=Bn();return o()?(console.log(r()),!0):(console.log(`${a.red}Not a git repository${a.reset}`),!0)}case"/review":{let{isGitRepo:o,getDiff:r}=Bn(),{processInput:i}=Ee(),c=s.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),f=`## Review Protocol
|
|
1572
1576
|
|
|
1573
1577
|
**Phase 1 \u2014 Broad Scan:** Read the target code and identify all issues at a high level.
|
|
1574
1578
|
|
|
@@ -1611,111 +1615,126 @@ ${f}
|
|
|
1611
1615
|
|
|
1612
1616
|
\`\`\`diff
|
|
1613
1617
|
${h.substring(0,2e4)}
|
|
1614
|
-
\`\`\``}return await i(p),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:i}=
|
|
1618
|
+
\`\`\``}return await i(p),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:i}=Bn();if(!o())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let c=s.join(" ").trim();if(!c){let u=r();return console.log(`${a.bold}${a.cyan}Branch:${a.reset} ${u||"(detached)"}`),!0}let l=i(c);return console.log(l?`${a.green}Created and switched to: ${l}${a.reset}`:`${a.red}Failed to create branch${a.reset}`),!0}case"/mcp":{let{listServers:o,connectAll:r,disconnectAll:i}=xi(),{getMcpTools:c,listMcpServers:l}=e$(),u=s.join(" ").trim();if(u==="list"){let f=l(),p=o();if(f.length===0&&p.length===0)return console.log(`${a.dim}No MCP servers connected${a.reset}`),console.log(`${a.dim}Configure servers in .nex/mcp.json then run /mcp connect${a.reset}`),!0;console.log(`
|
|
1615
1619
|
${a.bold}${a.cyan}Connected MCP Servers:${a.reset}`),f.length===0&&console.log(` ${a.dim}(none connected \u2014 run /mcp connect)${a.reset}`);for(let g of f){console.log(` ${a.green}\u2713${a.reset} ${a.bold}${g.name}${a.reset} \u2014 ${g.toolCount} tool(s)`);let m=c().filter(h=>h.function.name.startsWith(`mcp_${g.name}_`));for(let h of m)console.log(` ${a.cyan}${h.function.name}${a.reset} ${a.dim}${h.function.description}${a.reset}`)}return console.log(),!0}if(u==="status"){let f=o(),p=l(),g=new Set(p.map(m=>m.name));if(f.length===0&&p.length===0)return console.log(`${a.dim}No MCP servers configured${a.reset}`),console.log(`${a.dim}Add a .nex/mcp.json file with a "servers" block${a.reset}`),!0;console.log(`
|
|
1616
1620
|
${a.bold}${a.cyan}MCP Server Status:${a.reset}`);for(let m of f){let h=m.connected?`${a.green}\u2713 connected${a.reset}`:`${a.dim}\u25CB disconnected${a.reset}`;console.log(` ${h} ${a.bold}${m.name}${a.reset} (${m.command}) \u2014 ${m.toolCount} tools`)}for(let m of p)f.find(h=>h.name===m.name)||console.log(` ${a.green}\u2713 connected${a.reset} ${a.bold}${m.name}${a.reset} \u2014 ${m.toolCount} tools`);return console.log(),!0}if(u==="connect")return console.log(`${a.dim}Connecting MCP servers...${a.reset}`),r().then(f=>{for(let p of f)p.error?console.log(` ${a.red}\u2717${a.reset} ${p.name}: ${p.error}`):console.log(` ${a.green}\u2713${a.reset} ${p.name}: ${p.tools} tools`);f.length===0&&console.log(`${a.dim}No MCP servers configured in .nex/config.json${a.reset}`)}).catch(f=>{console.log(`${a.red}MCP connection error: ${f.message}${a.reset}`)}),!0;if(u==="disconnect")return i(),console.log(`${a.green}All MCP servers disconnected${a.reset}`),!0;let d=o();if(d.length===0)return console.log(`${a.dim}No MCP servers configured${a.reset}`),console.log(`${a.dim}Add servers to .nex/config.json under "mcpServers"${a.reset}`),!0;console.log(`
|
|
1617
1621
|
${a.bold}${a.cyan}MCP Servers:${a.reset}`);for(let f of d){let p=f.connected?`${a.green}\u2713 connected${a.reset}`:`${a.dim}\u25CB disconnected${a.reset}`;console.log(` ${p} ${a.bold}${f.name}${a.reset} (${f.command}) \u2014 ${f.toolCount} tools`)}return console.log(`
|
|
1618
1622
|
${a.dim}Use /mcp connect to connect all servers${a.reset}
|
|
1619
|
-
`),!0}case"/hooks":{let{listHooks:o}=
|
|
1620
|
-
${a.bold}${a.cyan}Hooks:${a.reset}`);for(let i of r){console.log(` ${a.cyan}${i.event}${a.reset}`);for(let c of i.commands)console.log(` ${a.dim}\u2192 ${c}${a.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:o,enableSkill:r,disableSkill:i}=
|
|
1623
|
+
`),!0}case"/hooks":{let{listHooks:o}=Rl(),r=o();if(r.length===0)return console.log(`${a.dim}No hooks configured${a.reset}`),console.log(`${a.dim}Add hooks to .nex/config.json or .nex/hooks/${a.reset}`),!0;console.log(`
|
|
1624
|
+
${a.bold}${a.cyan}Hooks:${a.reset}`);for(let i of r){console.log(` ${a.cyan}${i.event}${a.reset}`);for(let c of i.commands)console.log(` ${a.dim}\u2192 ${c}${a.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:o,enableSkill:r,disableSkill:i}=Cn(),c=s.join(" ").trim();if(c.startsWith("enable ")){let u=c.substring(7).trim();return r(u)?console.log(`${a.green}Skill enabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}if(c.startsWith("disable ")){let u=c.substring(8).trim();return i(u)?console.log(`${a.yellow}Skill disabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}let l=o();if(l.length===0)return console.log(`${a.dim}No skills loaded${a.reset}`),console.log(`${a.dim}Add .md or .js files to .nex/skills/${a.reset}`),!0;console.log(`
|
|
1621
1625
|
${a.bold}${a.cyan}Skills:${a.reset}`);for(let u of l){let d=u.enabled?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,f=u.type==="prompt"?`${a.dim}(prompt)${a.reset}`:`${a.dim}(script)${a.reset}`,p=[];u.commands>0&&p.push(`${u.commands} cmd`),u.tools>0&&p.push(`${u.tools} tools`);let g=p.length>0?` \u2014 ${p.join(", ")}`:"";console.log(` ${d} ${a.bold}${u.name}${a.reset} ${f}${g}`)}return console.log(`
|
|
1622
1626
|
${a.dim}Use /skills enable <name> or /skills disable <name>${a.reset}
|
|
1623
|
-
`),!0}case"/install-skill":{let o=s.join(" ").trim();if(!o)return console.log(`${a.yellow}Usage: /install-skill <git-url-or-user/repo>${a.reset}`),!0;let{installSkill:r}=
|
|
1627
|
+
`),!0}case"/install-skill":{let o=s.join(" ").trim();if(!o)return console.log(`${a.yellow}Usage: /install-skill <git-url-or-user/repo>${a.reset}`),!0;let{installSkill:r}=Cn();console.log(`${a.dim}Installing skill from ${o}...${a.reset}`);let i=await r(o);return i.ok?(console.log(`${a.green}Skill "${i.name}" installed successfully${a.reset}`),console.log(`${a.dim}Reload with /skills to see it${a.reset}`)):console.log(`${a.red}Failed: ${i.error}${a.reset}`),!0}case"/search-skill":{let o=s.join(" ").trim();if(!o)return console.log(`${a.yellow}Usage: /search-skill <query>${a.reset}`),!0;let{searchSkills:r}=Cn();console.log(`${a.dim}Searching for "${o}"...${a.reset}`);let i=await r(o);if(i.length===0)console.log(`${a.yellow}No skills found matching "${o}"${a.reset}`);else{console.log(`
|
|
1624
1628
|
${a.bold}Skills matching "${o}":${a.reset}
|
|
1625
1629
|
`);for(let c of i)c.name==="error"?console.log(` ${a.red}${c.description}${a.reset}`):(console.log(` ${a.cyan}${c.owner}/${c.name}${a.reset} ${a.dim}\u2605${c.stars}${a.reset}`),console.log(` ${c.description}`),console.log(` ${a.dim}/install-skill ${c.url}${a.reset}
|
|
1626
|
-
`))}return!0}case"/remove-skill":{let o=s.join(" ").trim();if(!o)return console.log(`${a.yellow}Usage: /remove-skill <name>${a.reset}`),!0;let{removeSkill:r}=
|
|
1630
|
+
`))}return!0}case"/remove-skill":{let o=s.join(" ").trim();if(!o)return console.log(`${a.yellow}Usage: /remove-skill <name>${a.reset}`),!0;let{removeSkill:r}=Cn(),i=r(o);return i.ok?console.log(`${a.green}Skill "${o}" removed${a.reset}`):console.log(`${a.red}${i.error}${a.reset}`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=Li();return s.join(" ").trim()==="clear"?(r(),console.log(`${a.green}Tasks cleared${a.reset}`),!0):(console.log(`
|
|
1627
1631
|
`+o()+`
|
|
1628
|
-
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=
|
|
1632
|
+
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=Rn(),i=o();if(!i)return console.log(`${a.yellow}Nothing to undo${a.reset}`),!0;i.wasCreated?console.log(`${a.green}Undone: deleted ${i.filePath} (was created by ${i.tool})${a.reset}`):console.log(`${a.green}Undone: restored ${i.filePath} (${i.tool})${a.reset}`);let c=r();return c>0&&console.log(`${a.dim}${c} more change(s) to undo${a.reset}`),!0}case"/redo":{let{redo:o,getRedoCount:r}=Rn(),i=o();if(!i)return console.log(`${a.yellow}Nothing to redo${a.reset}`),!0;console.log(`${a.green}Redone: ${i.filePath} (${i.tool})${a.reset}`);let c=r();return c>0&&console.log(`${a.dim}${c} more change(s) to redo${a.reset}`),!0}case"/history":{let{getHistory:o,getUndoCount:r,getRedoCount:i}=Rn(),c=o(20);if(c.length===0)return console.log(`${a.dim}No file changes in this session${a.reset}`),!0;console.log(`
|
|
1629
1633
|
${a.bold}File Change History${a.reset}
|
|
1630
1634
|
`);for(let l of c){let u=new Date(l.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${a.dim}${u}${a.reset} ${a.yellow}${l.tool}${a.reset} ${l.filePath}`)}return console.log(`
|
|
1631
1635
|
${a.dim}${r()} undo / ${i()} redo available${a.reset}
|
|
1632
|
-
`),!0}case"/snapshot":{let{createSnapshot:o,listSnapshots:r}=
|
|
1633
|
-
${a.bold}${a.cyan}Snapshots:${a.reset}`);for(let u of l)console.log(` ${a.cyan}#${u.index}${a.reset} ${a.bold}${u.shortName}${a.reset}`);console.log()}return!0}let c=o(i,
|
|
1636
|
+
`),!0}case"/snapshot":{let{createSnapshot:o,listSnapshots:r}=Rn(),i=s.join(" ").trim()||void 0;if(i==="list"){let l=r(Qt);if(l.length===0)console.log(`${a.dim}No snapshots found${a.reset}`);else{console.log(`
|
|
1637
|
+
${a.bold}${a.cyan}Snapshots:${a.reset}`);for(let u of l)console.log(` ${a.cyan}#${u.index}${a.reset} ${a.bold}${u.shortName}${a.reset}`);console.log()}return!0}let c=o(i,Qt);return c.ok?(console.log(`${a.green}Snapshot created:${a.reset} ${c.label}`),console.log(`${a.dim}Use /restore to apply it later${a.reset}`)):console.log(`${a.yellow}${c.error}${a.reset}`),!0}case"/restore":{let{restoreSnapshot:o,listSnapshots:r}=Rn(),i=s.join(" ").trim()||"last";if(i==="list"){let l=r(Qt);if(l.length===0)console.log(`${a.dim}No snapshots available${a.reset}`);else{console.log(`
|
|
1634
1638
|
${a.bold}${a.cyan}Available snapshots:${a.reset}`);for(let u of l)console.log(` ${a.cyan}#${u.index}${a.reset} ${a.bold}${u.shortName}${a.reset}`);console.log(`
|
|
1635
1639
|
${a.dim}Usage: /restore <name|last>${a.reset}
|
|
1636
|
-
`)}return!0}let c=o(i,
|
|
1640
|
+
`)}return!0}let c=o(i,Qt);return c.ok?(console.log(`${a.green}Restored snapshot:${a.reset} ${c.label}`),console.log(`${a.dim}Working tree updated. Use /undo for in-session file undos.${a.reset}`)):(console.log(`${a.red}Restore failed:${a.reset} ${c.error}`),console.log(`${a.dim}Use /snapshot list to see available snapshots${a.reset}`)),!0}case"/k8s":{let o=s.join(" ").trim(),{exec:r}=require("child_process"),{promisify:i}=require("util"),c=i(r),l=o||null,u=l?`ssh -o ConnectTimeout=10 -o BatchMode=yes ${l.replace(/[^a-zA-Z0-9@._-]/g,"")} `:"",d=f=>l?`${u}"${f.replace(/"/g,'\\"')}"`:f;console.log(`
|
|
1637
1641
|
${a.bold}${a.cyan}Kubernetes Overview${a.reset}${l?a.dim+" (remote: "+l+")"+a.reset:""}
|
|
1638
1642
|
`);try{let{stdout:f}=await c(d("kubectl get namespaces --no-headers -o custom-columns=NAME:.metadata.name"),{timeout:15e3}),p=f.trim().split(`
|
|
1639
1643
|
`).filter(Boolean);console.log(`${a.bold}Namespaces (${p.length}):${a.reset}`);for(let g of p)console.log(` ${a.cyan}${g}${a.reset}`);console.log()}catch{return console.log(`${a.dim}Could not reach cluster \u2014 is kubectl configured?${a.reset}
|
|
1640
1644
|
`),!0}try{let{stdout:f}=await c(d("kubectl get pods -A --no-headers -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,READY:.status.containerStatuses[0].ready,STATUS:.status.phase,RESTARTS:.status.containerStatuses[0].restartCount"),{timeout:2e4}),p=f.trim().split(`
|
|
1641
|
-
`).filter(Boolean),g=p.filter(
|
|
1642
|
-
`);let y=p.filter(
|
|
1645
|
+
`).filter(Boolean),g=p.filter(b=>b.includes("Running")).length,m=p.filter(b=>b.includes("Pending")).length,h=p.filter(b=>b.includes("Failed")||b.includes("Error")||b.includes("CrashLoop")).length;console.log(`${a.bold}Pods: ${p.length} total ${a.green}${g} running${a.reset} ${a.yellow}${m} pending${a.reset} ${a.red}${h} unhealthy${a.reset}
|
|
1646
|
+
`);let y=p.filter(b=>!b.includes("Running")&&!b.includes("<none>"));if(y.length>0){console.log(`${a.bold}${a.red}Unhealthy Pods:${a.reset}`);for(let b of y)console.log(` ${a.red}${b}${a.reset}`);console.log()}console.log(`${a.dim}Use k8s_pods / k8s_logs / k8s_exec tools for details${a.reset}`),console.log(`${a.dim}Or: /k8s user@host to query a remote cluster${a.reset}
|
|
1643
1647
|
`)}catch(f){console.log(`${a.dim}Could not list pods: ${f.message}${a.reset}
|
|
1644
|
-
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:r,sshExec:i}=
|
|
1648
|
+
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:r,sshExec:i}=ro(),c=o(),l=Object.keys(c);if(l.length===0)return console.log(`
|
|
1645
1649
|
${a.dim}No servers configured. Create .nex/servers.json:${a.reset}`),console.log(`${a.dim} { "prod": { "host": "1.2.3.4", "user": "deploy", "os": "almalinux9" } }${a.reset}
|
|
1646
1650
|
`),!0;if(s[0]==="ping"){let f=s[1]?[s[1]]:l;return console.log(`
|
|
1647
|
-
${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(f.map(async p=>{if(!c[p]){console.log(` ${a.red}\u2717${a.reset} ${p} \u2014 unknown profile`);return}try{let g={...c[p],_name:p},{exitCode:m}=await i(g,"echo ok",{timeout:8e3});console.log(m===0?` ${a.green}\u2713${a.reset} ${p} (${g.user?g.user+"@":""}${g.host})`:` ${a.red}\u2717${a.reset} ${p} (${g.host}) \u2014 SSH failed (exit ${m})`)}catch(g){console.log(` ${a.red}\u2717${a.reset} ${p} \u2014 ${g.message}`)}})),console.log(""),!0}let{formatProfile:d}=
|
|
1651
|
+
${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(f.map(async p=>{if(!c[p]){console.log(` ${a.red}\u2717${a.reset} ${p} \u2014 unknown profile`);return}try{let g={...c[p],_name:p},{exitCode:m}=await i(g,"echo ok",{timeout:8e3});console.log(m===0?` ${a.green}\u2713${a.reset} ${p} (${g.user?g.user+"@":""}${g.host})`:` ${a.red}\u2717${a.reset} ${p} (${g.host}) \u2014 SSH failed (exit ${m})`)}catch(g){console.log(` ${a.red}\u2717${a.reset} ${p} \u2014 ${g.message}`)}})),console.log(""),!0}let{formatProfile:d}=ro();console.log(`
|
|
1648
1652
|
${a.bold}${a.cyan}Configured servers (${l.length}):${a.reset}`);for(let f of l)console.log(` ${a.green}${f}${a.reset} ${a.dim}${d(f,c[f])}${a.reset}`);return console.log(`
|
|
1649
1653
|
${a.dim}/servers ping \u2014 check SSH connectivity for all servers${a.reset}`),console.log(`${a.dim}/servers ping <name> \u2014 check a specific server${a.reset}
|
|
1650
|
-
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=
|
|
1654
|
+
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=ro(),{exec:i}=require("child_process"),{promisify:c}=require("util"),l=c(i),u=s[0]==="-a"||s[0]==="--all"?'docker ps -a --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"':'docker ps --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"',d=o(),f=[["local",null],...Object.entries(d)];console.log(`
|
|
1651
1655
|
${a.bold}${a.cyan}Docker Containers:${a.reset}`);for(let[p,g]of f){let m=p==="local"?`${a.dim}local${a.reset}`:`${a.cyan}${p}${a.reset}`;try{let h;if(p==="local"){let{stdout:y}=await l(u,{timeout:8e3});h=(y||"").trim()}else{let y=await r(g,u,{timeout:1e4});if(h=[y.stdout,y.stderr].filter(Boolean).join("").trim(),y.exitCode!==0){console.log(` ${m}: ${a.red}SSH error (${y.exitCode})${a.reset}`);continue}}!h||h==="NAMES IMAGE STATUS PORTS"?console.log(` ${m}: ${a.dim}(no containers)${a.reset}`):(console.log(` ${m}:`),h.split(`
|
|
1652
|
-
`).forEach(y=>console.log(` ${a.dim}${y}${a.reset}`)))}catch(h){console.log(` ${m}: ${a.red}${h.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=
|
|
1656
|
+
`).forEach(y=>console.log(` ${a.dim}${y}${a.reset}`)))}catch(h){console.log(` ${m}: ${a.red}${h.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=Uc(),r=o(),i=Object.keys(r),c=s[0];if(c&&i.includes(c)){let l=s.includes("--dry-run")||s.includes("-n"),u=r[c],{executeTool:d}=en();console.log(`
|
|
1653
1657
|
${a.bold}Running deploy: ${c}${l?" (dry run)":""}${a.reset}`);let f=await d("deploy",{...u,dry_run:l});return console.log(f),!0}if(i.length===0)return console.log(`
|
|
1654
1658
|
${a.dim}No deploy configs. Run /init to create .nex/deploy.json${a.reset}
|
|
1655
1659
|
`),!0;console.log(`
|
|
1656
1660
|
${a.bold}${a.cyan}Deploy configs (${i.length}):${a.reset}`);for(let[l,u]of Object.entries(r)){let d=u.method||"rsync",f=`[${d}]`,p=d==="git"?`${u.server}:${u.remote_path}${u.branch?` (${u.branch})`:""}`:`${u.local_path||""} \u2192 ${u.server}:${u.remote_path}`,g=[u.deploy_script?`script: ${u.deploy_script}`:null,u.health_check?`health: ${u.health_check}`:null].filter(Boolean).map(m=>` ${a.dim}\u2192 ${m}${a.reset}`).join("");console.log(` ${a.green}${l}${a.reset} ${a.dim}${f} ${p}${a.reset}${g}`)}return console.log(`
|
|
1657
1661
|
${a.dim}/deploy <name> \u2014 run a named deploy${a.reset}`),console.log(`${a.dim}/deploy <name> --dry-run \u2014 preview without syncing${a.reset}
|
|
1658
|
-
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:i}=
|
|
1659
|
-
`)}}catch{}if(s.includes("--history")){let y=require("os"),
|
|
1660
|
-
${a.bold}${a.cyan}OpenClaw Nightly Results (${
|
|
1661
|
-
`),console.log(` ${a.dim}${"Date".padEnd(12)} ${"Model".padEnd(25)} ${"Score".padEnd(8)} ${"Pass".padEnd(8)}${a.reset}`),console.log(` ${a.dim}${"\u2500".repeat(58)}${a.reset}`);let C=[];for(let k of
|
|
1662
|
-
${a.bold}Trend:${a.reset} ${B}${a.reset} over ${C.length} days`)}}console.log();break}if(s.includes("--all")){let{fetchCloudModels:y,markBenchmarked:
|
|
1663
|
-
${a.bold}Fetching all available Ollama Cloud models...${a.reset}`);let ie;try{ie=await y()}catch(I){console.log(`${a.red}Failed to fetch model list: ${I.message}${a.reset}`);break}let Q=ie.filter(I=>!B.has(I)),O=ie.filter(I=>B.has(I)),
|
|
1664
|
-
`);let V=new Map,fe=await
|
|
1665
|
-
${a.cyan}${I.padEnd(30)}${a.reset} `));return}let ee=J?`${a.red}\u2717${a.reset}`:
|
|
1666
|
-
`);let he=require("os"),be=require("path").join(he.homedir(),".nex-code","benchmark-results.json");try{require("fs").writeFileSync(be,JSON.stringify(fe,null,2))}catch{}
|
|
1667
|
-
${a.green}README.md benchmark table updated${a.reset}`),A.updated&&console.log(`${a.green}DEFAULT_MODEL: ${A.previousModel} \u2192 ${A.newModel}${a.reset}`),
|
|
1668
|
-
${a.bold}Checking Ollama Cloud for new models...${a.reset}`);let
|
|
1662
|
+
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:i}=o$();return i(e),s[0]==="deploy"?await r():await o(),!0}case"/setup":{let{runSetupWizard:o}=uu();return await o({rl:e,force:!0}),!0}case"/benchmark":{try{let y=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(pt.existsSync(y)){let b=(Date.now()-pt.statSync(y).mtimeMs)/864e5;b>30&&console.log(`${a.dim} \u2139 Benchmark results are ${Math.floor(b)} days old \u2014 run /benchmark --all to refresh${a.reset}
|
|
1663
|
+
`)}}catch{}if(s.includes("--history")){let y=require("os"),b=at.join(y.homedir(),"Coding","nex-code-benchmarks","results");if(!pt.existsSync(b)){console.log(`${a.yellow}No nightly results at ${b}${a.reset}`),console.log(`${a.dim}Use /benchmark (no flags) to run a live model comparison.${a.reset}`);break}let S=pt.readdirSync(b).filter(k=>k.endsWith(".json")).sort().slice(-7);if(S.length===0){console.log(`${a.yellow}No result files found${a.reset}`);break}console.log(`
|
|
1664
|
+
${a.bold}${a.cyan}OpenClaw Nightly Results (${S.length}-day trend)${a.reset}
|
|
1665
|
+
`),console.log(` ${a.dim}${"Date".padEnd(12)} ${"Model".padEnd(25)} ${"Score".padEnd(8)} ${"Pass".padEnd(8)}${a.reset}`),console.log(` ${a.dim}${"\u2500".repeat(58)}${a.reset}`);let C=[];for(let k of S)try{let x=JSON.parse(pt.readFileSync(at.join(b,k),"utf-8")),E=k.replace(".json",""),B=x.tasks?.length||x.total||0,q=x.tasks?.filter(O=>O.passed||O.score>=.7)?.length||x.passed||0,re=x.score??x.overall_score??(B>0?Math.round(q/B*100):"N/A"),ie=x.model||x.config?.model||"unknown";C.push({date:E,model:ie,total:B,passed:q,score:re});let Q=typeof re=="number"?re>=80?a.green:re>=60?a.yellow:a.red:a.dim;console.log(` ${E.padEnd(12)} ${ie.substring(0,24).padEnd(25)} ${Q}${String(re).padEnd(8)}${a.reset} ${q}/${B}`)}catch{}if(C.length>=2){let k=C[0].score,x=C[C.length-1].score;if(typeof k=="number"&&typeof x=="number"){let E=x-k,B=E>0?`${a.green}\u25B2 +${E}`:E<0?`${a.red}\u25BC ${E}`:`${a.dim}\u2192 stable`;console.log(`
|
|
1666
|
+
${a.bold}Trend:${a.reset} ${B}${a.reset} over ${C.length} days`)}}console.log();break}if(s.includes("--all")){let{fetchCloudModels:y,markBenchmarked:b,updateReadme:S,updateModelsEnv:C,updateRoutingConfig:k}=To(),{runBenchmark:x,buildCategoryWinners:E}=Zn(),B=new Set(["nemotron-3-super:cloud"]),q=s.find(I=>I.startsWith("--parallel=")),re=q?Math.max(1,parseInt(q.replace("--parallel=",""),10)||3):3;console.log(`
|
|
1667
|
+
${a.bold}Fetching all available Ollama Cloud models...${a.reset}`);let ie;try{ie=await y()}catch(I){console.log(`${a.red}Failed to fetch model list: ${I.message}${a.reset}`);break}let Q=ie.filter(I=>!B.has(I)),O=ie.filter(I=>B.has(I)),Te=56,X=Math.ceil(Te*Q.length*4/re/60);console.log(`${a.cyan}${Q.length} models found${a.reset}`+(O.length>0?` ${a.dim}(${O.length} blacklisted: ${O.join(", ")})${a.reset}`:"")),console.log(`${a.dim}Models: ${Q.join(", ")}${a.reset}`),console.log(`${a.dim}${Te} tasks \xB7 ${re} parallel \xB7 ~${X}min estimated${a.reset}
|
|
1668
|
+
`);let V=new Map,fe=await x({models:Q,quick:!1,parallelModels:re,onProgress:({model:I,task:M,done:N,score:T,error:J})=>{if(!N){V.has(I)||(V.set(I,""),process.stdout.write(`
|
|
1669
|
+
${a.cyan}${I.padEnd(30)}${a.reset} `));return}let ee=J?`${a.red}\u2717${a.reset}`:T>=80?`${a.green}\xB7${a.reset}`:T>=40?`${a.yellow}\xB7${a.reset}`:`${a.red}\xB7${a.reset}`;process.stdout.write(ee)}});process.stdout.write(`
|
|
1670
|
+
`);let he=require("os"),be=require("path").join(he.homedir(),".nex-code","benchmark-results.json");try{require("fs").writeFileSync(be,JSON.stringify(fe,null,2))}catch{}b(Q);let ye=E(fe),Re=k(ye),v=require("path").join(process.cwd(),"README.md"),j=S(fe,v),A=C(fe);if(j&&console.log(`
|
|
1671
|
+
${a.green}README.md benchmark table updated${a.reset}`),A.updated&&console.log(`${a.green}DEFAULT_MODEL: ${A.previousModel} \u2192 ${A.newModel}${a.reset}`),Re.changes.length>0){console.log(`${a.green}Routing updated:${a.reset}`);for(let I of Re.changes)console.log(` ${a.dim}${I}${a.reset}`)}return console.log(),!0}if(s.includes("--discover")){let{findNewModels:y,markBenchmarked:b,updateReadme:S,updateModelsEnv:C}=To(),{runDiscoverBenchmark:k,buildSummary:x}=Zn();console.log(`
|
|
1672
|
+
${a.bold}Checking Ollama Cloud for new models...${a.reset}`);let E;try{E=await y()}catch(v){console.log(`${a.red}Discovery failed: ${v.message}${a.reset}`);break}let{newModels:B,allCloud:q}=E;if(console.log(`${a.dim}${q.length} models available on cloud${a.reset}`),B.length===0){console.log(`${a.green}No new models since last benchmark run.${a.reset}
|
|
1669
1673
|
`);break}console.log(`${a.cyan}New models to benchmark (${B.length}):${a.reset} ${B.join(", ")}
|
|
1670
|
-
`);let re=require("os"),ie=
|
|
1674
|
+
`);let re=require("os"),ie=at.join(re.homedir(),".nex-code","benchmark-results.json"),Q=[];try{pt.existsSync(ie)&&(Q=JSON.parse(pt.readFileSync(ie,"utf-8")))}catch{}let O="",Te=await k({newModels:B,existingRanking:Q,onProgress:({model:v,task:j,done:A,score:I,error:M})=>{if(!A){v!==O&&(O&&process.stdout.write(`
|
|
1671
1675
|
`),O=v,process.stdout.write(`${a.cyan}${v}${a.reset} `));return}let N=M?`${a.red}\u2717${a.reset}`:I>=80?`${a.green}\xB7${a.reset}`:I>=40?`${a.yellow}\xB7${a.reset}`:`${a.red}\xB7${a.reset}`;process.stdout.write(N)}});O&&process.stdout.write(`
|
|
1672
|
-
`);try{
|
|
1676
|
+
`);try{pt.writeFileSync(ie,JSON.stringify(Te,null,2))}catch{}b(q);let X=at.join(process.cwd(),"README.md"),V=S(Te,X),fe=C(Te),{buildCategoryWinners:he}=Zn(),{updateRoutingConfig:be}=To(),ye=he(Te),Re=be(ye);if(V&&console.log(`${a.green}README.md benchmark table updated${a.reset}`),fe.updated?console.log(`${a.green}DEFAULT_MODEL: ${fe.previousModel} \u2192 ${fe.newModel}${a.reset}`):fe.reason&&console.log(`${a.dim}models.env unchanged: ${fe.reason}${a.reset}`),Re.changes.length>0){console.log(`${a.green}Routing updated:${a.reset}`);for(let v of Re.changes)console.log(` ${a.dim}${v}${a.reset}`)}return console.log(),!0}let{runBenchmark:o,DEFAULT_MODELS:r,QUICK_MODELS:i}=Zn(),c=s.includes("--quick"),l=s.find(y=>y.startsWith("--models=")),u=l?l.replace("--models=","").split(",").map(y=>y.trim()).filter(Boolean):[],d=c?7:15,f=u.length>0?u:c?i:r;console.log(`
|
|
1673
1677
|
${a.bold}Starting benchmark${a.reset} ${a.dim}${d} tasks \xB7 ${f.length} models \xB7 ollama cloud${a.reset}`),console.log(`${a.dim}Models: ${f.join(", ")}${a.reset}
|
|
1674
|
-
`);let p="",g=0,m=d*f.length,h=await o({models:f,quick:c,onProgress:({model:y,task:
|
|
1675
|
-
`),p=y,process.stdout.write(`${a.cyan}${y}${a.reset} `));return}g++;let
|
|
1676
|
-
`),!c&&h&&h.length>0){let{buildCategoryWinners:y}=
|
|
1677
|
-
${a.bold}Per-category routing saved:${a.reset}`);for(let re of
|
|
1678
|
+
`);let p="",g=0,m=d*f.length,h=await o({models:f,quick:c,onProgress:({model:y,task:b,done:S,score:C,error:k})=>{if(!S){y!==p&&(p&&process.stdout.write(`
|
|
1679
|
+
`),p=y,process.stdout.write(`${a.cyan}${y}${a.reset} `));return}g++;let x=k?`${a.red}\u2717${a.reset}`:C>=80?`${a.green}\xB7${a.reset}`:C>=40?`${a.yellow}\xB7${a.reset}`:`${a.red}\xB7${a.reset}`;process.stdout.write(x)}});if(p&&process.stdout.write(`
|
|
1680
|
+
`),!c&&h&&h.length>0){let{buildCategoryWinners:y}=Zn(),{updateRoutingConfig:b,updateReadme:S,updateModelsEnv:C}=To(),k=y(h),x=b(k);if(x.changes.length>0){console.log(`
|
|
1681
|
+
${a.bold}Per-category routing saved:${a.reset}`);for(let re of x.changes)console.log(` ${a.dim}${re}${a.reset}`)}let E=at.join(process.cwd(),"README.md");S(h,E)&&console.log(`${a.green}README.md updated${a.reset}`),C(h);let B=require("os"),q=at.join(B.homedir(),".nex-code","benchmark-results.json");try{pt.writeFileSync(q,JSON.stringify(h,null,2))}catch{}}return!0}case"/bench":{let{runScenarioBenchmark:o}=Zn(),r=s.includes("--dry-run"),i=s.find(l=>l.startsWith("--model=")),c=i?i.replace("--model=","").trim():void 0;return r||console.log(`
|
|
1678
1682
|
${a.bold}Scenario Benchmark${a.reset} ${a.dim}5 agentic scenarios \xB7 each run as child process${a.reset}
|
|
1679
|
-
`),await o({dryRun:r,model:c,cwd:
|
|
1680
|
-
`)}}}),!0}case"/trend":{let{showScoreTrend:o}=
|
|
1683
|
+
`),await o({dryRun:r,model:c,cwd:Qt,onProgress:({id:l,name:u,done:d,score:f,grade:p})=>{if(!d)process.stdout.write(`${a.dim} \u2192 ${u}...${a.reset}`);else{let g=f>=8?a.green:f>=6?a.yellow:a.red;process.stdout.write(` ${g}${f}/10 (${p})${a.reset}
|
|
1684
|
+
`)}}}),!0}case"/trend":{let{showScoreTrend:o}=Zn(),r=parseInt(s[0],10)||10;return o(r),!0}case"/orchestrate":{let o=s.join(" ").trim();if(!o)return console.log(`${a.yellow}Usage: /orchestrate <prompt>${a.reset}`),console.log(`${a.dim}Example: /orchestrate fix login bug, update docs, add dark mode${a.reset}`),!0;let{runOrchestrated:r}=$r();return await r(o),!0}case"/bench-orchestrator":{let{runOrchestratorBenchmark:o,printResults:r}=E$(),i=s.find(u=>u.startsWith("--models=")),c=i?i.replace("--models=","").split(",").map(u=>u.trim()):void 0,l=await o({models:c,onProgress:({model:u,scenario:d,done:f,score:p,error:g})=>{f?g?process.stdout.write(` ${a.red}ERR${a.reset}
|
|
1681
1685
|
`):process.stdout.write(` ${a.green}${p}/10${a.reset}
|
|
1682
|
-
`):process.stdout.write(`${a.dim} \u2192 ${u}: ${d}...${a.reset}`)}});return r(l),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:{let o=
|
|
1683
|
-
`).filter(Boolean).slice(-
|
|
1684
|
-
`)}catch{}}function
|
|
1685
|
-
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:
|
|
1686
|
+
`):process.stdout.write(`${a.dim} \u2192 ${u}: ${d}...${a.reset}`)}});return r(l),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:{let o=d1(t);if(o)return o.agentPrompt&&(Wr._pendingAgentPrompt=o.agentPrompt),!0;{let r=[...Hr,...Da()].map(u=>u.cmd.split(" ")[0]),i=(u,d)=>{let f=u.length,p=d.length,g=Array.from({length:f+1},(m,h)=>Array.from({length:p+1},(y,b)=>h===0?b:b===0?h:0));for(let m=1;m<=f;m++)for(let h=1;h<=p;h++)g[m][h]=u[m-1]===d[h-1]?g[m-1][h-1]:1+Math.min(g[m-1][h],g[m][h-1],g[m-1][h-1]);return g[f][p]},c=null,l=3;for(let u of r){let d=i(n,u);d<l&&(l=d,c=u)}console.log(c?`${a.red}Unknown command: ${n}.${a.reset} ${a.dim}Did you mean ${a.reset}${a.cyan}${c}${a.reset}${a.dim}? Type /help for all commands.${a.reset}`:`${a.red}Unknown command: ${n}. Type /help${a.reset}`)}return!0}}}var Pu=1e3;function Lu(){return at.join(process.cwd(),".nex","repl_history")}function q$(){try{let t=Lu();if(pt.existsSync(t))return pt.readFileSync(t,"utf-8").split(`
|
|
1687
|
+
`).filter(Boolean).slice(-Pu)}catch{}return[]}function ja(t){try{let e=Lu(),n=at.dirname(e);pt.existsSync(n)||pt.mkdirSync(n,{recursive:!0}),pt.appendFileSync(e,t+`
|
|
1688
|
+
`)}catch{}}function Bt(){return`${a.bold}${a.cyan}\u203A${a.reset} `}function Ur(){if(!global._nexFooter)return;let{isPlanMode:t,getAutonomyLevel:e}=rn(),{getAutoConfirm:n}=$t(),s=[];t()&&s.push("plan");let o=e();o==="semi-auto"&&s.push("semi"),o==="autonomous"&&s.push("auto"),n()&&s.push("always"),global._nexFooter.setStatusInfo({mode:s.join(" \xB7 ")})}var Iu="\x1B[200~",ju="\x1B[201~";function g1(t){return typeof t=="string"&&t.includes(Iu)}function $1(t){return typeof t=="string"&&t.includes(ju)}function Br(t){return typeof t!="string"?t:t.split(Iu).join("").split(ju).join("")}async function y1(){if(!i1("local"))return!1;try{let{exec:e}=require("child_process"),{promisify:n}=require("util");return await n(e)("curl -s --max-time 1 http://localhost:11434/api/tags"),Mu("local:llama3"),!0}catch{return!1}}async function w1(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:n}=Ee();t(M$);let o=Nu().some(T=>T.configured),r=(async()=>{u1();let T=Dn(),J=Ms();return{model:T,providerName:J}})(),i=(async()=>o?!0:await y1()?(console.log(`${a.green}\u2713 Local Ollama detected \u2014 using local models${a.reset}`),console.log(`${a.dim}Tip: Set API keys for cloud providers for more model options (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${a.reset}
|
|
1689
|
+
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:T}=C$();return await T()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,i,c]);!u&&!o&&(console.error(`
|
|
1686
1690
|
${a.red}\u2717 No provider configured and no local Ollama detected.${a.reset}
|
|
1687
|
-
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:p}=
|
|
1688
|
-
${Z}\x1B[33m\u2753${ee} ${Z}${
|
|
1691
|
+
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:p}=Rn();f().then(T=>{}),p().catch(()=>{});let g=q$(),m=t1.createInterface({input:process.stdin,output:process.stdout,prompt:Bt(),completer:I$,history:g,historySize:Pu});f1(m);let{setAskUserHandler:h}=en();h(async(T,J)=>{let ee="\x1B[0m",Z="\x1B[1m",ge="\x1B[2m",Se="\x1B[36m";return process.stdout.write(`
|
|
1692
|
+
${Z}\x1B[33m\u2753${ee} ${Z}${T}${ee}
|
|
1689
1693
|
|
|
1690
|
-
`),J.forEach((Ne,Ue)=>{process.stdout.write(` ${
|
|
1694
|
+
`),J.forEach((Ne,Ue)=>{process.stdout.write(` ${Se}${Ue+1}${ee} ${Ne}
|
|
1691
1695
|
`)}),process.stdout.write(` ${ge}${J.length+1}${ee} ${ge}Eigene Antwort\u2026${ee}
|
|
1692
1696
|
`),process.stdout.write(`
|
|
1693
|
-
${
|
|
1694
|
-
`),Ne(J[qe-1])):qe===J.length+1||
|
|
1695
|
-
`),Ne(
|
|
1696
|
-
`),Ne(
|
|
1697
|
-
`),await
|
|
1698
|
-
`)}}catch{}},2e3);let
|
|
1699
|
-
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),
|
|
1700
|
-
`).replace(/\r/g,"").trim();if(q=[],B=!1,!
|
|
1701
|
-
`).length,Z=ee>1?`[Pasted content #${J} \u2014 ${ee} lines]`:`[Pasted content #${J}]`,ge=m.line||"",
|
|
1702
|
-
`)),O()}if(ge){B=!0,q=[];let xe=
|
|
1703
|
-
`)),!0}if(
|
|
1704
|
-
`)),O()}if(B){let xe=
|
|
1697
|
+
${Se}[1-${J.length+1}]${ee} \u203A `),new Promise(Ne=>{m.resume(),m.once("line",Ue=>{let bt=Ue.trim(),qe=parseInt(bt);qe>=1&&qe<=J.length?(process.stdout.write(`
|
|
1698
|
+
`),Ne(J[qe-1])):qe===J.length+1||bt===""?(process.stdout.write(` ${Se}\u203A${ee} `),m.once("line",Wt=>{process.stdout.write(`
|
|
1699
|
+
`),Ne(Wt.trim()||"")})):(process.stdout.write(`
|
|
1700
|
+
`),Ne(bt))})})});let y=new h1;y.activate(m),global._nexFooter=y,global._nexRawWrite=T=>y.rawWrite(T),m1(()=>Ur()),process.stdout.isTTY&&process.stdout.write("\x1B[H\x1B[2J\x1B[3J");let b=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;n1(b,Qt,{yolo:Au()});{y.setStatusInfo({model:b,branch:"",project:at.basename(Qt)});let{execFile:T}=require("child_process");T("git",["rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"},(J,ee)=>{!J&&ee&&y.setStatusInfo({model:b,branch:ee.trim(),project:at.basename(Qt)})})}d.hasNewVersion&&console.log(`${a.yellow}\u{1F4A1} New version available!${a.reset} Run ${a.cyan}npm update -g nex-code${a.reset} to upgrade from ${a.dim}${d.currentVersion}${a.reset} to ${a.green}${d.latestVersion}${a.reset}
|
|
1701
|
+
`),await N$(Qt),setTimeout(()=>{try{if(c1()){let{insights:T}=l1();T.length>0&&process.stdout.write(`${a.dim}\u{1F4AD} Dream consolidated ${T.length} insight(s) from recent sessions${a.reset}
|
|
1702
|
+
`)}}catch{}},2e3);let S=!1,C=0,k=!1,x=null;function E(){O$();try{let{getConversationMessages:T}=Ee();a1(T())}catch{}y.deactivate(),A$(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)}process.on("SIGTERM",E),process.on("exit",()=>{O$()}),m.on("SIGINT",()=>{if(A$(),C++,C>=2){E();return}if(S){pn&&pn.abort();let{cancelPendingAskUser:T}=en();T(),console.log(`
|
|
1703
|
+
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),S=!1,m.setPrompt(Bt()),m.prompt()}else console.log(`${a.dim} (Press Ctrl+C again to exit)${a.reset}`),m.setPrompt(Bt()),m.prompt(),x&&clearTimeout(x),x=setTimeout(()=>{C=0,x=null},2e3)}),process.on("SIGINT",()=>{process.stdin.isTTY?(C++,C>=2&&E()):E()});let B=!1,q=[],re=0,ie={},Q=!1;function O(){let T=q.join(`
|
|
1704
|
+
`).replace(/\r/g,"").trim();if(q=[],B=!1,!T)return!0;re++,Q=!0;let J=re;ie[J]=T;let ee=T.split(`
|
|
1705
|
+
`).length,Z=ee>1?`[Pasted content #${J} \u2014 ${ee} lines]`:`[Pasted content #${J}]`,ge=m.line||"",Se=ge&&!ge.endsWith(" ")?" ":"",xe=ge+Se+Z;return m.setPrompt(Bt()),m.prompt(),m.line=xe,m.cursor=xe.length,m._refreshLine(),!0}function Te(T){return T.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(J,ee)=>ie[Number(ee)]||"")}function X(){re=0,ie={},Q=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let T=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(J,...ee){if(J!=="data")return T.call(process.stdin,J,...ee);let Z=ee[0];if(Buffer.isBuffer(Z)&&(Z=Z.toString("utf8")),typeof Z!="string")return T.call(process.stdin,J,...ee);let ge=Z.includes(Iu),Se=Z.includes(ju);if(ge&&Se){let xe=Br(Z);return xe&&q.push(...xe.split(`
|
|
1706
|
+
`)),O()}if(ge){B=!0,q=[];let xe=Br(Z);return xe&&q.push(...xe.split(`
|
|
1707
|
+
`)),!0}if(Se){let xe=Br(Z);return xe&&q.push(...xe.split(`
|
|
1708
|
+
`)),O()}if(B){let xe=Br(Z);return xe&&q.push(...xe.split(`
|
|
1705
1709
|
`)),!0}return Z.includes(`
|
|
1706
1710
|
`)&&Z.length>40&&!B?(q.push(...Z.replace(/\r/g,"").split(`
|
|
1707
|
-
`)),O()):
|
|
1708
|
-
${ge}. `).trim()}let{loadSession:M}=
|
|
1709
|
-
`),m.prompt()}return}if(j!==null){if(j._mode==="triple"){if(
|
|
1710
|
-
`).trim();if(j=null,ge){
|
|
1711
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${Ne}${a.reset}`)}}
|
|
1712
|
-
`).trim();if(j=null,ge){
|
|
1713
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${Ue}${a.reset}`)}}let{getConversationLength:
|
|
1714
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${xe}${a.reset}`)}}
|
|
1715
|
-
`);process.stdout.isTTY&&process.stdout.write(`\x1B[${xe.length}A`),xe.forEach((Ne,Ue)=>{let
|
|
1716
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${
|
|
1717
|
-
`)}function
|
|
1718
|
-
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}
|
|
1711
|
+
`)),O()):T.call(process.stdin,J,...ee)}}let V=0,fe=-1,he=[],be="";function ye(){if(V>0){let T=y._scrollEnd,J="\x1B7";for(let ee=0;ee<V;ee++)J+=`\x1B[${T-V+1+ee};1H\x1B[2K`;J+="\x1B8",y.rawWrite(J),V=0}}function Re(){ye(),fe=-1,he=[],be=""}function v(T,J=-1){let ee=[...Hr,...Da()].filter(qe=>qe.cmd.startsWith(T));if(!ee.length||ee.length===1&&ee[0].cmd===T&&J<0)return;let Z=y._scrollEnd,ge=Math.min(10,Z-2);if(ge<1)return;let Se=ee.slice(0,ge),xe=Math.max(...Se.map(qe=>qe.cmd.length));V=Se.length,he=ee,be=T,ee.length>ge&&V++;let Ne=Z-V+1,Ue="\x1B7",bt=(y._cols||80)-1;for(let qe=0;qe<Se.length;qe++){let{cmd:Wt,desc:Qn}=Se[qe],Co=Math.max(0,xe-Wt.length+2),es=2+Wt.length+Co,Is=Qn;if(es+Qn.length>bt){let js=Math.max(0,bt-es-3);js>0?Is=Qn.substring(0,js)+"...":(Is="",Co=1)}let Kr=" ".repeat(Co);if(qe===J)Ue+=`\x1B[${Ne+qe};1H\x1B[2K \x1B[7m ${a.bold}${Wt}${a.reset}\x1B[7m${Kr}${Is}\x1B[27m${a.reset}`;else{let js=Wt.substring(0,T.length),Fa=Wt.substring(T.length);Ue+=`\x1B[${Ne+qe};1H\x1B[2K ${a.cyan}${js}${a.reset}${a.dim}${Fa}${Kr}${Is}${a.reset}`}}ee.length>ge&&(Ue+=`\x1B[${Ne+Se.length};1H\x1B[2K ${a.dim}\u2026 +${ee.length-ge} more${a.reset}`),Ue+="\x1B8",y.rawWrite(Ue)}if(process.stdin.isTTY){let T=m._ttyWrite.bind(m),J=!1;m._ttyWrite=function(ee,Z){if(J)return T(ee,Z);if(V>0&&Z&&!Z.ctrl&&!Z.meta){let ge=Math.min(he.length,10)-1;if(Z.name==="down"){fe=Math.min(fe+1,ge),J=!0,m.write(null,{ctrl:!0,name:"u"}),m.write(fe>=0?he[fe].cmd:be),J=!1,ye(),v(be,fe);return}if(Z.name==="up"){if(fe===-1)fe=Math.min(he.length,10)-1;else if(fe>0)fe--;else{fe=-1,J=!0,m.write(null,{ctrl:!0,name:"u"}),m.write(be),J=!1,ye(),v(be,-1);return}J=!0,m.write(null,{ctrl:!0,name:"u"}),m.write(he[fe].cmd),J=!1,ye(),v(be,fe);return}}return T(ee,Z)},process.stdin.on("keypress",(ee,Z)=>{V>0&&Z&&(Z.name==="down"||Z.name==="up")||(Re(),!(Z&&(Z.name==="tab"||Z.name==="return"))&&setImmediate(()=>{m.line&&m.line.startsWith("/")&&v(m.line,-1)}))})}let j=null,A=`${a.dim}...${a.reset} `;function I(T){return(T.match(/[^\s\d](\d{1,2})\.\s+\S/g)||[]).length<2?T:T.replace(/([^\s\d])(\d{1,2})\.\s+/g,(ee,Z,ge)=>`${Z}
|
|
1712
|
+
${ge}. `).trim()}let{loadSession:M}=on(),{setConversationMessages:N}=Ee();if(e()===0){let T=M("_autosave");if(T&&T.messages&&T.messages.length>0&&Date.now()-new Date(T.updatedAt).getTime()<1440*60*1e3){let{confirm:ee}=$t();if(await ee("Previous session found. Resume?")){let Se=T.messages,xe=Se.length>20?Se.slice(-20):Se;N(xe);let{getUsage:Ne,forceCompress:Ue}=Lt();if(Ne(xe,[]).percentage>=30){let{messages:qe}=Ue(xe,[]);N(qe)}}}}m.setPrompt(Bt()),m.prompt(),m.on("line",async T=>{if(Re(),Object.keys(ie).length>0&&(T=Te(T),X(),m.setPrompt(Bt())),S){let ge=T.trim();if(ge){let{injectMidRunNote:Se}=Ee();Se(ge),process.stdout.write(`${a.cyan} \u270E Queued \u2014 will be applied in the next step${a.reset}
|
|
1713
|
+
`),m.prompt()}return}if(j!==null){if(j._mode==="triple"){if(T.trim()==='"""'){let ge=j.join(`
|
|
1714
|
+
`).trim();if(j=null,ge){ja(ge.replace(/\n/g,"\\n")),S=!0,m.prompt(),C=0,k=!1,x&&(clearTimeout(x),x=null),pn=new AbortController;try{await n(ge)}catch(xe){if(!pn?.signal?.aborted){let Ne=xe.message?.split(`
|
|
1715
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${Ne}${a.reset}`)}}S=!1;let Se=ee();Se>0&&process.stdout.write(`${a.gray}[${Se} messages] ${a.reset}`)}m.setPrompt(Bt()),m.prompt();return}j.push(T),m.setPrompt(A),m.prompt();return}if(T.endsWith("\\"))j.push(T.slice(0,-1));else{j.push(T);let ge=j.join(`
|
|
1716
|
+
`).trim();if(j=null,ge){ja(ge.replace(/\n/g,"\\n")),S=!0,m.prompt(),C=0,k=!1,x&&(clearTimeout(x),x=null),pn=new AbortController;try{await n(ge)}catch(Ne){if(!pn?.signal?.aborted){let Ue=Ne.message?.split(`
|
|
1717
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${Ue}${a.reset}`)}}let{getConversationLength:Se}=Ee();S=!1;let xe=Se();xe>0&&process.stdout.write(`${a.gray}[${xe} messages] ${a.reset}`)}m.setPrompt(Bt()),m.prompt();return}m.setPrompt(A),m.prompt();return}if(T.trim()==='"""'||T.trim().startsWith('"""')){let ge=T.trim().substring(3);j=ge?[ge]:[],j._mode="triple",m.setPrompt(A),m.prompt();return}if(T.endsWith("\\")){j=[T.slice(0,-1)],j._mode="backslash",m.setPrompt(A),m.prompt();return}let J=I(T.trim());if(!J){m.setPrompt(Bt()),m.prompt();return}if(ja(J),J==="/"){P$(),m.setPrompt(Bt()),m.prompt();return}if(J.startsWith("/")){await Wr(J,m);let ge=Wr._pendingAgentPrompt;if(ge){Wr._pendingAgentPrompt=null;try{let{isPlanMode:Se,setPlanMode:xe}=rn(),{invalidateSystemPromptCache:Ne}=Ee();Se()&&(xe(!1),Ne())}catch{}S=!0,m.prompt(),C=0,k=!1,x&&(clearTimeout(x),x=null),pn=new AbortController;try{await n(ge,null,{autoOrchestrate:!1,skipPhaseRouting:!0,skillLoop:!0,maxIterations:200})}catch(Se){if(!pn?.signal?.aborted){let xe=Se.message?.split(`
|
|
1718
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${xe}${a.reset}`)}}S=!1}m.setPrompt(Bt()),m.prompt();return}{let ge=s1?"\x1B[48;5;237m":"\x1B[48;2;220;225;235m",Se=process.stdout.columns||80,xe=J.split(`
|
|
1719
|
+
`);process.stdout.isTTY&&process.stdout.write(`\x1B[${xe.length}A`),xe.forEach((Ne,Ue)=>{let bt=Ue===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",qe=2+Ne.length,Wt=" ".repeat(Math.max(0,Se-qe));console.log(`\x1B[2K${ge}${bt} ${Ne}${Wt}\x1B[0m`)}),console.log()}if(process.env.NEX_AUTO_PLAN!=="0"&&!Au()){let{isPlanMode:ge,setPlanMode:Se}=rn(),{invalidateSystemPromptCache:xe}=Ee(),Ne=/\b(implement|refactor|migrate|redesign)\b/i,Ue=/\b(create|build|add|write|introduce|develop|set\s+up)\b/i,bt=/^(how|what|why|when|where|which|explain|show|list|tell|describe|can\s+you|could\s+you|do\s+you)\b/i,qe=/\b(spawn[_\s]?agents?|swarm)\b/i;!bt.test(J)&&!qe.test(J)&&(Ne.test(J)||Ue.test(J)&&J.split(/\s+/).length>=5)&&!ge()&&(Se(!0),xe(),console.log(`${a.cyan}${a.bold}\u2387 Auto Plan Mode${a.reset}${a.dim} \u2014 implementation task detected \xB7 read-only until /plan approve${a.reset}`))}{let{getConversationLength:ge}=Ee();if(ge()===0)try{let{detectCategory:Se,getModelForCategory:xe}=Kn(),Ne=Se(J);if(Ne&&Ne.id!=="coding"){let Ue=xe(Ne.id),bt=Dn();if(Ue&&Ue!==bt?.id&&Mu(Ue)){let qe=Dn();console.log(`${a.dim}\u21B3 ${Ne.icon} ${Ne.label} task \u2014 routing to ${qe?.name||Ue}${a.reset}`),global._nexFooter&&global._nexFooter.setStatusInfo({model:qe?.name||Ue})}}}catch{}}S=!0,m.prompt(),C=0,k=!1,x&&(clearTimeout(x),x=null),pn=new AbortController;try{await n(J)}catch(ge){if(!pn?.signal?.aborted){let Se=ge.message?.split(`
|
|
1720
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${Se}${a.reset}`)}}S=!1;let{getConversationLength:ee}=Ee(),Z=ee();Z>0&&process.stdout.write(`${a.gray}[${Z} messages] ${a.reset}`),m.setPrompt(Bt()),m.prompt()}),m.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}F$.exports={startREPL:w1,getPrompt:Bt,loadHistory:q$,appendHistory:ja,getHistoryPath:Lu,HISTORY_MAX:Pu,showCommandList:P$,completer:I$,completeFilePath:L$,handleSlashCommand:Wr,showProviders:Ou,showHelp:j$,renderBar:D$,hasPasteStart:g1,hasPasteEnd:$1,stripPasteSequences:Br,getAbortSignal:M$}});var B$=oe((hC,U$)=>{"use strict";var b1=require("readline");function Ps(t){process.stdout.write(JSON.stringify(t)+`
|
|
1721
|
+
`)}function _1(){process.env.NEX_SERVER="1";let t=(...c)=>process.stderr.write(c.map(String).join(" ")+`
|
|
1722
|
+
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=$t(),n=new Map,s=0;e((c,l)=>{let u="cfm-"+ ++s,d=l?.toolName||"",f=!1;try{let{isCritical:p}=$t();f=p(c)}catch{}return Ps({type:"confirm_request",id:u,question:c,tool:d,critical:f}),new Promise(p=>{n.set(u,p)})});let o=null,r={onToken(c){o&&Ps({type:"token",id:o,text:c})},onThinkingToken(){},onToolStart(c,l){o&&Ps({type:"tool_start",id:o,tool:c,args:l||{}})},onToolEnd(c,l,u){o&&Ps({type:"tool_end",id:o,tool:c,summary:l||"",ok:!!u})}},i=b1.createInterface({input:process.stdin,output:null,terminal:!1});Ps({type:"ready"}),i.on("line",async c=>{let l=c.trim();if(!l)return;let u;try{u=JSON.parse(l)}catch{return}switch(u.type){case"chat":{let d=u.id||"msg-"+Date.now();o=d;let{processInput:f}=Ee();try{await f(u.text,r),Ps({type:"done",id:d})}catch(p){Ps({type:"error",id:d,message:p?.message||String(p)})}finally{o=null}break}case"confirm":{let d=n.get(u.id);d&&(n.delete(u.id),d(!!u.answer));break}case"cancel":{for(let[d,f]of n)n.delete(d),f(!1);break}case"clear":{let{clearConversation:d}=Ee();d();for(let[f,p]of n)n.delete(f),p(!1);break}default:break}}),i.on("close",()=>{process.exit(0)})}U$.exports={startServerMode:_1}});var G$=oe((gC,Y$)=>{"use strict";var Ls=require("fs"),qu=require("path"),x1=require("https"),{execSync:Fu}=require("child_process"),v1=5*1024*1024;function W$(t){let e=t.match(/^\*\/(\d+) \* \* \* \*$/);if(e){let s=parseInt(e[1],10);if(s>0)return{intervalMs:s*60*1e3,initialDelayMs:0}}let n=t.match(/^0 (\d+) \* \* \*$/);if(n){let s=parseInt(n[1],10),o=new Date,r=new Date;return r.setHours(s,0,0,0),r<=o&&r.setDate(r.getDate()+1),{intervalMs:1440*60*1e3,initialDelayMs:r.getTime()-o.getTime()}}return null}function Uu(t,e){return t.replace(/\{(\w+)\}/g,(n,s)=>e[s]!==void 0?e[s]:n)}function H$(t,e){if(t)try{let n=qu.resolve(t),s=qu.dirname(n);Ls.existsSync(s)||Ls.mkdirSync(s,{recursive:!0});try{Ls.statSync(n).size>v1&&Ls.truncateSync(n,0)}catch{}Ls.appendFileSync(n,JSON.stringify(e)+`
|
|
1723
|
+
`,"utf-8")}catch(n){process.stderr.write(`[daemon] log write error: ${n.message}
|
|
1724
|
+
`)}}function S1(t,e){if(process.platform==="darwin")try{let n=e.replace(/\\/g,"\\\\").replace(/"/g,'\\"'),s=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');Fu(`osascript -e 'display notification "${n}" with title "${s}"'`,{stdio:"ignore"})}catch{}}function K$(t){let e=process.env.NEX_MATRIX_URL,n=process.env.NEX_MATRIX_TOKEN,s=process.env.NEX_MATRIX_ROOM;if(!(!e||!n||!s))try{let o=JSON.stringify({msgtype:"m.text",body:t}),r=Date.now(),i=`${e}/_matrix/client/r0/rooms/${encodeURIComponent(s)}/send/m.room.message/${r}`,c=new URL(i),l={hostname:c.hostname,port:c.port||(c.protocol==="https:"?443:80),path:c.pathname+c.search,method:"PUT",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","Content-Length":Buffer.byteLength(o)}},u=x1.request(l);u.on("error",()=>{}),u.write(o),u.end()}catch{}}function k1(t,e,n){Array.isArray(t)&&(t.includes("desktop")&&S1(e,n),t.includes("matrix")&&K$(`[nex daemon] ${e}: ${n}`))}async function Bu(t,e,n,s,o){let{processInput:r,clearConversation:i}=Ee(),c=Date.now(),l="ok",u=null;try{await r(t,null,{autoConfirm:e})}catch(p){l="error",u=p.message,process.stderr.write(`[daemon] task error (${o}): ${p.message}
|
|
1725
|
+
`)}finally{i()}let d=Date.now()-c;H$(n,{ts:new Date().toISOString(),trigger:o,task:t.slice(0,200),status:l,error:u,durationMs:d});let f=l==="ok"?`Task completed in ${d}ms`:`Task failed: ${u}`;k1(s,`nex daemon (${o})`,f)}function E1(t,e){let n=t.replace(/\\/g,"/");return e.some(s=>{let o=s.replace(/^\.\//,"");if(o.endsWith("/**")){let r=o.slice(0,-3);return n===r||n.startsWith(r+"/")}if(o.startsWith("**/")){let r=o.slice(3);return n===r||n.endsWith("/"+r)}return n===o})}function T1(t,e,n){let{ignore:s=[],task:o,debounceMs:r=2e3,auto:i=!0}=t,c=new Set,l=null,u=async()=>{let f=[...c];c.clear();let p=Uu(o,{changedFile:f[0]||"",changedFiles:f.join(", ")});await Bu(p,i,e.logFile,e.notify,"file-change")},d=(f,p)=>{if(!p)return;let g=p.replace(/\\/g,"/");E1(g,s)||(c.add(g),clearTimeout(l),l=setTimeout(u,r))};try{return Ls.watch(n,{recursive:!0},d)}catch(f){return process.stderr.write(`[daemon] file-change watcher error: ${f.message}
|
|
1726
|
+
`),null}}function R1(t,e,n){let{task:s,debounceMs:o=0,auto:r=!0}=t,i=()=>{try{return Fu("git log --format=%H -1",{cwd:n,encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}},c=()=>{try{return Fu("git log --format=%s -1",{cwd:n,encoding:"utf-8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return""}},l=i();return setInterval(async()=>{let d=i();if(!d||d===l)return;let f=c();l=d;let p=async()=>{let g=Uu(s,{commitHash:d,commitMessage:f});await Bu(g,r,e.logFile,e.notify,"git-commit")};o>0?setTimeout(p,o):await p()},1e4)}function C1(t,e){let{cron:n,task:s,auto:o=!0}=t,r=W$(n);if(!r)return process.stderr.write(`[daemon] unsupported cron syntax: "${n}" \u2014 skipping
|
|
1727
|
+
`),null;let{intervalMs:i,initialDelayMs:c}=r,l=async()=>{await Bu(s,o,e.logFile,e.notify,"schedule")};return c>0?setTimeout(()=>{l(),setInterval(l,i)},c):setInterval(l,i)}async function A1(t,e={}){let n=e.cwd||process.cwd(),s=qu.resolve(n,t),o;try{let u=Ls.readFileSync(s,"utf-8");o=JSON.parse(u)}catch(u){if(u.code==="ENOENT"){let d=JSON.stringify({triggers:[{on:"file-change",glob:"**/*.{js,ts}",ignore:["dist/**","node_modules/**"],task:"run npm test -- --testPathPattern={changedFile} and report results",debounceMs:2e3,auto:!0}],notify:["desktop"],logFile:".nex/daemon.log"},null,2);throw process.stderr.write(`[daemon] config file not found: ${s}
|
|
1728
|
+
|
|
1729
|
+
Create .nex/daemon.json with this example:
|
|
1730
|
+
${d}
|
|
1731
|
+
`),new Error(`Config file not found: ${s}`)}throw new Error(`Failed to load daemon config: ${u.message}`)}if(!o.triggers||!Array.isArray(o.triggers))throw new Error("daemon.json must have a 'triggers' array");let r={"file-change":0,"git-commit":0,schedule:0};for(let u of o.triggers)u.on in r&&r[u.on]++;let i=[];r["file-change"]>0&&i.push(`${r["file-change"]} file-change trigger${r["file-change"]>1?"s":""}`),r["git-commit"]>0&&i.push(`${r["git-commit"]} git-commit trigger${r["git-commit"]>1?"s":""}`),r.schedule>0&&i.push(`${r.schedule} schedule trigger${r.schedule>1?"s":""}`),process.stdout.write(`nex daemon started \xB7 config: ${t}
|
|
1732
|
+
watching: ${i.join(", ")||"no triggers"}
|
|
1733
|
+
press Ctrl+C to stop
|
|
1734
|
+
`);let c=[];for(let u of o.triggers){let d=null;switch(u.on){case"file-change":d=T1(u,o,n);break;case"git-commit":d=R1(u,o,n);break;case"schedule":d=C1(u,o);break;default:process.stderr.write(`[daemon] unknown trigger type: ${u.on}
|
|
1735
|
+
`)}d&&c.push(d)}let l=()=>{process.stdout.write(`
|
|
1736
|
+
[daemon] shutting down...
|
|
1737
|
+
`);for(let u of c)try{u&&typeof u.close=="function"?u.close():u&&clearInterval(u)}catch{}process.exit(0)};return process.on("SIGINT",l),process.on("SIGTERM",l),new Promise(()=>{})}Y$.exports={startDaemon:A1,parseCronToMs:W$,expandTemplate:Uu,appendLog:H$,notifyMatrix:K$}});var X$=oe(($C,z$)=>{z$.exports=Du()});var qa=require("path"),O1=require("os");require("dotenv").config({path:qa.join(__dirname,"..",".env")});require("dotenv").config({path:qa.join(O1.homedir(),".nex-code",".env")});require("dotenv").config();var ve=process.argv.slice(2);(ve.includes("--help")||ve.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
1719
1738
|
|
|
1720
1739
|
Options:
|
|
1721
1740
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -1723,8 +1742,11 @@ Options:
|
|
|
1723
1742
|
--prompt-file <path> Read prompt from file and run headless (avoids shell escaping)
|
|
1724
1743
|
--delete-prompt-file Delete the prompt file after reading (use with --prompt-file)
|
|
1725
1744
|
--auto Skip all confirmations (implies --task / --prompt-file)
|
|
1745
|
+
--flatrate Flatrate mode: 100 turns, 6 parallel agents, 5 retries (auto on with OLLAMA_API_KEY)
|
|
1726
1746
|
--yolo, -yolo Skip all confirmations (interactive YOLO mode)
|
|
1727
1747
|
--server Start JSON-lines IPC server (used by VS Code extension)
|
|
1748
|
+
--daemon [config] Run as background watcher (reads .nex/daemon.json)
|
|
1749
|
+
--watch [config] Alias for --daemon
|
|
1728
1750
|
--model <spec> Set model (e.g. openai:gpt-4o)
|
|
1729
1751
|
--max-turns <n> Max agentic loop iterations (default: 50)
|
|
1730
1752
|
--orchestrate Use multi-agent orchestrator (with --task)
|
|
@@ -1735,6 +1757,7 @@ Options:
|
|
|
1735
1757
|
--mcp-config <path> Path to MCP server config (default: .nex/mcp.json)
|
|
1736
1758
|
-h, --help Show this help
|
|
1737
1759
|
-v, --version Show version
|
|
1738
|
-
`),process.exit(0));if(
|
|
1760
|
+
`),process.exit(0));if(ve.includes("-v")||ve.includes("--version")){let t=Hs();console.log(t.version),process.exit(0)}var Z$=ve.includes("--yolo")||ve.includes("-yolo");if(Z$){let{setAutoConfirm:t}=$t();t(!0)}if(!Z$)try{let t=require("fs"),e=qa.join(process.cwd(),".nex","config.json");if(t.existsSync(e)&&JSON.parse(t.readFileSync(e,"utf-8")).yolo===!0){let{setAutoConfirm:s}=$t();s(!0)}}catch{}var Gu=ve.includes("--flatrate")||!!process.env.OLLAMA_API_KEY&&!process.env.NEX_NO_FLATRATE;Gu&&(process.env.NEX_MAX_PARALLEL||(process.env.NEX_MAX_PARALLEL="6"),process.env.NEX_MAX_SUBTASKS||(process.env.NEX_MAX_SUBTASKS="10"),process.env.NEX_MAX_CHAT_RETRIES||(process.env.NEX_MAX_CHAT_RETRIES="5"),process.env.OLLAMA_FALLBACK_CHAIN||(process.env.OLLAMA_FALLBACK_CHAIN="ministral-3:8b,qwen3-vl:235b-instruct,devstral-small-2:24b"),process.stderr.write(`\x1B[38;2;80;210;120m\u25C6\x1B[0m \x1B[1mFlatrate mode\x1B[0m\x1B[2m \u2014 100 turns \xB7 6 parallel agents \xB7 5 retries \xB7 verify-on\x1B[0m
|
|
1761
|
+
`));var Wu=ve.indexOf("--model");if(Wu!==-1&&ve[Wu+1]){let{setActiveModel:t}=Be();t(ve[Wu+1])}var Hu=ve.indexOf("--max-turns");if(Hu!==-1&&ve[Hu+1]){let t=parseInt(ve[Hu+1],10);if(t>0){let{setMaxIterations:e}=Ee();e(t)}}else try{let t=require("fs"),e=qa.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let n=JSON.parse(t.readFileSync(e,"utf-8")),s=parseInt(n.maxIterations,10);if(s>0){let{setMaxIterations:o}=Ee();o(s)}}}catch{}var Ku=ve.indexOf("--mcp-config");Ku!==-1&&ve[Ku+1]&&(process.env.NEX_MCP_CONFIG=ve[Ku+1]);function Yu(){if(process.platform==="darwin")try{let{spawn:t}=require("child_process"),e=t("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});e.unref();let n=()=>{try{e.kill()}catch{}};process.on("exit",n),process.on("SIGINT",n),process.on("SIGTERM",n)}catch{}}async function N1(){let{runSetupWizard:t}=uu();await t()}function V$(t){if(ve.includes("--auto")){let{setAutoConfirm:c}=$t();c(!0)}if(Gu){let{setMaxIterations:c}=Ee();c(100)}if(!ve.includes("--model")){let{setActiveModel:c}=Be(),l=process.env.HEADLESS_MODEL||"devstral-small-2:24b";c(l)}let n=!ve.includes("--no-auto-orchestrate")&&process.env.NEX_AUTO_ORCHESTRATE!=="false",s=ve.indexOf("--orchestrator-model"),o=s!==-1?ve[s+1]:void 0;if(t.startsWith("/")){let{loadAllSkills:c,handleSkillCommand:l}=Cn();c();let u=l(t);if(u&&u.agentPrompt){let{processInput:f,getConversationMessages:p}=Ee();f(u.agentPrompt,null,{autoOrchestrate:n,orchestratorModel:o}).then(()=>process.exit(0)).catch(g=>{console.error(g.message),process.exit(1)});return}let{handleSlashCommand:d}=Du();d(t,null).then(()=>process.exit(0)).catch(f=>{console.error(f.message),process.exit(1)});return}let{processInput:r,getConversationMessages:i}=Ee();r(t,null,{autoOrchestrate:n,orchestratorModel:o}).then(()=>{try{let{writeDreamLog:c}=mu();c(i())}catch{}if(ve.includes("--json")){let l=i().filter(u=>u.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:l?.content||""}))}process.exit(0)}).catch(c=>{ve.includes("--json")?console.log(JSON.stringify({success:!1,error:c.message})):console.error(c.message),process.exit(1)})}if(ve.includes("--server")){let{setAutoConfirm:t}=$t();t(!0),B$().startServerMode();return}if(ve.includes("--daemon")||ve.includes("--watch")){let t=ve.includes("--daemon")?ve.indexOf("--daemon"):ve.indexOf("--watch"),e=ve[t+1],n=e&&!e.startsWith("--")?e:".nex/daemon.json",{startDaemon:s}=G$();s(n).catch(o=>{console.error("Daemon error:",o.message),process.exit(1)});return}var J$=ve.indexOf("--prompt-file");if(J$!==-1){let t=ve[J$+1];(!t||t.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let e=require("fs"),n;try{n=e.readFileSync(t,"utf-8").trim()}catch(s){console.error(`--prompt-file: cannot read file: ${s.message}`),process.exit(1)}if(n||(console.error("--prompt-file: file is empty"),process.exit(1)),ve.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}Yu(),V$(n)}else{let t=ve.indexOf("--task")!==-1?ve.indexOf("--task"):ve.indexOf("--prompt");if(t!==-1){let e=ve[t+1];if((!e||e.startsWith("--"))&&(console.error("--task/--prompt requires a prompt"),process.exit(1)),Yu(),ve.includes("--orchestrate")){let n=ve.indexOf("--orchestrator-model"),s=n!==-1?ve[n+1]:void 0,{runOrchestrated:o}=$r();o(e,{orchestratorModel:s}).then(()=>{process.exit(0)}).catch(r=>{console.error(`Orchestrator error: ${r.message}`),process.exit(1)})}else V$(e)}else N1().then(()=>{if(Yu(),Gu){let{setMaxIterations:n}=Ee();n(100)}let{startREPL:e}=X$();e(),setTimeout(async()=>{try{let{loadKnownModels:n,findNewModels:s}=To(),o=n(),r=o.lastChecked?new Date(o.lastChecked):null;if((r?(Date.now()-r.getTime())/864e5:999)<7||!process.env.OLLAMA_API_KEY)return;let{newModels:c}=await s();if(c.length>0){let{C:l}=Ke();process.stdout.write(`
|
|
1739
1762
|
${l.dim}\u{1F4A1} ${c.length} new Ollama Cloud model(s) available \u2014 /benchmark --discover to test them${l.reset}
|
|
1740
1763
|
`)}}catch{}},3e3)})}
|