nex-code 0.4.28 → 0.4.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/nex-code.js +229 -229
- package/dist/skills/autoresearch.js +2 -0
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var As=Q((
|
|
3
|
-
`),s=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(s){let r=parseInt(s[1].slice(0,2),16),i=parseInt(s[2].slice(0,2),16),c=parseInt(s[3].slice(0,2),16);return .299*r+.587*i+.114*c<128}}catch{}return null}function Ru(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function
|
|
2
|
+
var Q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var As=Q((mT,T$)=>{T$.exports={name:"nex-code",version:"0.4.30",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:"esbuild bin/nex-code.js --bundle --platform=node --target=node18 --outfile=dist/nex-code.js --minify --external:axios --external:dotenv --external:playwright && rm -rf dist/skills && cp -r cli/skills dist/skills",dev:"esbuild bin/nex-code.js --bundle --platform=node --target=node18 --outfile=dist/nex-code.js --external:axios --external:dotenv --external:playwright --watch",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","claude","gemini","llm","gpt","agentic","terminal","coding-assistant","claude-code-alternative","gemini-cli-alternative","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 Yn=Q((hT,Nu)=>{"use strict";var Eu="\x1B[0m",Tu="\x1B[1m",Os="\x1B[2m";function Z(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function R$(){if(!process.stdout.isTTY)return null;try{let{execFileSync:t}=require("child_process"),e=["import sys,os,tty,termios,select","f=open('/dev/tty','r+b',buffering=0)","fd=f.fileno()","s=termios.tcgetattr(fd)","try:"," tty.setraw(fd)"," f.write(bytes([0x1b,0x5d,0x31,0x31,0x3b,0x3f,0x1b,0x5c]))"," r=select.select([fd],[],[],0.1)[0]"," d=b''"," if r:"," while True:"," r2=select.select([fd],[],[],0.05)[0]"," if not r2:break"," c=os.read(fd,1)"," d+=c"," if d[-1:]==bytes([0x07]) or d[-2:]==bytes([0x1b,0x5c]):break"," sys.stdout.buffer.write(d)","finally:"," termios.tcsetattr(fd,termios.TCSADRAIN,s)"," f.close()"].join(`
|
|
3
|
+
`),s=t("python3",["-c",e],{encoding:"buffer",timeout:400,stdio:["ignore","pipe","ignore"]}).toString("utf8").match(/rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(s){let r=parseInt(s[1].slice(0,2),16),i=parseInt(s[2].slice(0,2),16),c=parseInt(s[3].slice(0,2),16);return .299*r+.587*i+.114*c<128}}catch{}return null}function Ru(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function C$(t){try{let n=require("fs").readFileSync(Ru(),"utf8"),o=JSON.parse(n);if(o&&typeof o[t]=="boolean")return o[t]}catch{}return null}function A$(t,e){try{let n=require("fs"),o=require("path"),s=Ru(),r=o.dirname(s),i={};try{i=JSON.parse(n.readFileSync(s,"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(s,JSON.stringify(i),"utf8")}catch{}}function O$(){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",o=C$(n);if(o!==null)return o;let s=R$(),r=s!==null?s:!0;return A$(n,r),r}var Cu=O$(),Au={reset:Eu,bold:Tu,dim:Os,primary:Z(80,190,255),secondary:Z(60,170,190),success:Z(80,210,120),warning:Z(245,175,50),error:Z(230,80,80),muted:Os,subtle:Z(130,130,145),tool_read:Z(80,190,255),tool_write:Z(245,165,55),tool_exec:Z(185,100,235),tool_search:Z(70,185,190),tool_git:Z(90,210,100),tool_web:Z(100,215,250),tool_sysadmin:Z(225,150,75),tool_default:Z(100,205,115),syn_keyword:Z(185,100,235),syn_string:Z(90,210,120),syn_number:Z(245,175,50),syn_comment:Os,syn_key:Z(80,190,255),diff_add:Z(80,210,120),diff_rem:Z(230,80,80),banner_logo:Z(80,200,255),banner_name:Z(80,200,255),banner_version:Os,banner_model:Os,banner_yolo:Z(245,175,50),footer_sep:Os,footer_model:Z(80,175,235),footer_branch:Z(80,210,100),footer_project:Z(130,130,145),footer_divider:Z(80,80,95),footer_mode:Z(210,150,50),white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",diff_add_bg:"\x1B[48;2;10;46;20m",diff_rem_bg:"\x1B[48;2;58;16;16m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},Ou={reset:Eu,bold:Tu,dim:Z(110,110,120),primary:Z(0,110,190),secondary:Z(0,125,148),success:Z(0,148,62),warning:Z(168,92,0),error:Z(188,32,32),muted:Z(110,110,120),subtle:Z(155,155,165),tool_read:Z(0,110,190),tool_write:Z(168,92,0),tool_exec:Z(128,42,188),tool_search:Z(0,122,148),tool_git:Z(0,138,62),tool_web:Z(0,112,178),tool_sysadmin:Z(168,82,0),tool_default:Z(0,138,62),syn_keyword:Z(128,42,188),syn_string:Z(0,138,62),syn_number:Z(168,92,0),syn_comment:Z(135,135,148),syn_key:Z(0,110,190),diff_add:Z(0,148,62),diff_rem:Z(188,32,32),banner_logo:Z(0,122,205),banner_name:Z(0,122,205),banner_version:Z(100,100,118),banner_model:Z(100,100,118),banner_yolo:Z(168,62,0),footer_sep:Z(168,168,178),footer_model:Z(0,102,175),footer_branch:Z(0,138,62),footer_project:Z(135,135,148),footer_divider:Z(168,168,178),footer_mode:Z(148,88,0),white:Z(40,40,52),red:Z(188,32,32),green:Z(0,148,62),yellow:Z(168,92,0),blue:Z(0,110,190),magenta:Z(128,42,188),cyan:Z(0,125,148),gray:Z(132,132,142),bgRed:"\x1B[41m",bgGreen:"\x1B[42m",diff_add_bg:"\x1B[48;2;215;245;220m",diff_rem_bg:"\x1B[48;2;255;215;215m",brightCyan:Z(0,158,182),brightMagenta:Z(158,52,208),brightBlue:Z(0,112,208)},N$=Cu?Au:Ou;Nu.exports={T:N$,isDark:Cu,DARK:Au,LIGHT:Ou}});var Ms=Q((gT,Pu)=>{var{T:ne}=Yn(),Lr=5,Ns=(()=>{let t=[];for(let e=0;e<Lr;e++)t.push(e);for(let e=Lr-2;e>=1;e--)t.push(e);return t})(),Mu=["\u273D","\u2726","\u2727","\u2726"],Ca=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Ns[this.frame%Ns.length],n="";for(let s=0;s<Lr;s++)n+=s===e?`${ne.cyan}\u25CF${ne.reset}`:" ";let o="";if(this.startTime){let s=Math.floor((Date.now()-this.startTime)/1e3);if(s>=60){let r=Math.floor(s/60),i=s%60;o=` ${ne.dim}${r}m ${String(i).padStart(2,"0")}s${ne.reset}`}else s>=1&&(o=` ${ne.dim}${s}s${ne.reset}`)}process.stderr.write(`\x1B[2K\r${n} ${ne.dim}${this.text}${ne.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){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}},Aa=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_render(){if(this._stopped)return;let e=Ns[this.frame%Ns.length],n=`${ne.cyan}\u25CF${ne.reset}`,o=this._formatElapsed(),s=o?` ${ne.dim}${o}${ne.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=`${ne.green}\u2713${ne.reset}`,u=ne.dim;break;case"error":l=`${ne.red}\u2717${ne.reset}`,u=ne.dim;break;case"retry":l=`${ne.yellow}\u21BB${ne.reset}`,u=ne.yellow;break;default:l=c===e?n:" ",u=""}let d=c===this.labels.length-1?s:"",f=r-4-(d?o.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}${ne.reset}${d}
|
|
4
4
|
`}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let n=0;n<this.lineCount;n++)e+=`
|
|
5
5
|
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),100)}update(e,n){e>=0&&e<this.statuses.length&&(this.statuses[e]=n)}stop(e={}){if(this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),!e.silent)this._renderFinal();else{let n="";for(let o=0;o<this.lineCount;o++)n+=`\x1B[2K
|
|
6
6
|
`;this.lineCount>0&&(n+=`\x1B[${this.lineCount}A`),process.stderr.write(n)}process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),n=e?` ${ne.dim}${e}${ne.reset}`:"",o=process.stderr.columns||80,s="";for(let r=0;r<this.labels.length;r++){let i;switch(this.statuses[r]){case"done":i=`${ne.green}\u2713${ne.reset}`;break;case"error":i=`${ne.red}\u2717${ne.reset}`;break;case"retry":i=`${ne.yellow}\u21BB${ne.reset}`;break;default:i=`${ne.yellow}\u25CB${ne.reset}`}let c=r===this.labels.length-1?n:"",l=o-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];s+=`\x1B[2K ${i} ${ne.dim}${u}${ne.reset}${c}
|
|
@@ -11,12 +11,12 @@ var Q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var As=Q((pT,E$)=>
|
|
|
11
11
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let n=0;n<this.lineCount;n++)e+=`
|
|
12
12
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,n){let o=this.tasks.find(s=>s.id===e);o&&(o.status=n)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),n=this.tasks.filter(c=>c.status==="done").length,o=this.tasks.filter(c=>c.status==="failed").length,s=this.tasks.length,r=o>0?`${n}/${s} done, ${o} failed`:`${n}/${s} done`,i=`\x1B[2K${ne.green}\u2714${ne.reset} ${this.name} ${ne.dim}(${e} \xB7 ${r})${ne.reset}
|
|
13
13
|
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=Mr[l.status]||Mr.pending,f=Pr[l.status]||Pr.pending,p=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${ne.dim}${u}${ne.reset} ${f}${d}${ne.reset} ${ne.dim}${p}${ne.reset}
|
|
14
|
-
`}process.stderr.write(i)}},Na=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=Ns[this.frame%Ns.length],n="";for(let r=0;r<Lr;r++)n+=r===e?`${ne.cyan}\u25CF${ne.reset}`:" ";let o=this.message;this.count>0&&(o+=` ${ne.cyan}${this.count}${ne.reset}`,this.total&&(o+=`/${this.total}`),this.detail&&(o+=` ${ne.dim}${this.detail}${ne.reset}`));let s="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(s=` ${ne.dim}${r}s${ne.reset}`)}process.stderr.write(`\x1B[2K\r${n} ${ne.dim}${o}${ne.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){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
|
|
14
|
+
`}process.stderr.write(i)}},Na=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=Ns[this.frame%Ns.length],n="";for(let r=0;r<Lr;r++)n+=r===e?`${ne.cyan}\u25CF${ne.reset}`:" ";let o=this.message;this.count>0&&(o+=` ${ne.cyan}${this.count}${ne.reset}`,this.total&&(o+=`/${this.total}`),this.detail&&(o+=` ${ne.dim}${this.detail}${ne.reset}`));let s="";if(this.startTime){let r=Math.floor((Date.now()-this.startTime)/1e3);r>=1&&(s=` ${ne.dim}${r}s${ne.reset}`)}process.stderr.write(`\x1B[2K\r${n} ${ne.dim}${o}${ne.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){e.count!==void 0&&(this.count=e.count),e.total!==void 0&&(this.total=e.total),e.detail!==void 0&&(this.detail=e.detail),e.message!==void 0&&(this.message=e.message)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h")}};function M$(t){Rn=t}function P$(){return Rn}function L$(){Rn&&(Rn.stop(),Rn=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Pu.exports={C:ne,Spinner:Ca,MultiProgress:Aa,TaskProgress:Oa,ToolProgress:Na,setActiveTaskProgress:M$,getActiveTaskProgress:P$,cleanupTerminal:L$}});var Ma=Q(($T,Du)=>{"use strict";var de={kw:"\x1B[34m",str:"\x1B[32m",cmt:"\x1B[90m",num:"\x1B[33m",type:"\x1B[36m",punct:"\x1B[35m",reset:"\x1B[0m"},Lu={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"])},I$={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 Iu(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return I$[e]||null}function j$(t){return t.replace(/"([^"\\]|\\.)*"\s*:/g,e=>de.type+e+de.reset).replace(/"([^"\\]|\\.)*"/g,e=>de.str+e+de.reset).replace(/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,e=>de.num+e+de.reset).replace(/\b(true|false|null)\b/g,e=>de.kw+e+de.reset)}function D$(t){return/<!--/.test(t)?t.replace(/<!--[\s\S]*?(?:-->|$)/g,e=>de.cmt+e+de.reset):t.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(e,n,o)=>n+de.type+o+de.reset).replace(/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(e,n)=>" "+de.kw+n+de.reset+"=").replace(/"([^"]*)"/g,e=>de.str+e+de.reset)}function q$(t){return t.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,e=>de.cmt+e+de.reset).replace(/#[0-9a-fA-F]{3,8}\b/g,e=>de.num+e+de.reset).replace(/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(e,n,o)=>de.num+n+de.reset+o).replace(/([a-z][a-z-]*)(\s*:)/g,(e,n,o)=>de.type+n+de.reset+o).replace(/"[^"]*"|'[^']*'/g,e=>de.str+e+de.reset)}function ju(t,e,n){if(e==="json")return j$(t);if(e==="html"||e==="xml")return D$(t);if(e==="css")return q$(t);if(e==="md")return t;let o=Lu[e]||Lu.js,s="",r=0;if(n.inBlockComment){let i=t.indexOf("*/");if(i===-1)return de.cmt+t+de.reset;if(s+=de.cmt+t.slice(0,i+2)+de.reset,n.inBlockComment=!1,r=i+2,r>=t.length)return s}if(n.inString==="`"){let i=t.indexOf("`");if(i===-1)return de.str+t+de.reset;if(s+=de.str+t.slice(0,i+1)+de.reset,n.inString=null,r=i+1,r>=t.length)return s}for(;r<t.length;){let i=t[r];if(!n.inString&&i==="/"&&t[r+1]==="*"){let c=t.indexOf("*/",r+2);if(c===-1)return s+=de.cmt+t.slice(r)+de.reset,n.inBlockComment=!0,s;s+=de.cmt+t.slice(r,c+2)+de.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 s+=de.cmt+t.slice(r)+de.reset,s;if(!n.inString&&(i==='"'||i==="'"||i==="`")){n.inString=i,s+=de.str+i,r++;continue}if(n.inString){if(i==="\\"&&r+1<t.length){s+=i+t[r+1],r+=2;continue}if(i===n.inString){s+=i+de.reset,n.inString=null,r++;continue}s+=i,r++;continue}if(/[0-9]/.test(i)&&(r===0||!/[a-zA-Z0-9_$]/.test(t[r-1]))){let 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++];s+=de.num+c+de.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++];s+=de.punct+c+de.reset;continue}if(/[a-zA-Z_$]/.test(i)){let c="";for(;r<t.length&&/[a-zA-Z0-9_$]/.test(t[r]);)c+=t[r++];o.has(c)?s+=de.kw+c+de.reset:/^[A-Z][A-Za-z0-9]*$/.test(c)&&e!=="sh"?s+=de.type+c+de.reset:s+=c;continue}s+=i,r++}return n.inString&&n.inString!=="`"&&(s+=de.reset,n.inString=null),s}function F$(t,e){let n=Iu(e);if(!n)return t.split(`
|
|
15
15
|
`);let o=t.split(`
|
|
16
|
-
`),s={inString:null,inBlockComment:!1};return o.map(r=>ju(r,n,s))}function
|
|
16
|
+
`),s={inString:null,inBlockComment:!1};return o.map(r=>ju(r,n,s))}function U$(t,e){return e?ju(t,e,{inString:null,inBlockComment:!1}):t}Du.exports={detectLang:Iu,highlightLine:U$,highlightLines:F$}});var Fu=Q((yT,qu)=>{var{T:P}=Yn(),dt=P,B$={read_file:P.tool_read,list_directory:P.tool_read,write_file:P.tool_write,edit_file:P.tool_write,patch_file:P.tool_write,bash:P.tool_exec,grep:P.tool_search,search_files:P.tool_search,glob:P.tool_search,git_commit:P.tool_git,git_push:P.tool_git,git_pull:P.tool_git,git_status:P.tool_git,git_diff:P.tool_git,git_log:P.tool_git,git_branch:P.tool_git,git_stash:P.tool_git,web_fetch:P.tool_web,web_search:P.tool_web,sysadmin:P.tool_sysadmin,ssh_exec:P.tool_sysadmin,ssh_upload:P.tool_sysadmin,ssh_download:P.tool_sysadmin,deploy:P.tool_sysadmin},Pa={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 Ir(t,e=!1,n=null){if(e)return`${P.error}\u23FA${P.reset}`;let o=B$[t]||P.tool_default;return n==="blink"?`${o}\x1B[5m\u23FA\x1B[25m${P.reset}`:`${o}${n!==null?n:"\u23FA"}${P.reset}`}function W$(t,e,n=!1,o=null){let s=(t||[]).filter(l=>l&&l.canExecute!==!1);if(s.length===0)return`${Ir("",n,o)} Step ${e}`;if(s.length===1){let l=s[0],u=l.args||{},d=Pa[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?`(${dt.dim}${f}${dt.reset})`:"";return`${Ir(l.fnName,n,o)} ${dt.bold}${d}${dt.reset}${p}`}let r=s[0].fnName,i=[...new Set(s.map(l=>Pa[l.fnName]||l.fnName.replace(/_/g," ")))],c=i.length<=3?i.join(", "):`${s.length} tools`;return`${Ir(r,n,o)} ${dt.bold}${c}${dt.reset}`}function H$(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 o=Pa[t]||t.replace(/_/g," "),s=n?`(${dt.dim}${n}${dt.reset})`:"";return`${Ir(t)} ${dt.bold}${o}${dt.reset}${s}`}function K$(t,e=8){let n=t.split(`
|
|
17
17
|
`),o=n.slice(0,e),s=n.length-e,r=`${P.muted} \u23BF ${P.reset}`,i=" ",c=o.map((l,u)=>`${u===0?r:i}${P.success}${l}${P.reset}`).join(`
|
|
18
18
|
`);return s>0&&(c+=`
|
|
19
|
-
${P.subtle} \u2026 +${s} lines${P.reset}`),c}function
|
|
19
|
+
${P.subtle} \u2026 +${s} lines${P.reset}`),c}function G$(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`Glob: ${e.pattern||"..."}`;case"grep":return`Grep: ${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"Git status...";case"git_diff":return`Git diff${e.file?`: ${e.file}`:""}...`;case"git_log":return`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 Y$(t,e,n,o){let s=String(n||"");if(o){let c=s.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` ${P.muted}\u23BF blocked: ${f}${P.reset}`}let l=c.replace(/^ERROR:\s*/i,"").substring(0,80),u=s.match(/\nHINT: (.+)/),d=u?`
|
|
21
21
|
${P.muted}${u[1].substring(0,100)}${P.reset}`:"";return` ${P.error}\u23BF ${l}${P.reset}${d}`}let r;switch(t){case"read_file":{let l=s.split(`
|
|
22
22
|
`).filter(Boolean).filter(g=>!/^File:\s/.test(g)&&!/^\[LARGE FILE:/.test(g)),u=l.length,d=l[l.length-1],f=d?parseInt(d.match(/^(\d+):/)?.[1]||"0"):0,p=e.line_start||e.line_end,h=e.path?require("path").basename(e.path):null,m=h?` ${P.muted}from ${h}${P.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(`
|
|
@@ -47,87 +47,87 @@ ${g}
|
|
|
47
47
|
`)[0].replace(/^\d+\.\s*/,"").trim():null,d=u?` ${P.muted}\u2014 ${u.substring(0,70)}${P.reset}`:"";r=`${l} result${l!==1?"s":""}${d}`;break}case"task_list":r="Done";break;case"spawn_agents":{let c=(s.match(/✓ Agent/g)||[]).length,l=(s.match(/✗ Agent/g)||[]).length;r=l>0?`${c} done, ${l} failed`:`${c} agent${c!==1?"s":""} done`;break}case"switch_model":{let c=s.match(/Switched to (.+)/);r=c?`\u2192 ${c[1]}`:"Done";break}case"ssh_exec":{let l=s.startsWith("EXIT ")||s.startsWith("Command failed"),u=s.split(`
|
|
48
48
|
`).filter(f=>f.trim()&&!f.startsWith("EXIT ")),d=l?`${P.error}\u2717${P.reset}`:`${P.success}\u2713${P.reset}`;if(u.length===0)r=d;else{if(u.length>2&&u.every(g=>/^\[/.test(g.trim()))){r=`${d} ${u.length} log lines`;break}let p=l?u.slice(-3):u.slice(0,3),h=u.length-3,m=p.map((g,y)=>y===0?`${d} ${P.muted}${g.substring(0,120)}${P.reset}`:` ${P.muted}${g.substring(0,120)}${P.reset}`);if(h>0){let g=l?` ${P.subtle}${h} lines above\u2026${P.reset}`:` ${P.subtle}\u2026 +${h} lines${P.reset}`;l?m.unshift(g):m.push(g)}r=m.join(`
|
|
49
49
|
`)}break}default:{let c=s.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?` ${P.subtle}\u2026 +${c.length-1} lines${P.reset}`:"";r=`${P.muted}${l}${P.reset}${u}`}else r="Done"}}return` ${P.muted}\u23BF ${r}${P.reset}`}function
|
|
51
|
-
${P.success}\u25C6${dt.reset} ${dt.bold}${t}${dt.reset}`;return l+=`${dt.dim} \xB7 ${c}`,r.size>0&&(l+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),l+=dt.reset,l}qu.exports={C:dt,formatToolCall:
|
|
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?` ${P.subtle}\u2026 +${c.length-1} lines${P.reset}`:"";r=`${P.muted}${l}${P.reset}${u}`}else r="Done"}}return` ${P.muted}\u23BF ${r}${P.reset}`}function z$(t,e,n,o,s,r){let i=Math.round(o/1e3),c=i>=60?`${Math.floor(i/60)}m ${i%60}s`:`${i}s`,l=`
|
|
51
|
+
${P.success}\u25C6${dt.reset} ${dt.bold}${t}${dt.reset}`;return l+=`${dt.dim} \xB7 ${c}`,r.size>0&&(l+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),l+=dt.reset,l}qu.exports={C:dt,formatToolCall:H$,formatResult:K$,getToolSpinnerText:G$,formatToolSummary:Y$,formatSectionHeader:W$,formatMilestone:z$}});var Fe=Q((wT,Bu)=>{var{T:zn}=Yn(),La=zn,Uu=["01100110","01111110","01111110","01011010","01111110","00111100"];function X$(t,e){let n=[];for(let o=0;o<t.length;o+=2){let s="";for(let r=0;r<t[0].length;r++){let i=t[o][r]==="1",c=o+1<t.length&&t[o+1][r]==="1";i&&c?s+=`${e}\u2588\x1B[0m`:i&&!c?s+=`${e}\u2580\x1B[0m`:!i&&c?s+=`${e}\u2584\x1B[0m`:s+=" "}n.push(s)}return n}function J$(t,e,n={}){let o=La.bold,s=La.reset,r=X$(Uu,zn.banner_logo),i=n.yolo?` ${o}${zn.banner_yolo}\u26A1 YOLO${s}`:"",c=As().version,l=[` ${zn.banner_name}${o}nex-code${s} ${zn.banner_version}v${c}${s}`,` ${zn.banner_model}${t}${s} ${zn.muted}\xB7 /help${s}${i}`,""],u=Math.max(r.length,l.length),d=Math.floor((u-r.length)/2),f=Math.floor((u-l.length)/2),p=Uu[0].length,h=[];for(let m=0;m<u;m++){let g=r[m-d]??" ".repeat(p),y=l[m-f]??"";h.push(g+y)}console.log(`
|
|
52
52
|
`+h.join(`
|
|
53
53
|
`)+`
|
|
54
|
-
`)}var{Spinner:
|
|
55
|
-
`){u(s);return}if(p==="\x1B[A"){s=(s-1+n.length)%n.length,c();return}if(p==="\x1B[B"){s=(s+1)%n.length,c();return}let h=p.toLowerCase().trim();if(h==="y"){l(!0);return}if(h==="n"){l(!1);return}if(h==="a"&&e.toolName){jr(e.toolName),l(!0);return}};c(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",d)})}function
|
|
56
|
-
`);this.buffer=n.pop()||"";for(let o of n){let s=this.parseLine(o);if(s?.done)return s}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},Dr=class extends Is{constructor(e,n={}){super(e,n),this.toolCallsMap={}}parseLine(e){let n=e.trim();if(!n||!n.startsWith("data: "))return{done:!1};let o=n.slice(6);if(o==="[DONE]")return{done:!0,result:this.getResult()};let s;try{s=JSON.parse(o)}catch{return{done:!1}}let r=s.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let 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}}))}}},qr=class extends Ls{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i}){let c={model:e,messages:n,max_tokens:s,temperature:r};return i&&(c.stream=!0),o&&o.length>0&&(c.tools=o),c}normalizeResponse(e){let n=e.choices?.[0]?.message||{},o=(n.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:n.content||"",tool_calls:o}}createStreamParser(e,n={}){return new Dr(e,n)}},Fr=class extends Is{constructor(e,n={}){super(e,n),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let n=e.trim();if(!n.startsWith("data: "))return{done:!1};let o=n.slice(6),s;try{s=JSON.parse(o)}catch{return{done:!1}}switch(s.type){case"content_block_start":{let r=s.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=s.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let n={};if(e.inputJson)try{n=JSON.parse(e.inputJson)}catch{n=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:n}}})}}},Ur=class extends Ls{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:c}){let l={model:e,messages:n,max_tokens:s,temperature:r};return i&&(l.stream=!0),c?.system&&(l.system=c.system),o&&o.length>0&&(l.tools=o),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="",o=[];for(let s of e.content||[])s.type==="text"?n+=s.text:s.type==="tool_use"&&o.push({id:s.id,function:{name:s.name,arguments:s.input}});return{content:n,tool_calls:o}}createStreamParser(e,n={}){return new Fr(e,n)}},Br=class extends Is{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||{}}}))}}},Wr=class extends Ls{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:c}){let l={model:e,messages:n,stream:i,options:{temperature:r,num_predict:s,repeat_penalty:c?.repeat_penalty??1.05}};return o&&o.length>0&&(l.tools=o),l}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:(n.tool_calls||[]).map((o,s)=>({id:o.id||`ollama-${Date.now()}-${s}`,function:{name:o.function?.name||o.name||"unknown",arguments:o.function?.arguments||o.arguments||{}}}))}}createStreamParser(e,n={}){return new Br(e,n)}},ky=new qr,Sy=new Ur,Ey=new Wr;Ju.exports={WireProtocol:Ls,StreamParser:Is,OpenAICompatibleProtocol:qr,AnthropicProtocol:Ur,OllamaChatProtocol:Wr,OpenAIStreamParser:Dr,AnthropicStreamParser:Fr,OllamaStreamParser:Br,openaiProtocol:ky,anthropicProtocol:Sy,ollamaProtocol:Ey}});var Qu=Q((xT,Zu)=>{var Hr=require("axios"),Ty=require("http"),Ry=require("https"),{BaseProvider:Cy,readStreamErrorBody:Ay}=Ps(),{ollamaProtocol:Jn}=js(),Kr=new Ty.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Gr=new Ry.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Vu={"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}},Ba=class extends Cy{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Vu,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){Hr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Kr,httpsAgent:Gr}).then(e=>{let n=e.data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await Hr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Kr,httpsAgent:Gr})).data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:"user",content:o.join(`
|
|
57
|
-
`)};return s.length>0&&(r.images=s),r}return n})}async chat(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,c=Jn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1,extra:{repeat_penalty:o.repeat_penalty}}),l;try{l=await Hr.post(`${this.baseUrl}${Jn.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Kr,httpsAgent:Gr})}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 Jn.normalizeResponse(l.data)}async stream(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,c=o.onToken||(()=>{}),l=o.onThinkingToken||(()=>{}),u=Jn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0,extra:{repeat_penalty:o.repeat_penalty}}),d;try{d=await Hr.post(`${this.baseUrl}${Jn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:Kr,httpsAgent:Gr})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let h=p.response?.status?` [HTTP ${p.response.status}]`:"",m=await
|
|
58
|
-
|
|
59
|
-
`:"")+s.content;continue}if(s.role!=="system"&&s.role!=="tool"&&this._messageFormatCache.has(s)){o.push(this._messageFormatCache.get(s));continue}let r=this._formatSingleMessage(s,o);if(r){if(s.role!=="system"&&s.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(s);this._messageStringCache.set(i,r),this._messageFormatCache.set(s,r)}o.push(r)}}for(let s=o.length-1;s>0;s--)o[s].role==="user"&&o[s-1].role==="user"&&o.splice(s,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:o,system:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let s of e.tool_calls)o.push({type:"tool_use",id:s.id||`toolu-${Date.now()}`,name:s.function.name,input:typeof s.function.arguments=="string"?JSON.parse(s.function.arguments||"{}"):s.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=n[n.length-1],s={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(s),null):{role:"user",content:[s]}}if(Array.isArray(e.content)){let o=[];for(let s of e.content)s.type==="text"?o.push({type:"text",text:s.text??""}):s.type==="image"&&s.data&&o.push({type:"image",source:{type:"base64",media_type:s.media_type||"image/png",data:s.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return Cn.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),c=o.maxTokens||i?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d=this.formatTools(n),f=Cn.buildRequestBody({model:r,messages:l,tools:d,maxTokens:c,temperature:o.temperature??this.temperature,stream:!1,extra:{system:u}}),p;try{p=await od.post(`${this.baseUrl}${Cn.getEndpoint()}`,f,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let m=h.response?.status?` [HTTP ${h.response.status}]`:"",g=h.response?.data?.error?.message||h.response?.data?.error||h.message;throw new Error(`API Error${m}: ${g}`)}return Cn.normalizeResponse(p.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),c=o.maxTokens||i?.maxTokens||8192,l=o.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f=this.formatTools(n),p=Cn.buildRequestBody({model:r,messages:u,tools:f,maxTokens:c,temperature:o.temperature??this.temperature,stream:!0,extra:{system:d}}),h;try{h=await od.post(`${this.baseUrl}${Cn.getEndpoint()}`,p,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let y=g.response?.status?` [HTTP ${g.response.status}]`:"",w=await Py(g,v=>v?.error?.message||v?.error);throw new Error(`API Error${y}: ${w}`)}let m=Cn.createStreamParser(l);return new Promise((g,y)=>{o.signal&&o.signal.addEventListener("abort",()=>{h.data.destroy(),y(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",w=>{let{done:v,result:M}=m.feed(w.toString());v&&g(M)}),h.data.on("error",w=>{o.signal?.aborted||y(new Error(`Stream error: ${w.message}`))}),h.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return Cn.normalizeResponse(e)}};id.exports={AnthropicProvider:Ha,ANTHROPIC_MODELS:rd}});var dd=Q((ST,ud)=>{var cd=require("axios"),{BaseProvider:Iy,readStreamErrorBody:jy}=Ps(),{openaiProtocol:Zn}=js(),ld={"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}},Ka=class extends Iy{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||ld,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l=Zn.buildRequestBody({model:s,messages:c,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await cd.post(`${this.baseUrl}${Zn.getEndpoint()}`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return Zn.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,c=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u=Zn.buildRequestBody({model:s,messages:l,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),d;try{d=await cd.post(`${this.baseUrl}${Zn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let h=p.response?.status?` [HTTP ${p.response.status}]`:"",m=await jy(p,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let f=Zn.createStreamParser(c);return new Promise((p,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",m=>{let{done:g,result:y}=f.feed(m.toString());g&&p(y)}),d.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return Zn.normalizeResponse(e)}};ud.exports={GeminiProvider:Ka,GEMINI_MODELS:ld}});var md=Q((ET,pd)=>{var Yr=require("axios"),{BaseProvider:Dy,readStreamErrorBody:qy}=Ps(),{ollamaProtocol:Qn}=js(),fd="http://localhost:11434",Ga=class extends Dy{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||fd,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 Yr.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of n){let s=o.name||o.model;if(!s)continue;let r=s.replace(/:latest$/,""),i=32768;try{let c=await Yr.post(`${this.baseUrl}/api/show`,{name:s},{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:o.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:"user",content:o.join(`
|
|
60
|
-
`)};return s.length>0&&(r.images=s),r}return n})}async chat(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=Qn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await Yr.post(`${this.baseUrl}${Qn.getEndpoint()}`,r,{timeout:o.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 Qn.normalizeResponse(i.data)}async stream(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),i=Qn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),c;try{c=await Yr.post(`${this.baseUrl}${Qn.getEndpoint()}`,i,{timeout:o.timeout||this.timeout,responseType:"stream",signal:o.signal})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=await
|
|
61
|
-
`)}}function za(t,e){let n=$d[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function yd(t){let e=za(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function wd(){let t={};for(let r of zr){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:yd(r)})),n=e.reduce((r,i)=>r+i.cost,0),o=e.reduce((r,i)=>r+i.input,0),s=e.reduce((r,i)=>r+i.output,0);return{totalCost:n,totalInput:o,totalOutput:s,breakdown:e}}function
|
|
62
|
-
`)}function
|
|
63
|
-
`),c}catch(c){throw s.stop(),c}}async function
|
|
54
|
+
`)}var{Spinner:V$,MultiProgress:Z$,TaskProgress:Q$,ToolProgress:ey,setActiveTaskProgress:ty,getActiveTaskProgress:ny,cleanupTerminal:sy}=Ms(),{formatToolCall:oy,formatResult:ry,getToolSpinnerText:iy,formatToolSummary:ay,formatSectionHeader:cy,formatMilestone:ly}=Fu();Bu.exports={C:La,banner:J$,Spinner:V$,MultiProgress:Z$,TaskProgress:Q$,ToolProgress:ey,setActiveTaskProgress:ty,getActiveTaskProgress:ny,cleanupTerminal:sy,formatToolCall:oy,formatResult:ry,getToolSpinnerText:iy,formatToolSummary:ay,formatSectionHeader:cy,formatMilestone:ly}});var ft=Q((bT,zu)=>{var uy=require("readline"),{C:cn}=Fe(),Da=[/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/],Wu=[...Da,/\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 dy(t){for(let e of Wu)if(e.test(t))return e;return null}var Hu=[/\.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)/],fy=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,Ia=[/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 Ku(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let o=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(o.length===0)return!1;let s=r=>{let i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let c=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return c?c.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>s(u)):Ia.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Ia.some(c=>c.test(i))};return o.every(s)}var qa=[/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)/],Gu=[/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/],Yu=[...qa,...Gu],Fa=!1,Xn=null,ja=null;function py(t){Fa=t}function my(t){ja=t}function hy(){return Fa}function gy(t){Xn=t}function $y(t){for(let e of Da)if(e.test(t))return e;return null}function yy(t){if(/ssh\s/.test(t)&&Ku(t))return!1;for(let e of Yu)if(e.test(t))return!0;return!1}function wy(t){for(let e of qa)if(e.test(t))return!0;return!1}function by(t){if(process.env.NEX_UNPROTECT==="1"||!fy.test(t))return null;for(let e of Hu)if(e.test(t))return e;return null}function _y(t,e={}){if(Fa)return Promise.resolve(!0);if(ja)return ja(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return xy(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;Xn&&Xn.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(),p=`\x1B[${f};1H\x1B[2K${cn.yellow}${t}${cn.reset}`;for(let h=0;h<n.length;h++){let m=h===s,g=m?`${cn.yellow}\u276F${cn.reset}`:" ",y=m?`${cn.yellow}${n[h]}${cn.reset}`:n[h];p+=`\x1B[${f+1+h};1H\x1B[2K ${g} ${y}`}r(p)},l=f=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",d);let p=global._nexRawWrite||(g=>process.stdout.write(g)),h=i(),m="";for(let g=0;g<n.length+1;g++)m+=`\x1B[${h+g};1H\x1B[2K`;p(m),global._nexFooter&&global._nexFooter.drawFooter(),Xn&&Xn.resume(),o(f)},u=f=>{if(f===1){l(!1);return}f===2&&e.toolName&&jr(e.toolName),l(!0)},d=f=>{if(f[0]===3){l(!1);return}let p=f.toString();if(p==="\r"||p===`
|
|
55
|
+
`){u(s);return}if(p==="\x1B[A"){s=(s-1+n.length)%n.length,c();return}if(p==="\x1B[B"){s=(s+1)%n.length,c();return}let h=p.toLowerCase().trim();if(h==="y"){l(!0);return}if(h==="n"){l(!1);return}if(h==="a"&&e.toolName){jr(e.toolName),l(!0);return}};c(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",d)})}function xy(t,e){let n=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(o=>{let s=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(jr(e.toolName),o(!0)):o(i!=="n")};if(Xn)Xn.question(`${cn.yellow}${t} ${n}${cn.reset}`,s);else{let r=uy.createInterface({input:process.stdin,output:process.stdout});r.question(`${cn.yellow}${t} ${n}${cn.reset}`,i=>{r.close(),s(i)})}})}var jr=()=>{};function vy(t){jr=t}zu.exports={FORBIDDEN_PATTERNS:Da,SSH_FORBIDDEN_PATTERNS:Wu,BASH_PROTECTED_PATHS:Hu,SSH_SAFE_PATTERNS:Ia,isSSHReadOnly:Ku,DANGEROUS_BASH:Yu,CRITICAL_BASH:qa,NOTABLE_BASH:Gu,isForbidden:$y,isSSHForbidden:dy,isDangerous:yy,isCritical:wy,isBashPathForbidden:by,confirm:_y,setAutoConfirm:py,getAutoConfirm:hy,setConfirmHook:my,setReadlineInterface:gy,setAllowAlwaysHandler:vy}});var Ps=Q((_T,Xu)=>{async function ky(t,e){if(!t.response?.data)return t.message;let n=t.response.data;if(typeof n=="object"&&n!==null&&typeof n.pipe!="function")return e(n)||t.message;try{let o=await new Promise((r,i)=>{let c=[];n.on("data",l=>c.push(l)),n.on("end",()=>r(Buffer.concat(c).toString("utf8"))),n.on("error",i)}),s=JSON.parse(o);return e(s)||o||t.message}catch{return t.message}}var Ua=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,n,o={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,n,o={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};Xu.exports={BaseProvider:Ua,readStreamErrorBody:ky}});var js=Q((xT,Ju)=>{var Ls=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")}},Is=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 o of n){let s=this.parseLine(o);if(s?.done)return s}return{done:!1}}flush(){return this.buffer.trim()&&(this.parseLine(this.buffer),this.buffer=""),this.getResult()}parseLine(e){throw new Error("parseLine() not implemented")}getResult(){throw new Error("getResult() not implemented")}},Dr=class extends Is{constructor(e,n={}){super(e,n),this.toolCallsMap={}}parseLine(e){let n=e.trim();if(!n||!n.startsWith("data: "))return{done:!1};let o=n.slice(6);if(o==="[DONE]")return{done:!0,result:this.getResult()};let s;try{s=JSON.parse(o)}catch{return{done:!1}}let r=s.choices?.[0]?.delta;if(!r)return{done:!1};if(r.content&&(this.onToken(r.content),this.content+=r.content),r.tool_calls)for(let i of r.tool_calls){let 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}}))}}},qr=class extends Ls{getEndpoint(){return"/chat/completions"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i}){let c={model:e,messages:n,max_tokens:s,temperature:r};return i&&(c.stream=!0),o&&o.length>0&&(c.tools=o),c}normalizeResponse(e){let n=e.choices?.[0]?.message||{},o=(n.tool_calls||[]).map(s=>({id:s.id,function:{name:s.function.name,arguments:s.function.arguments}}));return{content:n.content||"",tool_calls:o}}createStreamParser(e,n={}){return new Dr(e,n)}},Fr=class extends Is{constructor(e,n={}){super(e,n),this.toolUses=[],this.currentToolIndex=-1}parseLine(e){let n=e.trim();if(!n.startsWith("data: "))return{done:!1};let o=n.slice(6),s;try{s=JSON.parse(o)}catch{return{done:!1}}switch(s.type){case"content_block_start":{let r=s.content_block;r?.type==="tool_use"&&(this.currentToolIndex=this.toolUses.length,this.toolUses.push({id:r.id,name:r.name,inputJson:""}));break}case"content_block_delta":{let r=s.delta;r?.type==="text_delta"&&r.text&&(this.onToken(r.text),this.content+=r.text),r?.type==="input_json_delta"&&r.partial_json!==void 0&&this.currentToolIndex>=0&&(this.toolUses[this.currentToolIndex].inputJson+=r.partial_json);break}case"content_block_stop":this.currentToolIndex=-1;break;case"message_stop":return{done:!0,result:this.getResult()}}return{done:!1}}getResult(){return{content:this.content,tool_calls:this.toolUses.filter(e=>e.name).map(e=>{let n={};if(e.inputJson)try{n=JSON.parse(e.inputJson)}catch{n=e.inputJson}return{id:e.id||`anthropic-${Date.now()}`,function:{name:e.name,arguments:n}}})}}},Ur=class extends Ls{getEndpoint(){return"/messages"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:c}){let l={model:e,messages:n,max_tokens:s,temperature:r};return i&&(l.stream=!0),c?.system&&(l.system=c.system),o&&o.length>0&&(l.tools=o),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="",o=[];for(let s of e.content||[])s.type==="text"?n+=s.text:s.type==="tool_use"&&o.push({id:s.id,function:{name:s.name,arguments:s.input}});return{content:n,tool_calls:o}}createStreamParser(e,n={}){return new Fr(e,n)}},Br=class extends Is{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||{}}}))}}},Wr=class extends Ls{getEndpoint(){return"/api/chat"}buildRequestBody({model:e,messages:n,tools:o,maxTokens:s,temperature:r,stream:i,extra:c}){let l={model:e,messages:n,stream:i,options:{temperature:r,num_predict:s,repeat_penalty:c?.repeat_penalty??1.05}};return o&&o.length>0&&(l.tools=o),l}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:(n.tool_calls||[]).map((o,s)=>({id:o.id||`ollama-${Date.now()}-${s}`,function:{name:o.function?.name||o.name||"unknown",arguments:o.function?.arguments||o.arguments||{}}}))}}createStreamParser(e,n={}){return new Br(e,n)}},Sy=new qr,Ey=new Ur,Ty=new Wr;Ju.exports={WireProtocol:Ls,StreamParser:Is,OpenAICompatibleProtocol:qr,AnthropicProtocol:Ur,OllamaChatProtocol:Wr,OpenAIStreamParser:Dr,AnthropicStreamParser:Fr,OllamaStreamParser:Br,openaiProtocol:Sy,anthropicProtocol:Ey,ollamaProtocol:Ty}});var Qu=Q((vT,Zu)=>{var Hr=require("axios"),Ry=require("http"),Cy=require("https"),{BaseProvider:Ay,readStreamErrorBody:Oy}=Ps(),{ollamaProtocol:Jn}=js(),Kr=new Ry.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Gr=new Cy.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Vu={"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}},Ba=class extends Ay{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Vu,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){Hr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Kr,httpsAgent:Gr}).then(e=>{let n=e.data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let n=(await Hr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Kr,httpsAgent:Gr})).data?.models||[];for(let o of n){let s=(o.name||o.model||"").replace(/:latest$/,"");!s||this.models[s]||(this.models[s]={id:s,name:o.name||s,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:"user",content:o.join(`
|
|
57
|
+
`)};return s.length>0&&(r.images=s),r}return n})}async chat(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,c=Jn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1,extra:{repeat_penalty:o.repeat_penalty}}),l;try{l=await Hr.post(`${this.baseUrl}${Jn.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Kr,httpsAgent:Gr})}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 Jn.normalizeResponse(l.data)}async stream(e,n,o={}){await this.discoverModels();let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,c=o.onToken||(()=>{}),l=o.onThinkingToken||(()=>{}),u=Jn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0,extra:{repeat_penalty:o.repeat_penalty}}),d;try{d=await Hr.post(`${this.baseUrl}${Jn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:Kr,httpsAgent:Gr})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let h=p.response?.status?` [HTTP ${p.response.status}]`:"",m=await Oy(p,g=>g?.error);throw new Error(`API Error${h}: ${m}`)}let f=Jn.createStreamParser(c,{onThinkingToken:l});return new Promise((p,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",m=>{let{done:g,result:y}=f.feed(m.toString());g&&p(y)}),d.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return Jn.normalizeResponse(e)}};Zu.exports={OllamaProvider:Ba,OLLAMA_MODELS:Vu}});var sd=Q((kT,nd)=>{var ed=require("axios"),{BaseProvider:Ny,readStreamErrorBody:My}=Ps(),{openaiProtocol:Vn}=js(),td={"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}},Wa=class extends Ny{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||td,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,{messages:c}=this.formatMessages(e),l=Vn.buildRequestBody({model:s,messages:c,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await ed.post(`${this.baseUrl}${Vn.getEndpoint()}`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return Vn.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,c=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u=Vn.buildRequestBody({model:s,messages:l,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),d;try{d=await ed.post(`${this.baseUrl}${Vn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let h=p.response?.status?` [HTTP ${p.response.status}]`:"",m=await My(p,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let f=Vn.createStreamParser(c);return new Promise((p,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",m=>{let{done:g,result:y}=f.feed(m.toString());g&&p(y)}),d.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return Vn.normalizeResponse(e)}};nd.exports={OpenAIProvider:Wa,OPENAI_MODELS:td}});var ad=Q((ST,id)=>{var od=require("axios"),{BaseProvider:Py,readStreamErrorBody:Ly}=Ps(),{anthropicProtocol:Cn}=js(),rd={"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}},Iy="2023-06-01",Ha=class extends Py{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||rd,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Iy}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n="",o=[];for(let s of e){if(s.role==="system"){n+=(n?`
|
|
58
|
+
|
|
59
|
+
`:"")+s.content;continue}if(s.role!=="system"&&s.role!=="tool"&&this._messageFormatCache.has(s)){o.push(this._messageFormatCache.get(s));continue}let r=this._formatSingleMessage(s,o);if(r){if(s.role!=="system"&&s.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let i=this._getMessageCacheKey(s);this._messageStringCache.set(i,r),this._messageFormatCache.set(s,r)}o.push(r)}}for(let s=o.length-1;s>0;s--)o[s].role==="user"&&o[s-1].role==="user"&&o.splice(s,0,{role:"assistant",content:[{type:"text",text:"[continuing]"}]});return{messages:o,system:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e,n=[]){if(e.role==="assistant"){let o=[];if(e.content&&o.push({type:"text",text:e.content}),e.tool_calls)for(let s of e.tool_calls)o.push({type:"tool_use",id:s.id||`toolu-${Date.now()}`,name:s.function.name,input:typeof s.function.arguments=="string"?JSON.parse(s.function.arguments||"{}"):s.function.arguments||{}});return{role:"assistant",content:o.length>0?o:[{type:"text",text:""}]}}if(e.role==="tool"){let o=n[n.length-1],s={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return o&&o.role==="user"&&Array.isArray(o.content)&&o.content[0]?.type==="tool_result"?(o.content.push(s),null):{role:"user",content:[s]}}if(Array.isArray(e.content)){let o=[];for(let s of e.content)s.type==="text"?o.push({type:"text",text:s.text??""}):s.type==="image"&&s.data&&o.push({type:"image",source:{type:"base64",media_type:s.media_type||"image/png",data:s.data}});return{role:"user",content:o}}return{role:"user",content:e.content}}formatTools(e){return Cn.formatTools(e)}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),c=o.maxTokens||i?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d=this.formatTools(n),f=Cn.buildRequestBody({model:r,messages:l,tools:d,maxTokens:c,temperature:o.temperature??this.temperature,stream:!1,extra:{system:u}}),p;try{p=await od.post(`${this.baseUrl}${Cn.getEndpoint()}`,f,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let m=h.response?.status?` [HTTP ${h.response.status}]`:"",g=h.response?.data?.error?.message||h.response?.data?.error||h.message;throw new Error(`API Error${m}: ${g}`)}return Cn.normalizeResponse(p.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),c=o.maxTokens||i?.maxTokens||8192,l=o.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f=this.formatTools(n),p=Cn.buildRequestBody({model:r,messages:u,tools:f,maxTokens:c,temperature:o.temperature??this.temperature,stream:!0,extra:{system:d}}),h;try{h=await od.post(`${this.baseUrl}${Cn.getEndpoint()}`,p,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(g){if(g.name==="CanceledError"||g.name==="AbortError"||g.code==="ERR_CANCELED")throw g;let y=g.response?.status?` [HTTP ${g.response.status}]`:"",w=await Ly(g,v=>v?.error?.message||v?.error);throw new Error(`API Error${y}: ${w}`)}let m=Cn.createStreamParser(l);return new Promise((g,y)=>{o.signal&&o.signal.addEventListener("abort",()=>{h.data.destroy(),y(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",w=>{let{done:v,result:M}=m.feed(w.toString());v&&g(M)}),h.data.on("error",w=>{o.signal?.aborted||y(new Error(`Stream error: ${w.message}`))}),h.data.on("end",()=>{g(m.flush())})})}normalizeResponse(e){return Cn.normalizeResponse(e)}};id.exports={AnthropicProvider:Ha,ANTHROPIC_MODELS:rd}});var dd=Q((ET,ud)=>{var cd=require("axios"),{BaseProvider:jy,readStreamErrorBody:Dy}=Ps(),{openaiProtocol:Zn}=js(),ld={"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}},Ka=class extends jy{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||ld,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let n=[];for(let o of e){if(this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let s=this._getMessageCacheKey(o);if(this._messageStringCache.has(s)){let i=this._messageStringCache.get(s);this._messageFormatCache.set(o,i),n.push(i);continue}let r=this._formatSingleMessage(o);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(s,r),this._messageFormatCache.set(o,r),n.push(r)}return{messages:n}}_getMessageCacheKey(e){let n=e.role||"",o=typeof e.content=="string"?e.content.substring(0,100):"",s=e.tool_calls?e.tool_calls.length:0;return`${n}:${o.length}:${s}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(n=>({id:n.id||`call-${Date.now()}`,type:"function",function:{name:n.function.name,arguments:typeof n.function.arguments=="string"?n.function.arguments:JSON.stringify(n.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let n=[];for(let o of e.content)if(o.type==="text")n.push({type:"text",text:o.text??""});else if(o.type==="image"&&o.data){let s=o.data.startsWith("data:")?o.data:`data:${o.media_type||"image/png"};base64,${o.data}`;n.push({type:"image_url",image_url:{url:s,detail:"auto"}})}return{role:"user",content:n}}return{role:e.role,content:e.content}}async chat(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l=Zn.buildRequestBody({model:s,messages:c,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!1}),u;try{u=await cd.post(`${this.baseUrl}${Zn.getEndpoint()}`,l,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",p=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${p}`)}return Zn.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,c=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u=Zn.buildRequestBody({model:s,messages:l,tools:n,maxTokens:i,temperature:o.temperature??this.temperature,stream:!0}),d;try{d=await cd.post(`${this.baseUrl}${Zn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let h=p.response?.status?` [HTTP ${p.response.status}]`:"",m=await Dy(p,g=>g?.error?.message||g?.error);throw new Error(`API Error${h}: ${m}`)}let f=Zn.createStreamParser(c);return new Promise((p,h)=>{o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),h(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",m=>{let{done:g,result:y}=f.feed(m.toString());g&&p(y)}),d.data.on("error",m=>{o.signal?.aborted||h(new Error(`Stream error: ${m.message}`))}),d.data.on("end",()=>{p(f.flush())})})}normalizeResponse(e){return Zn.normalizeResponse(e)}};ud.exports={GeminiProvider:Ka,GEMINI_MODELS:ld}});var md=Q((TT,pd)=>{var Yr=require("axios"),{BaseProvider:qy,readStreamErrorBody:Fy}=Ps(),{ollamaProtocol:Qn}=js(),fd="http://localhost:11434",Ga=class extends qy{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||fd,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 Yr.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let o of n){let s=o.name||o.model;if(!s)continue;let r=s.replace(/:latest$/,""),i=32768;try{let c=await Yr.post(`${this.baseUrl}/api/show`,{name:s},{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:o.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(n=>{if(n.role==="user"&&Array.isArray(n.content)){let o=[],s=[];for(let i of n.content)i.type==="text"?o.push(i.text??""):i.type==="image"&&i.data&&s.push(i.data);let r={role:"user",content:o.join(`
|
|
60
|
+
`)};return s.length>0&&(r.images=s),r}return n})}async chat(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=Qn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!1}),i;try{i=await Yr.post(`${this.baseUrl}${Qn.getEndpoint()}`,r,{timeout:o.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 Qn.normalizeResponse(i.data)}async stream(e,n,o={}){this._modelsLoaded||await this.loadModels();let s=o.model||this.defaultModel;if(!s)throw new Error("No local model available. Is Ollama running?");let r=o.onToken||(()=>{}),i=Qn.buildRequestBody({model:s,messages:this._formatMessages(e),tools:n,maxTokens:o.maxTokens||8192,temperature:o.temperature??this.temperature,stream:!0}),c;try{c=await Yr.post(`${this.baseUrl}${Qn.getEndpoint()}`,i,{timeout:o.timeout||this.timeout,responseType:"stream",signal:o.signal})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.status?` [HTTP ${u.response.status}]`:"",f=await Fy(u,p=>p?.error);throw new Error(`API Error${d}: ${f}`)}let l=Qn.createStreamParser(r);return new Promise((u,d)=>{o.signal&&o.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:h}=l.feed(f.toString());p&&u(h)}),c.data.on("error",f=>{o.signal?.aborted||d(new Error(`Stream error: ${f.message}`))}),c.data.on("end",()=>{u(l.flush())})})}normalizeResponse(e){return Qn.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}};pd.exports={LocalProvider:Ga,DEFAULT_LOCAL_URL:fd}});var An=Q((RT,gd)=>{"use strict";var Rt=require("fs"),hd=require("path");function Uy(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function By(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function Wy(t,e){let n=hd.dirname(t),o=hd.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{Rt.existsSync(n)||Rt.mkdirSync(n,{recursive:!0}),Rt.writeFileSync(o,e,"utf-8"),Rt.renameSync(o,t)}catch(s){try{Rt.unlinkSync(o)}catch{}throw s}}function Hy(t,e,{timeout:n=5e3,retryMs:o=50}={}){let s=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=Rt.openSync(s,"wx"),Rt.writeSync(i,Buffer.from(String(process.pid))),Rt.closeSync(i),i=-1;try{return e()}finally{try{Rt.unlinkSync(s)}catch{}}}catch(c){if(i!==-1)try{Rt.closeSync(i)}catch{}if(c.code!=="EEXIST")throw c;try{let l=Rt.readFileSync(s,"utf-8").trim(),u=parseInt(l,10);if(!Uy(u)){try{Rt.unlinkSync(s)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{Rt.unlinkSync(s)}catch{}return e()}By(o)}}}gd.exports={atomicWrite:Wy,withFileLockSync:Hy}});var qs=Q((CT,vd)=>{var Ds=require("fs"),Ya=require("path"),{atomicWrite:Ky,withFileLockSync:Gy}=An(),$d={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:{}},zr=[],On={};function Yy(t,e,n,o){if(zr.push({provider:t,model:e,input:n,output:o}),On[t]!==void 0){let s=_d(t);s.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${s.spent.toFixed(2)} / $${s.limit.toFixed(2)}\x1B[0m
|
|
61
|
+
`)}}function za(t,e){let n=$d[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function yd(t){let e=za(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function wd(){let t={};for(let r of zr){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:yd(r)})),n=e.reduce((r,i)=>r+i.cost,0),o=e.reduce((r,i)=>r+i.input,0),s=e.reduce((r,i)=>r+i.output,0);return{totalCost:n,totalInput:o,totalOutput:s,breakdown:e}}function zy(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:o}=wd();if(o.length===0)return"No token usage recorded this session.";let s=[];s.push("Session Token Usage:"),s.push("");for(let r of o){let i=r.cost>0?`$${r.cost.toFixed(4)}`:"free";s.push(` ${r.provider}:${r.model}`),s.push(` Input: ${r.input.toLocaleString()} tokens`),s.push(` Output: ${r.output.toLocaleString()} tokens`),s.push(` Cost: ${i}`)}return s.push(""),s.push(` Total: ${e.toLocaleString()} in + ${n.toLocaleString()} out = $${t.toFixed(4)}`),s.join(`
|
|
62
|
+
`)}function Xy(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function Jy(t,e,n,o){let s=za(t,e),r=(n*s.input+o*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Vy(){zr=[]}function Zy(t,e){On[t]=e}function Qy(t){delete On[t]}function ew(){return{...On}}function bd(t){let e=0;for(let n of zr)n.provider===t&&(e+=yd(n));return e}function _d(t){let e=bd(t),n=On[t];if(n===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let o=Math.max(0,n-e);return{allowed:e<n,spent:e,limit:n,remaining:o}}function xd(){let t=Ya.join(process.cwd(),".nex","config.json");if(Ds.existsSync(t))try{let e=JSON.parse(Ds.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(On={...e.costLimits})}catch{}}function tw(){let t=Ya.join(process.cwd(),".nex"),e=Ya.join(t,"config.json");Ds.existsSync(t)||Ds.mkdirSync(t,{recursive:!0}),Gy(e,()=>{let n={};if(Ds.existsSync(e))try{n=JSON.parse(Ds.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=On,Ky(e,JSON.stringify(n,null,2))})}function nw(){On={}}xd();vd.exports={PRICING:$d,trackUsage:Yy,getSessionCosts:wd,formatCosts:zy,formatCostHint:Jy,resetCosts:Vy,getPricing:za,setCostLimit:Zy,removeCostLimit:Qy,getCostLimits:ew,getProviderSpend:bd,checkBudget:_d,loadCostLimits:xd,saveCostLimits:tw,resetCostLimits:nw,estimateTokens:Xy}});var Xr=Q((AT,kd)=>{function Xa(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var sw=Xa();function ow(...t){Xa()&&console.log(...t)}function rw(...t){Xa()&&console.warn(...t)}kd.exports={DEBUG:sw,debugLog:ow,warnLog:rw}});var Td=Q((OT,Ed)=>{"use strict";var iw=new Set(["read_file","grep","glob","search_files","list_directory"]),aw=new Set(["write_file","edit_file","patch_file"]),cw=new Set(["bash"]),lw=new Set(["web_search","web_fetch","perplexity_search"]);function Sd(t,e){let n=0,o=0,s=0,r=0,i=0;for(let[c,l]of t)i+=l,iw.has(c)&&(n+=l),aw.has(c)&&(o+=l),cw.has(c)&&(s+=l),lw.has(c)&&(r+=l);return i===0?`Phase ${e}`:r/i>.5?"Research":n/i>.5?"Exploration":o/i>.3?"Implementation":s/i>.3&&o/i<.15?"Verification":`Phase ${e}`}var Ja=class{constructor(e){this._N=e,this._disabled=e<=0,this._phaseNum=0,this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now()}record(e,n,o,s){if(this._disabled)return null;this._stepsThisPhase++;for(let i of n)this._phaseCounts.set(i,(this._phaseCounts.get(i)||0)+1);if(this._stepsThisPhase<this._N)return null;this._phaseNum++;let r={phaseNum:this._phaseNum,phaseName:Sd(this._phaseCounts,this._phaseNum),stepCount:this._stepsThisPhase,toolCounts:new Map(this._phaseCounts),elapsed:Date.now()-this._phaseStart,filesRead:new Set(o),filesModified:new Set(s)};return this._stepsThisPhase=0,this._phaseCounts=new Map,this._phaseStart=Date.now(),r}};Ed.exports={MilestoneTracker:Ja,_phaseName:Sd}});var Fs=Q((NT,Rd)=>{var yo=je(),uw={"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 dw(){return yo.getActiveModel()}function fw(t){return yo.setActiveModel(t)}function pw(){return yo.getModelNames()}function mw(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let o=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(o)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let o=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(o)}catch{}let n=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)try{return JSON.parse(n[1].trim())}catch{}return null}async function hw(t,e){let{C:n}=Fe(),{Spinner:o}=Fe(),s=new o("Thinking...");s.start();let r=!0,i="";try{let c=await yo.callStream(t,e,{onToken:l=>{r&&(s.stop(),process.stdout.write(`${n.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?s.stop():process.stdout.write(`${n.reset}
|
|
63
|
+
`),c}catch(c){throw s.stop(),c}}async function gw(t,e){return yo.callChat(t,e)}Rd.exports={MODELS:uw,getActiveModel:dw,setActiveModel:fw,getModelNames:pw,callOllamaStream:hw,callOllama:gw,parseToolArgs:mw}});var Od=Q((PT,Ad)=>{var Jr=require("path"),{C:q}=Fe(),{T:Va,isDark:MT}=Yn(),{confirm:$w,getAutoConfirm:yw}=ft(),Cd=2e3;function wo(t,e){let n=t.split(`
|
|
64
64
|
`),o=e.split(`
|
|
65
|
-
`),s=[],r=n.length,i=o.length;if(r>Cd||i>Cd){for(let f of n)s.push({type:"remove",line:f});for(let f of o)s.push({type:"add",line:f});return s}let 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]===o[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]===o[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:o[u-1]}),u--):(d.unshift({type:"remove",line:n[l-1]}),l--);return d}function
|
|
66
|
-
${q.bold}${q.cyan} Diff: ${t}${q.reset}`);let s=wo(e,n),r=[];if(s.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${q.gray} (no changes)${q.reset}`);return}let i=Math.max(0,r[0]-o),c=Math.min(s.length,r[r.length-1]+o+1);i>0&&console.log(`${q.gray} ...${q.reset}`);for(let l=i;l<c;l++){let u=s[l];switch(u.type){case"remove":console.log(`${q.red} - ${u.line}${q.reset}`);break;case"add":console.log(`${q.green} + ${u.line}${q.reset}`);break;default:console.log(`${q.gray} ${u.line}${q.reset}`)}}c<s.length&&console.log(`${q.gray} ...${q.reset}`),console.log()}function
|
|
67
|
-
${q.bold}${q.cyan} File exists \u2014 showing changes: ${t}${q.reset}`);let o=wo(e,n),s=0;for(let i of o)i.type!=="same"&&s++;if(s===0){console.log(`${q.gray} (identical content)${q.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${q.gray} ...(${s-r} more changes)${q.reset}`);break}switch(i.type){case"remove":console.log(`${q.red} - ${i.line}${q.reset}`),r++;break;case"add":console.log(`${q.green} + ${i.line}${q.reset}`),r++;break;default:r>0&&console.log(`${q.gray} ${i.line}${q.reset}`)}}console.log()}function
|
|
65
|
+
`),s=[],r=n.length,i=o.length;if(r>Cd||i>Cd){for(let f of n)s.push({type:"remove",line:f});for(let f of o)s.push({type:"add",line:f});return s}let 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]===o[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]===o[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:o[u-1]}),u--):(d.unshift({type:"remove",line:n[l-1]}),l--);return d}function ww(t,e,n,o=3){console.log(`
|
|
66
|
+
${q.bold}${q.cyan} Diff: ${t}${q.reset}`);let s=wo(e,n),r=[];if(s.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${q.gray} (no changes)${q.reset}`);return}let i=Math.max(0,r[0]-o),c=Math.min(s.length,r[r.length-1]+o+1);i>0&&console.log(`${q.gray} ...${q.reset}`);for(let l=i;l<c;l++){let u=s[l];switch(u.type){case"remove":console.log(`${q.red} - ${u.line}${q.reset}`);break;case"add":console.log(`${q.green} + ${u.line}${q.reset}`);break;default:console.log(`${q.gray} ${u.line}${q.reset}`)}}c<s.length&&console.log(`${q.gray} ...${q.reset}`),console.log()}function bw(t,e,n){console.log(`
|
|
67
|
+
${q.bold}${q.cyan} File exists \u2014 showing changes: ${t}${q.reset}`);let o=wo(e,n),s=0;for(let i of o)i.type!=="same"&&s++;if(s===0){console.log(`${q.gray} (identical content)${q.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${q.gray} ...(${s-r} more changes)${q.reset}`);break}switch(i.type){case"remove":console.log(`${q.red} - ${i.line}${q.reset}`),r++;break;case"add":console.log(`${q.green} + ${i.line}${q.reset}`),r++;break;default:r>0&&console.log(`${q.gray} ${i.line}${q.reset}`)}}console.log()}function _w(t,e){console.log(`
|
|
68
68
|
${q.bold}${q.cyan} New file: ${t}${q.reset}`);let n=e.split(`
|
|
69
|
-
`),o=n.slice(0,20);for(let s of o)console.log(`${q.green} + ${s}${q.reset}`);n.length>20&&console.log(`${q.gray} ...+${n.length-20} more lines${q.reset}`),console.log()}async function
|
|
69
|
+
`),o=n.slice(0,20);for(let s of o)console.log(`${q.green} + ${s}${q.reset}`);n.length>20&&console.log(`${q.gray} ...+${n.length-20} more lines${q.reset}`),console.log()}async function xw(t){return yw()?!0:$w(` ${t}?`)}function vw(t,e,n,o){let s=o||process.stdout.columns||80,r=Math.floor((s-3)/2);console.log(`
|
|
70
70
|
${q.bold}${q.cyan} Side-by-side: ${t}${q.reset}`),console.log(` ${q.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${q.reset}`);let i=wo(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 h=[];for(;l<i.length&&i[l].type==="remove";)h.push(i[l].line),l++;let m=[];for(;l<i.length&&i[l].type==="add";)m.push(i[l].line),l++;let g=Math.max(h.length,m.length);for(let y=0;y<g;y++)c.push({left:y<h.length?h[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((h,m)=>h.type!=="same"?m:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${q.gray}(no changes)${q.reset}`);return}let d=Math.max(0,u[0]-2),f=Math.min(c.length,u[u.length-1]+3),p=(h,m)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?h.substring(0,m):h+" ".repeat(m-g.length)};d>0&&console.log(` ${q.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${q.reset}`);for(let h=d;h<f;h++){let m=c[h];if(m.type==="same")console.log(` ${q.gray}${p(m.left,r)}${q.reset}\u2502${q.gray}${p(m.right,r)}${q.reset}`);else{let g=m.left?`${q.red}${p(m.left,r)}${q.reset}`:`${p("",r)}`,y=m.right?`${q.green}${p(m.right,r)}${q.reset}`:`${p("",r)}`;console.log(` ${g}\u2502${y}`)}}f<c.length&&console.log(` ${q.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${q.reset}`),console.log(` ${q.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${q.reset}
|
|
71
|
-
`)}function
|
|
71
|
+
`)}function kw(t,e,n,o={}){let s=o.label||"Update",r=o.context||3,i=o.annotations||[],c=Jr.isAbsolute(t)?Jr.relative(process.cwd(),t):t,l=wo(e,n),u=1,d=1;for(let O of l)O.type==="same"?(O.oldLine=u++,O.newLine=d++):O.type==="remove"?(O.oldLine=u++,O.newLine=null):(O.oldLine=null,O.newLine=d++);let f=0,p=0;for(let O of l)O.type==="add"?f++:O.type==="remove"&&p++;if(console.log(`
|
|
72
72
|
${q.green}\u23FA${q.reset} ${q.bold}${s}(${c})${q.reset}`),f===0&&p===0){console.log(` ${q.dim}\u23BF (no changes)${q.reset}
|
|
73
|
-
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),p>0&&h.push(`removed ${p} line${p!==1?"s":""}`),i.length>0){let O=i.filter(X=>X.severity==="error").length,D=i.filter(X=>X.severity==="warn").length,K=i.filter(X=>X.severity==="info").length,V=[];O>0&&V.push(`${q.red}${O} error${O!==1?"s":""}${q.dim}`),D>0&&V.push(`${q.yellow}${D} warning${D!==1?"s":""}${q.dim}`),K>0&&V.push(`${q.cyan}${K} info${K!==1?"s":""}${q.dim}`),h.push(`found ${V.join(", ")}`)}console.log(` ${q.dim}\u23BF ${h.join(", ")}${q.reset}`);let g=[];l.forEach((O,D)=>{O.type!=="same"&&g.push(D)});let y=[],w=null,v=null;for(let O of g){let D=Math.max(0,O-r),K=Math.min(l.length-1,O+r);w===null?(w=D,v=K):(D<=v+1||(y.push([w,v]),w=D),v=K)}w!==null&&y.push([w,v]);let M=" ",C=process.stdout.columns||120;function S(O,D,K){let V=K.replace(/\x1b\[[0-9;]*m/g,""),X=K+" ".repeat(Math.max(0,C-V.length));return`${O}${D}${X}${q.reset}`}for(let O=0;O<y.length;O++){O>0&&console.log(`${M}${q.dim}\xB7\xB7\xB7${q.reset}`);let[D,K]=y[O];for(let V=D;V<=K;V++){let X=l[V],B=X.newLine!=null?X.newLine:X.oldLine,R=String(B).padStart(4),ye=X.type!=="remove"?i.filter(be=>be.line===X.newLine):[];X.type==="remove"?console.log(S(Va.diff_rem_bg,q.red,`${M}${R} - ${X.line}`)):X.type==="add"?console.log(S(Va.diff_add_bg,q.green,`${M}${R} + ${X.line}`)):console.log(`${M}${q.dim}${R} ${q.reset}${X.line}`);for(let be of ye){let
|
|
73
|
+
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),p>0&&h.push(`removed ${p} line${p!==1?"s":""}`),i.length>0){let O=i.filter(X=>X.severity==="error").length,D=i.filter(X=>X.severity==="warn").length,K=i.filter(X=>X.severity==="info").length,V=[];O>0&&V.push(`${q.red}${O} error${O!==1?"s":""}${q.dim}`),D>0&&V.push(`${q.yellow}${D} warning${D!==1?"s":""}${q.dim}`),K>0&&V.push(`${q.cyan}${K} info${K!==1?"s":""}${q.dim}`),h.push(`found ${V.join(", ")}`)}console.log(` ${q.dim}\u23BF ${h.join(", ")}${q.reset}`);let g=[];l.forEach((O,D)=>{O.type!=="same"&&g.push(D)});let y=[],w=null,v=null;for(let O of g){let D=Math.max(0,O-r),K=Math.min(l.length-1,O+r);w===null?(w=D,v=K):(D<=v+1||(y.push([w,v]),w=D),v=K)}w!==null&&y.push([w,v]);let M=" ",C=process.stdout.columns||120;function S(O,D,K){let V=K.replace(/\x1b\[[0-9;]*m/g,""),X=K+" ".repeat(Math.max(0,C-V.length));return`${O}${D}${X}${q.reset}`}for(let O=0;O<y.length;O++){O>0&&console.log(`${M}${q.dim}\xB7\xB7\xB7${q.reset}`);let[D,K]=y[O];for(let V=D;V<=K;V++){let X=l[V],B=X.newLine!=null?X.newLine:X.oldLine,R=String(B).padStart(4),ye=X.type!=="remove"?i.filter(be=>be.line===X.newLine):[];X.type==="remove"?console.log(S(Va.diff_rem_bg,q.red,`${M}${R} - ${X.line}`)):X.type==="add"?console.log(S(Va.diff_add_bg,q.green,`${M}${R} + ${X.line}`)):console.log(`${M}${q.dim}${R} ${q.reset}${X.line}`);for(let be of ye){let pe=q.cyan,me="\u2139";be.severity==="error"?(pe=q.red,me="\u2716"):be.severity==="warn"&&(pe=q.yellow,me="\u26A0"),console.log(`${M} ${pe}${me} ${be.message}${q.reset}`)}}}console.log()}function Sw(t,e,n={}){let o=Jr.isAbsolute(t)?Jr.relative(process.cwd(),t):t,s=e.split(`
|
|
74
74
|
`),r=n.annotations||[];console.log(`
|
|
75
|
-
${q.green}\u23FA${q.reset} ${q.bold}Create(${o})${q.reset}`);let i=[`${s.length} line${s.length!==1?"s":""}`];if(r.length>0){let f=r.filter(g=>g.severity==="error").length,p=r.filter(g=>g.severity==="warn").length,h=r.filter(g=>g.severity==="info").length,m=[];f>0&&m.push(`${q.red}${f} error${f!==1?"s":""}${q.dim}`),p>0&&m.push(`${q.yellow}${p} warning${p!==1?"s":""}${q.dim}`),h>0&&m.push(`${q.cyan}${h} info${h!==1?"s":""}${q.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${q.dim}\u23BF ${i.join(", ")}${q.reset}`);let l=" ",u=process.stdout.columns||120,d=Math.min(s.length,20);for(let f=0;f<d;f++){let p=String(f+1).padStart(4),h=f+1,m=r.filter(v=>v.line===h),g=`${l}${p} + ${s[f]}`,y=g.replace(/\x1b\[[0-9;]*m/g,""),w=g+" ".repeat(Math.max(0,u-y.length));console.log(`${Va.diff_add_bg}${q.green}${w}${q.reset}`);for(let v of m){let M=q.cyan,C="\u2139";v.severity==="error"?(M=q.red,C="\u2716"):v.severity==="warn"&&(M=q.yellow,C="\u26A0"),console.log(`${l} ${M}${C} ${v.message}${q.reset}`)}}s.length>20&&console.log(`${l}${q.dim} ...+${s.length-20} more lines${q.reset}`),console.log()}Ad.exports={diffLines:wo,showEditDiff:
|
|
75
|
+
${q.green}\u23FA${q.reset} ${q.bold}Create(${o})${q.reset}`);let i=[`${s.length} line${s.length!==1?"s":""}`];if(r.length>0){let f=r.filter(g=>g.severity==="error").length,p=r.filter(g=>g.severity==="warn").length,h=r.filter(g=>g.severity==="info").length,m=[];f>0&&m.push(`${q.red}${f} error${f!==1?"s":""}${q.dim}`),p>0&&m.push(`${q.yellow}${p} warning${p!==1?"s":""}${q.dim}`),h>0&&m.push(`${q.cyan}${h} info${h!==1?"s":""}${q.dim}`),i.push(`found ${m.join(", ")}`)}console.log(` ${q.dim}\u23BF ${i.join(", ")}${q.reset}`);let l=" ",u=process.stdout.columns||120,d=Math.min(s.length,20);for(let f=0;f<d;f++){let p=String(f+1).padStart(4),h=f+1,m=r.filter(v=>v.line===h),g=`${l}${p} + ${s[f]}`,y=g.replace(/\x1b\[[0-9;]*m/g,""),w=g+" ".repeat(Math.max(0,u-y.length));console.log(`${Va.diff_add_bg}${q.green}${w}${q.reset}`);for(let v of m){let M=q.cyan,C="\u2139";v.severity==="error"?(M=q.red,C="\u2716"):v.severity==="warn"&&(M=q.yellow,C="\u26A0"),console.log(`${l} ${M}${C} ${v.message}${q.reset}`)}}s.length>20&&console.log(`${l}${q.dim} ...+${s.length-20} more lines${q.reset}`),console.log()}Ad.exports={diffLines:wo,showEditDiff:ww,showWriteDiff:bw,showNewFilePreview:_w,confirmFileChange:xw,showSideBySideDiff:vw,showClaudeDiff:kw,showClaudeNewFile:Sw}});var Nn=Q((LT,Pd)=>{var Nd=require("util").promisify(require("child_process").exec),Ew=require("util").promisify(require("child_process").execFile),{C:Ge}=Fe();async function Za(t){try{let{stdout:e}=await Nd(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Vr(...t){try{let{stdout:e}=await Ew("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Tw(){return await Za("git rev-parse --is-inside-work-tree")==="true"}async function Rw(){return await Za("git branch --show-current")}async function Qa(){try{let{stdout:t}=await Nd("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
76
76
|
`).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function Zr(t=!1){return await Za(`git diff ${t?"--cached":""}`)||""}async function ec(){return(await Qa()).map(e=>e.file)}async function Md(){let t=await ec();if(t.length===0)return null;let e=await Zr(),o=await Zr(!0)||e,s=0,r=0;if(o){let d=o.split(`
|
|
77
|
-
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&s++,f.startsWith("-")&&!f.startsWith("---")&&r++}else s=t.length;let i="chore",c=t.join(" ").toLowerCase();c.includes("test")?i="test":c.includes("readme")||c.includes("doc")?i="docs":s>r*2?i="feat":r>s?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:s,deletions:r}}}async function
|
|
77
|
+
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&s++,f.startsWith("-")&&!f.startsWith("---")&&r++}else s=t.length;let i="chore",c=t.join(" ").toLowerCase();c.includes("test")?i="test":c.includes("readme")||c.includes("doc")?i="docs":s>r*2?i="feat":r>s?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:s,deletions:r}}}async function Cw(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Vr("checkout","-b",n)!==null?n:null}async function Aw(t){return await Vr("add","-A"),await Vr("commit","-m",t)?await Vr("rev-parse","--short","HEAD"):null}async function Ow(){let t=await Md();if(!t)return`${Ge.dim}No changes${Ge.reset}`;let e=[];e.push(`
|
|
78
78
|
${Ge.bold}${Ge.cyan}Git Diff Summary:${Ge.reset}`),e.push(` ${Ge.green}+${t.stats.additions}${Ge.reset} ${Ge.red}-${t.stats.deletions}${Ge.reset} in ${t.files.length} file(s)`),e.push(`
|
|
79
79
|
${Ge.bold}${Ge.cyan}Files:${Ge.reset}`);for(let n of t.files.slice(0,20))e.push(` ${Ge.dim}${n}${Ge.reset}`);return t.files.length>20&&e.push(` ${Ge.dim}...+${t.files.length-20} more${Ge.reset}`),e.push(`
|
|
80
80
|
${Ge.bold}${Ge.cyan}Suggested message:${Ge.reset}`),e.push(` ${Ge.cyan}${t.summary}${Ge.reset}
|
|
81
81
|
`),e.join(`
|
|
82
|
-
`)}async function
|
|
82
|
+
`)}async function Nw(){return(await Qa()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Mw(){let t=await ec();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let o of t.slice(0,10))e.push(` ${o}`);let n=await Zr();if(n){let o=n.length>5e3?n.substring(0,5e3)+`
|
|
83
83
|
...(truncated)`:n;e.push(`
|
|
84
84
|
DIFF:
|
|
85
85
|
${o}`)}return e.join(`
|
|
86
|
-
`)}Pd.exports={isGitRepo:
|
|
87
|
-
`).map(n=>{let o=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let s=o[2].trim();return s.startsWith(Qr)?{index:parseInt(o[1],10),label:s,shortName:s.replace(`${Qr}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function
|
|
86
|
+
`)}Pd.exports={isGitRepo:Tw,getCurrentBranch:Rw,getStatus:Qa,getDiff:Zr,getChangedFiles:ec,analyzeDiff:Md,createBranch:Cw,commit:Aw,formatDiffSummary:Ow,getDiffContext:Mw,getMergeConflicts:Nw}});var yn=Q((jT,Fd)=>{var nt=require("fs").promises,IT=require("fs"),Dt=require("path"),Pw=require("crypto"),{execSync:bo}=require("child_process"),Lw=100*1024,jd=50,bt=[],Us=[];function Iw(t,e,n,o){for(bt.push({tool:t,filePath:e,oldContent:n,newContent:o,timestamp:Date.now()});bt.length>jd;)bt.shift();Us.length=0,Dd(bt[bt.length-1]).catch(()=>{})}async function jw(){if(bt.length===0)return null;let t=bt.pop();if(t.oldContent===null)try{await nt.unlink(t.filePath)}catch{}else await nt.writeFile(t.filePath,t.oldContent,"utf-8");return Us.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Dw(){if(Us.length===0)return null;let t=Us.pop();return await nt.writeFile(t.filePath,t.newContent,"utf-8"),bt.push(t),{tool:t.tool,filePath:t.filePath}}function qw(t=10){return bt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Fw(){return bt.length}function Uw(){return Us.length}function Bw({diskToo:t=!0}={}){if(bt.length=0,Us.length=0,t){let e=ei();nt.readdir(e).then(n=>{for(let o of n)o.endsWith(".json")&&nt.unlink(Dt.join(e,o)).catch(()=>{})}).catch(()=>{})}}function ei(){return Dt.join(process.cwd(),".nex","history")}async function Ld(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=Lw)return{inline:!0,content:t};let n=Pw.createHash("sha256").update(t,"utf-8").digest("hex"),o=Dt.join(e,"blobs");return await nt.mkdir(o,{recursive:!0}),await nt.writeFile(Dt.join(o,n),t,"utf-8"),{inline:!1,hash:n}}async function Dd(t){let e=ei();await nt.mkdir(e,{recursive:!0});let n=Dt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${n}.json`,s=await Ld(t.oldContent,e),r=await Ld(t.newContent,e),i={tool:t.tool,filePath:t.filePath,timestamp:t.timestamp,oldContent:s.inline?{inline:!0,content:s.content}:{inline:!1,hash:s.hash},newContent:r.inline?{inline:!0,content:r.content}:{inline:!1,hash:r.hash}};await nt.writeFile(Dt.join(e,o),JSON.stringify(i),"utf-8")}async function Id(t,e){if(!t)return null;if(t.inline)return t.content;let n=Dt.join(e,"blobs",t.hash);return nt.readFile(n,"utf-8")}async function Ww(){let t=ei(),e;try{e=await nt.readdir(t)}catch{return 0}let n=e.filter(s=>s.endsWith(".json")).sort(),o=0;for(let s of n)try{let r=await nt.readFile(Dt.join(t,s),"utf-8"),i=JSON.parse(r),c=await Id(i.oldContent,t),l=await Id(i.newContent,t);bt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:c,newContent:l}),o++}catch{}for(;bt.length>jd;)bt.shift();return o}async function Hw(t=7){let e=ei(),n;try{n=await nt.readdir(e)}catch{return 0}let o=Date.now()-t*24*60*60*1e3,s=n.filter(u=>u.endsWith(".json")),r=0,i=new Set,c=[];for(let u of s)try{let d=await nt.readFile(Dt.join(e,u),"utf-8"),f=JSON.parse(d);f.timestamp<o?(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 nt.unlink(Dt.join(e,u))}catch{}let l=Dt.join(e,"blobs");try{let u=await nt.readdir(l);for(let d of u)if(!i.has(d))try{await nt.unlink(Dt.join(l,d))}catch{}}catch{}return r}var Qr="nex-snapshot";function Kw(t,e=process.cwd()){let n=t?`${Qr}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Qr}-${Date.now()}`;try{return bo("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(bo(`git stash push -u -m "${n}"`,{cwd:e,timeout:15e3}),bo("git stash pop",{cwd:e,timeout:1e4}),{name:n,label:n,ok:!0}):{name:n,label:n,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(o){return{name:n,label:n,ok:!1,error:o.message}}}function qd(t=process.cwd()){try{let e=bo("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
|
|
87
|
+
`).map(n=>{let o=n.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!o)return null;let s=o[2].trim();return s.startsWith(Qr)?{index:parseInt(o[1],10),label:s,shortName:s.replace(`${Qr}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function Gw(t,e=process.cwd()){try{let n=qd(e);if(n.length===0)return{ok:!1,error:"No snapshots found"};let o;return t===void 0||t==="last"?o=n[0]:typeof t=="number"?o=n.find(s=>s.index===t):o=n.find(s=>s.label===t||s.shortName===t||s.shortName.includes(String(t))),o?(bo(`git stash apply stash@{${o.index}}`,{cwd:e,timeout:15e3}),{ok:!0,label:o.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(n){return{ok:!1,error:n.message}}}Fd.exports={recordChange:Iw,undo:jw,redo:Dw,getHistory:qw,getUndoCount:Fw,getRedoCount:Uw,clearHistory:Bw,persistEntry:Dd,loadPersistedHistory:Ww,pruneHistory:Hw,createSnapshot:Kw,listSnapshots:qd,restoreSnapshot:Gw}});var Mn=Q((DT,Gd)=>{var Ue=require("fs"),_t=require("path"),{atomicWrite:Yw,withFileLockSync:zw}=An(),ht=[];function _o(){return _t.join(process.cwd(),".nex","skills")}function Ud(){return _t.join(process.cwd(),".nex","config.json")}function Bd(){let t=_o();return Ue.existsSync(t)||Ue.mkdirSync(t,{recursive:!0}),t}function sc(){let t=Ud();if(!Ue.existsSync(t))return[];try{let e=JSON.parse(Ue.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Wd(t){let e=Ud(),n=_t.dirname(e);Ue.existsSync(n)||Ue.mkdirSync(n,{recursive:!0}),zw(e,()=>{let o={};if(Ue.existsSync(e))try{o=JSON.parse(Ue.readFileSync(e,"utf-8"))}catch{o={}}o.skills||(o.skills={}),o.skills.disabled=t,Yw(e,JSON.stringify(o,null,2))})}function Hd(t,e){let n=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&n.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&n.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&n.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))n.push("commands must be an array");else for(let o=0;o<t.commands.length;o++){let s=t.commands[o];(!s.cmd||typeof s.cmd!="string")&&n.push(`commands[${o}].cmd must be a non-empty string`),s.handler!==void 0&&typeof s.handler!="function"&&n.push(`commands[${o}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))n.push("tools must be an array");else for(let o=0;o<t.tools.length;o++){let s=t.tools[o];(!s.function||!s.function.name||typeof s.function.name!="string")&&n.push(`tools[${o}].function.name must be a non-empty string`),s.execute!==void 0&&typeof s.execute!="function"&&n.push(`tools[${o}].execute must be a function`)}return{valid:n.length===0,errors:n}}function Kd(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{triggers:[],body:t};let n=e[1],o=e[2].trim(),s=[],r=!1;for(let i of n.split(`
|
|
88
88
|
`)){let c=i.trim();if(/^trigger:\s*$/i.test(c)){r=!0;continue}r&&c.startsWith("- ")?s.push(c.slice(2).trim().replace(/^["']|["']$/g,"")):r&&c&&!c.startsWith("#")&&(r=!1)}return{triggers:s,body:o}}function tc(t){try{let e=Ue.readFileSync(t,"utf-8").trim();if(!e)return null;let n=_t.basename(t,".md"),{triggers:o,body:s}=Kd(e);return{name:n,type:"prompt",filePath:t,instructions:s||e,triggers:o,commands:[],tools:[]}}catch{return null}}function nc(t){try{let e=require(t),{valid:n,errors:o}=Hd(e,t);return n?{name:e.name||_t.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
|
${o.join(`
|
|
90
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function oc(){ht=[];let t=sc(),e=_o(),n=[];if(Ue.existsSync(e))try{n=Ue.readdirSync(e)}catch{n=[]}for(let s of n){let r=_t.join(e,s),i;try{i=Ue.statSync(r)}catch{continue}if(!i.isFile())continue;let c=null;s.endsWith(".md")?c=tc(r):s.endsWith(".js")&&(c=nc(r)),c&&(c.enabled=!t.includes(c.name),ht.push(c))}let o=_t.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Ue.existsSync(o)){let s;try{s=Ue.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{s=[]}for(let r of s){let i=_t.join(o,r),c=_t.basename(r,_t.extname(r));if(ht.some(d=>d.name===c))continue;let l;try{l=Ue.statSync(i)}catch{continue}if(!l.isFile())continue;let u=r.endsWith(".md")?tc(i):nc(i);u&&(u._builtin=!0,u.enabled=!t.includes(u.name),ht.push(u))}}return ht}function
|
|
90
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function oc(){ht=[];let t=sc(),e=_o(),n=[];if(Ue.existsSync(e))try{n=Ue.readdirSync(e)}catch{n=[]}for(let s of n){let r=_t.join(e,s),i;try{i=Ue.statSync(r)}catch{continue}if(!i.isFile())continue;let c=null;s.endsWith(".md")?c=tc(r):s.endsWith(".js")&&(c=nc(r)),c&&(c.enabled=!t.includes(c.name),ht.push(c))}let o=_t.join(__dirname,"skills");if(!process.env.NEX_SKIP_BUILTIN_SKILLS&&Ue.existsSync(o)){let s;try{s=Ue.readdirSync(o).filter(r=>r.endsWith(".md")||r.endsWith(".js"))}catch{s=[]}for(let r of s){let i=_t.join(o,r),c=_t.basename(r,_t.extname(r));if(ht.some(d=>d.name===c))continue;let l;try{l=Ue.statSync(i)}catch{continue}if(!l.isFile())continue;let u=r.endsWith(".md")?tc(i):nc(i);u&&(u._builtin=!0,u.enabled=!t.includes(u.name),ht.push(u))}}return ht}function Xw(){let t=[];for(let e of ht)!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 Jw(){let t=[];for(let e of ht)if(e.enabled)for(let n of e.commands)t.push({cmd:n.cmd,desc:n.desc||`[skill: ${e.name}]`});return t}function Vw(){let t=[];for(let e of ht)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 Zw(t,e){if(!t.startsWith("skill_"))return null;let n=t.substring(6);for(let o of ht)if(o.enabled){for(let s of o.tools)if(s.function.name===n&&s.execute)try{let r=await s.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${n}' failed: ${r.message}`}}return`ERROR: Skill tool '${n}' not found`}function Qw(t){let[e,...n]=t.split(/\s+/),o=n.join(" ").trim();for(let s of ht)if(s.enabled){for(let r of s.commands)if(r.cmd===e&&r.handler){try{let i=r.handler(o);if(typeof i=="string"&&i.length>0)return{handled:!0,agentPrompt:i}}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return{handled:!0}}}return!1}function e0(){return ht.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 t0(t){let e=ht.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let n=sc().filter(o=>o!==t);return Wd(n),!0}function n0(t){let e=ht.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let n=sc();return n.includes(t)||(n.push(t),Wd(n)),!0}function s0(){return ht}async function o0(t,e={}){let{execSync:n}=require("child_process"),o=Bd(),s=t;/^[\w-]+\/[\w.-]+$/.test(t)&&(s=`https://github.com/${t}.git`);let r=e.name||_t.basename(s,".git").replace(/^nex-skill-/,""),i=_t.join(o,r);if(Ue.existsSync(i))return{ok:!1,name:r,error:`Skill "${r}" is already installed at ${i}. Remove it first to reinstall.`};try{if(!/^https?:\/\/[a-zA-Z0-9._\-/:@#?=&%+~]+$/.test(s))throw new Error(`Invalid git URL: ${s}`);let d=i.replace(/'/g,"'\\''");n(`git clone --depth 1 '${s}' '${d}'`,{timeout:3e4,stdio:"pipe"})}catch(d){return{ok:!1,name:r,error:`Git clone failed: ${d.stderr?.toString().trim()||d.message}`}}let c=_t.join(i,"skill.json"),l=Ue.existsSync(c),u=Ue.readdirSync(i).some(d=>(d.endsWith(".md")||d.endsWith(".js"))&&!d.startsWith("."));if(!l&&!u){try{Ue.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(Ue.readFileSync(c,"utf-8"));d.name||(d.name=r)}catch{try{Ue.rmSync(i,{recursive:!0,force:!0})}catch{}return{ok:!1,name:r,error:"Invalid skill.json \u2014 not valid JSON"}}return oc(),{ok:!0,name:r}}async function r0(t){let e=require("axios");try{let n=encodeURIComponent(`nex-skill ${t} OR nex-code-skill ${t}`);return((await e.get(`https://api.github.com/search/repositories?q=${n}&sort=stars&per_page=10`,{timeout:1e4,headers:{Accept:"application/vnd.github.v3+json"}})).data.items||[]).map(s=>({name:s.name.replace(/^nex-skill-/,""),description:s.description||"(no description)",url:s.clone_url,stars:s.stargazers_count,owner:s.owner.login}))}catch(n){return[{name:"error",description:`Search failed: ${n.message}`,url:"",stars:0,owner:""}]}}function i0(t){let e=_t.join(_o(),t);if(!Ue.existsSync(e))return{ok:!1,error:`Skill "${t}" not found in ${_o()}`};try{return Ue.rmSync(e,{recursive:!0,force:!0}),oc(),{ok:!0}}catch(n){return{ok:!1,error:n.message}}}function a0(t){if(!t)return[];let e=t.toLowerCase(),n=[];for(let o of ht){if(!o.enabled||!o.triggers||o.triggers.length===0)continue;if(o.triggers.some(r=>e.includes(r.toLowerCase()))){let r=(o.instructions||"").split(`
|
|
95
95
|
`).slice(0,3).join(`
|
|
96
|
-
`);n.push({name:o.name,instructions:r})}}return n}Gd.exports={initSkillsDir:Bd,loadAllSkills:oc,getSkillInstructions:
|
|
96
|
+
`);n.push({name:o.name,instructions:r})}}return n}Gd.exports={initSkillsDir:Bd,loadAllSkills:oc,getSkillInstructions:Xw,getSkillCommands:Jw,getSkillToolDefinitions:Vw,routeSkillCall:Zw,handleSkillCommand:Qw,listSkills:e0,enableSkill:t0,disableSkill:n0,getLoadedSkills:s0,installSkill:o0,searchSkills:r0,removeSkill:i0,matchSkillTriggers:a0,_getSkillsDir:_o,_validateScriptSkill:Hd,_loadMarkdownSkill:tc,_loadScriptSkill:nc,_parseFrontmatter:Kd}});var ni=Q((qT,Zd)=>{var{spawn:c0}=require("child_process"),l0=require("path"),Yd=require("fs"),wn=new Map;function u0(){return l0.join(process.cwd(),".nex","config.json")}function rc(){let t=u0();if(!Yd.existsSync(t))return{};try{return JSON.parse(Yd.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function ti(t,e,n={},o=1e4){return new Promise((s,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}`))},o);function d(p){l+=p.toString();let h=l.split(`
|
|
98
|
-
`);for(let m of h)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):s(g.result);return}}catch{}l=h[h.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 zd(t,e){if(wn.has(t))return wn.get(t);let n=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],o={};for(let i of n)process.env[i]&&(o[i]=process.env[i]);let s=
|
|
99
|
-
`):JSON.stringify(s)}function Vd(){let t=[];for(let[e,n]of wn)for(let o of n.tools)t.push({server:e,name:o.name,description:o.description||"",inputSchema:o.inputSchema||{type:"object",properties:{}}});return t}function
|
|
98
|
+
`);for(let m of h)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):s(g.result);return}}catch{}l=h[h.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 zd(t,e){if(wn.has(t))return wn.get(t);let n=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],o={};for(let i of n)process.env[i]&&(o[i]=process.env[i]);let s=c0(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:s,tools:[],config:e};try{await ti(s,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await ti(s,"tools/list",{});return r.tools=i&&i.tools||[],wn.set(t,r),r}catch(i){throw s.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Xd(t){let e=wn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return wn.delete(t),!0}function d0(){for(let[t]of wn)Xd(t)}async function Jd(t,e,n={}){let o=wn.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await ti(o.proc,"tools/call",{name:e,arguments:n});return s&&Array.isArray(s.content)?s.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
99
|
+
`):JSON.stringify(s)}function Vd(){let t=[];for(let[e,n]of wn)for(let o of n.tools)t.push({server:e,name:o.name,description:o.description||"",inputSchema:o.inputSchema||{type:"object",properties:{}}});return t}function f0(){return Vd().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function p0(t,e){if(!t.startsWith("mcp_"))return null;let n=t.substring(4).split("_");if(n.length<2)return null;let o=n[0],s=n.slice(1).join("_");return Jd(o,s,e)}function m0(){let t=rc();return Object.entries(t).map(([e,n])=>{let o=wn.get(e);return{name:e,command:n.command,connected:!!o,toolCount:o?o.tools.length:0}})}async function h0(){let t=rc(),e=[];for(let[n,o]of Object.entries(t))try{let s=await zd(n,o);e.push({name:n,tools:s.tools.length})}catch(s){e.push({name:n,tools:0,error:s.message})}return e}Zd.exports={loadMCPConfig:rc,sendRequest:ti,connectServer:zd,disconnectServer:Xd,disconnectAll:d0,callTool:Jd,getAllTools:Vd,getMCPToolDefinitions:f0,routeMCPCall:p0,listServers:m0,connectAll:h0}});var oi=Q((FT,nf)=>{var Qd=require("fs"),ic=require("path"),si=[],xo=[],es={},vo=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function ef(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 xo.some(o=>o.definition.function.name===n)?{ok:!1,error:`Tool "${n}" is already registered`}:(xo.push({definition:{type:"function",...t},handler:e}),{ok:!0})}function tf(t,e){return vo.includes(t)?typeof e!="function"?{ok:!1,error:"Handler must be a function"}:(es[t]||(es[t]=[]),es[t].push(e),{ok:!0}):{ok:!1,error:`Unknown event "${t}". Available: ${vo.join(", ")}`}}async function ac(t,e){let n=es[t]||[],o=e;for(let s of n)try{let r=await s(o);r!==void 0&&(o=r)}catch(r){process.env.NEX_DEBUG&&console.error(`[plugin] Hook error on ${t}: ${r.message}`)}return o}function g0(){let t=ic.join(process.cwd(),".nex","plugins"),e=[];if(!Qd.existsSync(t))return{loaded:0,errors:[]};let n=Qd.readdirSync(t).filter(s=>s.endsWith(".js")),o={registerTool:ef,registerHook:tf,EVENTS:vo};for(let s of n){let r=ic.join(t,s);try{let i=require(r);if(typeof i=="function")i(o);else if(typeof i.setup=="function")i.setup(o);else{e.push(`${s}: Plugin must export a function or { setup: function }`);continue}si.push({name:i.name||ic.basename(s,".js"),filePath:r})}catch(i){e.push(`${s}: ${i.message}`)}}return{loaded:si.length,errors:e}}function $0(){return xo.map(t=>t.definition)}async function y0(t,e,n={}){let o=xo.find(c=>c.definition.function.name===t);if(!o)return null;let s=await ac("beforeToolExec",{name:t,args:e,options:n}),r=await o.handler(s.args||e,n);return(await ac("afterToolExec",{name:t,args:e,result:r})).result||r}function w0(){return[...si]}function b0(){let t={};for(let e of vo)t[e]=(es[e]||[]).length;return t}function _0(){si.length=0,xo.length=0;for(let t of Object.keys(es))delete es[t]}nf.exports={registerTool:ef,registerHook:tf,emit:ac,loadPlugins:g0,getPluginToolDefinitions:$0,executePluginTool:y0,getLoadedPlugins:w0,getHookCounts:b0,clearPlugins:_0,EVENTS:vo}});var cc=Q((UT,af)=>{var{getSkillToolDefinitions:x0}=Mn(),{getMCPToolDefinitions:v0}=ni(),{getPluginToolDefinitions:k0}=oi(),ri=new Map;function sf(){let{TOOL_DEFINITIONS:t}=Gt();return[...t,...x0(),...v0(),...k0()]}function of(t){if(ri.has(t))return ri.get(t);let n=sf().find(s=>s.function.name===t);if(!n)return null;let o=n.function.parameters;return ri.set(t,o),o}function S0(){ri.clear()}function ii(t,e){if(!t||e.length===0)return null;let n=null,o=1/0;for(let s of e){let r=rf(t.toLowerCase(),s.toLowerCase());r<o&&(o=r,n=s)}return o<=Math.ceil(t.length/2)?n:null}function rf(t,e){let n=t.length,o=e.length,s=Array.from({length:n+1},()=>Array(o+1).fill(0));for(let r=0;r<=n;r++)s[r][0]=r;for(let r=0;r<=o;r++)s[0][r]=r;for(let r=1;r<=n;r++)for(let i=1;i<=o;i++)s[r][i]=t[r-1]===e[i-1]?s[r-1][i-1]:1+Math.min(s[r-1][i],s[r][i-1],s[r-1][i-1]);return s[n][o]}function E0(t,e){let n=of(t);if(n===null){let f=sf().map(h=>h.function.name),p=ii(t,f);return{valid:!1,error:`Unknown tool "${t}".${p?` Did you mean "${p}"?`:""}
|
|
100
100
|
Available tools: ${f.join(", ")}`}}if(!n||!n.properties)return{valid:!0};let o=n.required||[],s=Object.keys(n.properties),r=Object.keys(e),i=[],c={...e},l=!1;for(let d of o)if(!(d in e)||e[d]===void 0||e[d]===null){let f=ii(d,r);f&&!s.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)&&!s.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(!s.includes(d)){let f=ii(d,s);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 T0(t,e){let n=[],o={...t};if(!o.function&&!o.name)return n.push('Tool call missing both "function" and "name" fields'),{valid:!1,normalized:o,errors:n};if(!o.function&&o.name&&(o.function={name:o.name,arguments:o.arguments||o.args||{}},delete o.name,delete o.args),o.function&&o.function.args!==void 0&&o.function.arguments===void 0&&(o.function.arguments=o.function.args,delete o.function.args),o.function&&(o.function.arguments===void 0||o.function.arguments===null)&&(o.function.arguments={}),o.function&&typeof o.function.arguments=="string"){let s=o.function.arguments;if(s.trim()==="")o.function.arguments={};else try{o.function.arguments=JSON.parse(s)}catch(r){return n.push(`Invalid JSON in arguments${e?` (${e})`:""}: ${r.message}`),{valid:!1,normalized:o,errors:n}}}return o.function&&typeof o.function.arguments!="object"?(n.push(`Arguments must be an object, got ${typeof o.function.arguments}`),{valid:!1,normalized:o,errors:n}):!o.function.name||typeof o.function.name!="string"?(n.push("Tool call function name must be a non-empty string"),{valid:!1,normalized:o,errors:n}):{valid:n.length===0,normalized:o,errors:n}}af.exports={validateToolArgs:E0,validateToolCallFormat:T0,closestMatch:ii,levenshtein:rf,getCachedSchema:of,clearSchemaCache:S0}});var df=Q((BT,uf)=>{var{levenshtein:ai}=cc(),R0=200,C0=.3,A0=2;function lc(t){return t.replace(/\r\n/g,`
|
|
105
105
|
`).replace(/\r/g,`
|
|
106
|
-
`).replace(/\t/g," ".repeat(
|
|
106
|
+
`).replace(/\t/g," ".repeat(A0)).split(`
|
|
107
107
|
`).map(e=>{let n=e.replace(/\s+$/,""),o=n.match(/^(\s*)(.*)/);if(!o)return n;let[,s,r]=o;return s+r.replace(/ {2,}/g," ")}).join(`
|
|
108
|
-
`)}function
|
|
108
|
+
`)}function O0(t,e){if(t.includes(e))return e;if(e.length<10)return null;let n=lc(t),o=lc(e);if(!n.includes(o))return null;let s=t.split(`
|
|
109
109
|
`),r=n.split(`
|
|
110
110
|
`),i=o.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 s.slice(u,u+i.length).join(`
|
|
112
|
-
`)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(o)!==-1)return s[u]}return null}function
|
|
112
|
+
`)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(o)!==-1)return s[u]}return null}function N0(t,e){if(!t||!e)return null;let n=t.split(`
|
|
113
113
|
`),s=e.split(`
|
|
114
|
-
`).length;return n.length===0||s===0?null:s===1?
|
|
115
|
-
`),u=ai(l,e);u<i&&(i=u,r={text:l,distance:u,line:c+1})}return r&&s>1&&(r=
|
|
116
|
-
`),h=ai(p,e);h<u&&(u=h,d={text:p,distance:h,line:f+1})}return d}uf.exports={normalizeWhitespace:lc,fuzzyFindText:
|
|
117
|
-
`),o=[],s=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),dc=Date.now(),ci=!1;return}catch{}let e=[],n=async(o,s)=>{let r;try{r=await Bs.readdir(o,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let c=s?`${s}/${i.name}`:i.name;i.isDirectory()?await n(Ws.join(o,i.name),c):e.push(c)}};await n(t,""),Hs=e,dc=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{ci=!1}}}function fc(){return Hs}function
|
|
119
|
-
`);for(let s=0;s<o.length;s++){let r=o[s],i=s+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let 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(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of p)/^\w+$/.test(h)&&n.push({type:"export",name:h,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 yf(t){t=t||process.cwd();let e=Ws.join(t,".nex","index","content-index.json"),n={};if(uc&&Date.now()-mf<
|
|
114
|
+
`).length;return n.length===0||s===0?null:s===1?M0(n,e):L0(n,e,s)}function cf(t){return Math.max(1,Math.floor(t/R0))}function lf(t,e){return t<=Math.ceil(e*C0)}function M0(t,e){let n=e.trim(),o=cf(t.length),s=null,r=1/0;for(let i=0;i<t.length;i+=o){let c=t[i];if(!c.trim())continue;let l=ai(c.trim(),n);l<r&&(r=l,s={text:c,distance:l,line:i+1})}return s&&o>1&&(s=P0(t,n,s,o)||s,r=s.distance),lf(r,e.length)?s:null}function P0(t,e,n,o){let s=n.line-1,r=Math.max(0,s-o),i=Math.min(t.length-1,s+o),c=n.distance,l=null;for(let u=r;u<=i;u++){let d=t[u];if(!d.trim())continue;let f=ai(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function L0(t,e,n){let o=t.length-n+1;if(o<=0)return null;let s=cf(o),r=null,i=1/0;for(let c=0;c<o;c+=s){let l=t.slice(c,c+n).join(`
|
|
115
|
+
`),u=ai(l,e);u<i&&(i=u,r={text:l,distance:u,line:c+1})}return r&&s>1&&(r=I0(t,e,r,s,n,o)||r,i=r.distance),lf(i,e.length)?r:null}function I0(t,e,n,o,s,r){let i=n.line-1,c=Math.max(0,i-o),l=Math.min(r-1,i+o),u=n.distance,d=null;for(let f=c;f<=l;f++){let p=t.slice(f,f+s).join(`
|
|
116
|
+
`),h=ai(p,e);h<u&&(u=h,d={text:p,distance:h,line:f+1})}return d}uf.exports={normalizeWhitespace:lc,fuzzyFindText:O0,findMostSimilar:N0}});var pf=Q((HT,ff)=>{var{C:WT}=Fe(),j0=[{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}],D0=[{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 q0(t,e){let n=e.split(`
|
|
117
|
+
`),o=[],s=t?`.${t.split(".").pop()}`:"";for(let r=0;r<n.length;r++){let i=n[r],c=r+1;for(let l of j0)l.regex.test(i)&&o.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of D0)l.ext&&!l.ext.includes(s)||l.regex.test(i)&&o.push({line:c,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return n.length>500&&o.push({line:0,message:`Large file detected (${n.length} lines). Consider refactoring.`,severity:"info"}),o}function F0(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}ff.exports={runDiagnostics:q0,getMemoryUsage:F0}});var mc=Q((KT,wf)=>{var Bs=require("fs").promises,Ws=require("path"),{exec:U0}=require("util").promisify(require("child_process").exec),Hs=[],pc=null,ci=!1,dc=0,B0=6e4;function hf(t){return!(Hs.length===0||pc!==t||Date.now()-dc>B0)}async function gf(t){if(!ci&&!hf(t)){ci=!0,pc=t;try{try{let{stdout:o}=await U0("rg --files",{cwd:t,timeout:5e3});Hs=o.split(`
|
|
118
|
+
`).filter(Boolean),dc=Date.now(),ci=!1;return}catch{}let e=[],n=async(o,s)=>{let r;try{r=await Bs.readdir(o,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let c=s?`${s}/${i.name}`:i.name;i.isDirectory()?await n(Ws.join(o,i.name),c):e.push(c)}};await n(t,""),Hs=e,dc=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{ci=!1}}}function fc(){return Hs}function W0(){return pc}function H0(t){return Hs.filter(e=>Ws.basename(e)===t)}function K0(t){let e=t.toLowerCase();return Hs.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}var uc=null,mf=0,G0=12e4,Y0=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function $f(t,e){let n=[],o=t.split(`
|
|
119
|
+
`);for(let s=0;s<o.length;s++){let r=o[s],i=s+1;if([".js",".ts",".jsx",".tsx",".mjs",".cjs"].includes(e)){let 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(h=>h.trim().split(":")[0].trim()).filter(Boolean);for(let h of p)/^\w+$/.test(h)&&n.push({type:"export",name:h,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 yf(t){t=t||process.cwd();let e=Ws.join(t,".nex","index","content-index.json"),n={};if(uc&&Date.now()-mf<G0)return uc;try{let i=await Bs.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}fc().length===0&&await gf(t);let s={files:{}},r=!1;for(let i of fc()){let c=Ws.extname(i);if(!Y0.has(c))continue;let l=Ws.join(t,i);try{let d=(await Bs.stat(l)).mtimeMs;if(n.files[i]&&n.files[i].mtime===d){s.files[i]=n.files[i];continue}let f=await Bs.readFile(l,"utf-8"),p=$f(f,c);s.files[i]={defs:p,mtime:d},r=!0}catch{}}if(r){let i=Ws.join(t,".nex","index");await Bs.mkdir(i,{recursive:!0}),await Bs.writeFile(e,JSON.stringify(s),"utf-8")}return uc=s,mf=Date.now(),s}async function z0(t,e){let n=await yf(),o=[],s=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(s)&&o.push({file:r,type:c.type,name:c.name,line:c.line});return o.sort((r,i)=>{let c=r.name.toLowerCase()===s?0:1,l=i.name.toLowerCase()===s?0:1;if(c!==l)return c-l;let u=r.name.toLowerCase().startsWith(s)?0:1,d=i.name.toLowerCase().startsWith(s)?0:1;return u-d}),o.slice(0,50)}wf.exports={refreshIndex:gf,getFileIndex:fc,getIndexedCwd:W0,findFileInIndex:H0,searchIndex:K0,isIndexValid:hf,buildContentIndex:yf,searchContentIndex:z0,extractDefinitions:$f}});var Ks=Q((GT,vf)=>{var li=require("fs"),di=require("path"),fi=require("os"),{execFile:X0}=require("child_process"),{promisify:J0}=require("util"),hc=J0(X0),V0=di.join(fi.homedir(),".nex","servers.json"),ui=di.join(fi.tmpdir(),"nex-ssh-sockets");function Z0(){return di.join(process.cwd(),".nex","servers.json")}function bf(){let t=o=>{if(!li.existsSync(o))return{};try{return JSON.parse(li.readFileSync(o,"utf-8"))}catch{return{}}},e=t(V0),n=t(Z0());return{...e,...n}}function Q0(t){let e=bf();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[s,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:s}}let n=Object.keys(e),o=n.length?`Available profiles: ${n.join(", ")}`:"No profiles configured. Create .nex/servers.json (project) or ~/.nex/servers.json (global)";throw new Error(`Unknown server: "${t}". ${o}`)}function eb(){li.existsSync(ui)||li.mkdirSync(ui,{recursive:!0})}function _f(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,fi.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),eb();let n=t.user?`${t.user}@${t.host}`:t.host,o=di.join(ui,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function xf(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,fi.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function tb(t,e,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=_f(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:c}=await hc("ssh",[...s,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:pi(l,t)}}}async function nb(t,e,n,{timeout:o=12e4}={}){let s=xf(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(e,`${r}:${n}`);try{let{stdout:i,stderr:c}=await hc("scp",s,{timeout:o,maxBuffer:1048576});return i||c||`Uploaded ${e} \u2192 ${r}:${n}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(pi(c,t)||c)}}async function sb(t,e,n,{timeout:o=12e4}={}){let s=xf(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(`${r}:${e}`,n);try{let{stdout:i,stderr:c}=await hc("scp",s,{timeout:o,maxBuffer:1048576});return i||c||`Downloaded ${r}:${e} \u2192 ${n}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(pi(c,t)||c)}}function pi(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")}Sf.exports={loadDeployConfigs:kf,resolveDeployConfig:
|
|
125
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function ob(t,e){let n=e.user?`${e.user}@${e.host}`:e.host,o=e.port&&Number(e.port)!==22?`:${e.port}`:"",s=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${n}${o}${s}${r}${i}`}vf.exports={loadServerProfiles:bf,resolveProfile:Q0,buildSSHArgs:_f,sshExec:tb,scpUpload:nb,scpDownload:sb,enrichSSHError:pi,formatProfile:ob,SSH_SOCKET_DIR:ui}});var yc=Q((YT,Sf)=>{var ko=require("fs"),gc=require("path"),rb=gc.join(".nex","deploy.json");function $c(){return gc.join(process.cwd(),rb)}function kf(){let t=$c();if(!ko.existsSync(t))return{};try{return JSON.parse(ko.readFileSync(t,"utf-8"))}catch{return{}}}function ib(t){let e=kf();if(e[t])return{...e[t],_name:t};let n=Object.keys(e),o=n.length?`Available: ${n.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${o}`)}function ab(t){let e=gc.join(process.cwd(),".nex");ko.existsSync(e)||ko.mkdirSync(e,{recursive:!0}),ko.writeFileSync($c(),JSON.stringify(t,null,2)+`
|
|
126
|
+
`,"utf-8")}Sf.exports={loadDeployConfigs:kf,resolveDeployConfig:ib,saveDeployConfigs:ab,getDeployConfigPath:$c}});var Ro=Q((zT,Rf)=>{var{getActiveModel:cb,getActiveProviderName:lb}=je(),So={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},Eo={"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"},To={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},ln={};function Tf(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(ln=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{ln={}}}Tf();function wc(){let e=cb()?.id,n=lb();return e&&ln[e]?ln[e]:n&&ln[`${n}:*`]?ln[`${n}:*`]:e&&Eo[e]?Eo[e]:n&&To[n]?To[n]:"full"}var ub=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"]),Ef={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function db(t,e){return t&&(ub.has(t)||t.startsWith("claude-"))?"strict":e&&Ef[e]?Ef[e]:"fuzzy"}function fb(t,e){return t&&ln[t]?ln[t]:e&&ln[`${e}:*`]?ln[`${e}:*`]:t&&Eo[t]?Eo[t]:e&&To[e]?To[e]:"full"}function pb(t,e){let n=e||wc();if(n==="full"||!So[n])return t;let o=new Set(So[n]);return t.filter(s=>o.has(s.function.name))}function mb(){let t=wc(),e=So[t]?So[t].length:"all";return{tier:t,toolCount:e}}Rf.exports={filterToolsForModel:pb,getActiveTier:wc,getModelTier:fb,getEditMode:db,getTierInfo:mb,TIERS:So,MODEL_TIERS:Eo,PROVIDER_DEFAULT_TIER:To,loadConfigOverrides:Tf}});var Ao=Q((XT,Of)=>{var bc=null,bn=null,Co=null,Cf=`Playwright is not installed. Install with:
|
|
127
127
|
npm install playwright && npx playwright install chromium
|
|
128
|
-
Then restart nex-code.`;function Af(){if(Co!==null)return Co;try{require("playwright"),Co=!0}catch{Co=!1}return Co}async function mi(){if(!Af())throw new Error(Cf);return bc||(bc=require("playwright")),(!bn||!bn.isConnected())&&(bn=await bc.chromium.launch({headless:!0})),bn}async function
|
|
129
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await s.close()}}async function
|
|
130
|
-
`)}function
|
|
128
|
+
Then restart nex-code.`;function Af(){if(Co!==null)return Co;try{require("playwright"),Co=!0}catch{Co=!1}return Co}async function mi(){if(!Af())throw new Error(Cf);return bc||(bc=require("playwright")),(!bn||!bn.isConnected())&&(bn=await bc.chromium.launch({headless:!0})),bn}async function hb(){if(bn){try{await bn.close()}catch{}bn=null}}process.on("exit",()=>{if(bn)try{bn.close()}catch{}});async function gb(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let s=await(await mi()).newPage();try{await s.goto(t,{waitUntil:n,timeout:e});let r=await s.title(),i=await s.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),c=await s.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:s.url(),text:i.substring(0,8e3)+(i.length>8e3?`
|
|
129
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await s.close()}}async function $b(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await mi()).newPage();try{await i.setViewportSize({width:e,height:n}),await i.goto(t,{waitUntil:"networkidle",timeout:s});let c=await i.screenshot({type:"png",fullPage:o}),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 yb(t,{selector:e,text:n,timeout:o=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await mi()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:o}),n?await r.getByText(n,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function wb(t,{selector:e,value:n,submit:o=!1,timeout:s=3e4}={}){if(!e||n===void 0)throw new Error("selector and value are required");let i=await(await mi()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:s}),await i.fill(e,String(n)),o&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${o?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}Of.exports={isPlaywrightAvailable:Af,browserNavigate:gb,browserScreenshot:$b,browserClick:yb,browserFill:wb,closeBrowser:hb,INSTALL_MSG:Cf}});var hi=Q((JT,Nf)=>{var{C:Be}=Fe(),No="",gt=[],Oo=0,ts=null;function bb(t){ts=t}function _b(t,e){No=t,gt=[],Oo=0;for(let o of e){Oo++;let s=`t${Oo}`;gt.push({id:s,description:o.description||o.title||o.name||o.task||`Task ${Oo}`,status:"pending",dependsOn:o.depends_on||[],result:null})}let n=gt.map(o=>({...o}));return ts&&ts("create",{name:t,tasks:n}),n}function xb(t,e,n){let o=gt.find(s=>s.id===t);return o?(o.status=e,n!==void 0&&(o.result=n),ts&&ts("update",{id:t,status:e,result:n}),{...o}):null}function vb(){return{name:No,tasks:gt.map(t=>({...t}))}}function kb(){No="",gt=[],Oo=0,ts&&ts("clear",{})}function Sb(){return gt.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let n=gt.find(o=>o.id===e);return n&&n.status==="done"}))}function Eb(){if(gt.length===0)return`${Be.dim}No active tasks${Be.reset}`;let t=[];No&&(t.push(` ${Be.bold}${Be.cyan}Tasks: ${No}${Be.reset}`),t.push(` ${Be.dim}${"\u2500".repeat(40)}${Be.reset}`));for(let s of gt){let r,i;switch(s.status){case"done":r="\u2713",i=Be.green;break;case"in_progress":r="\u2192",i=Be.cyan;break;case"failed":r="\u2717",i=Be.red;break;default:r="\xB7",i=Be.dim}let c=s.dependsOn.length>0?` ${Be.dim}(after: ${s.dependsOn.join(", ")})${Be.reset}`:"",l=`[${s.status}]`,u=s.description.length>50?s.description.substring(0,47)+"...":s.description;if(t.push(` ${i}${r}${Be.reset} ${Be.bold}${s.id}${Be.reset} ${u.padEnd(40)} ${i}${l}${Be.reset}${c}`),s.result&&s.status==="done"){let d=s.result.length>60?s.result.substring(0,57)+"...":s.result;t.push(` ${Be.dim}\u2192 ${d}${Be.reset}`)}}let e=gt.filter(s=>s.status==="done").length,n=gt.filter(s=>s.status==="failed").length,o=gt.length;return t.push(` ${Be.dim}${"\u2500".repeat(40)}${Be.reset}`),t.push(` ${Be.dim}${e}/${o} done${n>0?`, ${n} failed`:""}${Be.reset}`),t.join(`
|
|
130
|
+
`)}function Tb(){return gt.length>0&>.some(t=>t.status==="pending"||t.status==="in_progress")}Nf.exports={createTasks:_b,updateTask:xb,getTaskList:vb,clearTasks:kb,getReadyTasks:Sb,renderTaskList:Eb,setOnChange:bb,hasActiveTasks:Tb}});var gi=Q((VT,Pf)=>{var Mo={"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,31 +140,31 @@ 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.`}},Mf={staleWarn:6e4,staleAbort:12e4,investigationCap:12,postEditCap:10};function
|
|
143
|
+
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},Mf={staleWarn:6e4,staleAbort:12e4,investigationCap:12,postEditCap:10};function Rb(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let r of Object.keys(Mo))e.startsWith(r)&&r.length>o&&(n=r,o=r.length);let s=n?{...Mo[n]}:{...Mf};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&&(s[i]=c)}return s}function Cb(t){let e=(t||"").toLowerCase(),n=null,o=0;for(let s of Object.keys(Mo))e.startsWith(s)&&s.length>o&&(n=s,o=s.length);return n&&Mo[n].briefing||""}Pf.exports={getModelProfile:Rb,getModelBriefing:Cb,PROFILES:Mo,DEFAULTS:Mf}});var Ff=Q((ZT,qf)=>{var{callChat:Ab}=je(),{estimateTokens:_c}=Ct(),Lf=process.env.NEX_COMPACTION!=="false",If=6,jf=500,Ob=`Summarize this conversation history concisely. Focus on:
|
|
144
144
|
- What files were read, created, or modified
|
|
145
145
|
- Key decisions made and their rationale
|
|
146
146
|
- Current state of the task (what's done, what's pending)
|
|
147
147
|
- Any errors encountered and how they were resolved
|
|
148
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
148
|
+
Be factual and brief. Use bullet points. Max 300 words.`;async function Nb(t){if(!Lf||t.length<If)return null;let e=[{role:"system",content:Ob},{role:"user",content:Df(t)}];try{let o=((await Ab(e,[],{temperature:0,maxTokens:jf})).content||"").trim();if(!o)return null;let s=t.reduce((i,c)=>i+_c(c.content||"")+(c.tool_calls?_c(JSON.stringify(c.tool_calls)):0),0),r=_c(o);return r>=s*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
149
149
|
${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:s-r}}catch{return null}}function Df(t){return t.map(e=>{let n=e.role==="tool"?"tool_result":e.role,o=(e.content||"").substring(0,500);if(e.tool_calls){let s=e.tool_calls.map(r=>r.function?.name).join(", ");return`[${n}] ${o}
|
|
150
150
|
tools: ${s}`}return`[${n}] ${o}`}).join(`
|
|
151
151
|
|
|
152
|
-
`)}qf.exports={compactMessages:
|
|
152
|
+
`)}qf.exports={compactMessages:Nb,formatMessagesForSummary:Df,COMPACTION_ENABLED:Lf,COMPACTION_MIN_MESSAGES:If,COMPACTION_SUMMARY_BUDGET:jf}});var Ct=Q((QT,Jf)=>{var Mb=require("path");function Bf(){return je().getActiveModel()}var Pb={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},Lb={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},ns=new Map,Uf=1e3,xc=new WeakMap,ss=null;function Ib(){if(ss!==null)return ss;try{let t=Bf(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[o,s]of Object.entries(Lb))if(n.startsWith(o))return ss=s,ss;return ss=Pb[e]||4,ss}catch{return 4}}function jb(){ss=null}function os(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=ns.get(e);if(n!==void 0)return ns.delete(e),ns.set(e,n),n;let o=Math.ceil(t.length/Ib());if(ns.size>=Uf){let s=Uf>>1,r=ns.keys();for(let i=0;i<s;i++)ns.delete(r.next().value)}return ns.set(e,o),o}function Db(t){if(xc.has(t))return xc.get(t);let e=JSON.stringify(t);return xc.set(t,e),e}function zs(t){let n=4;if(t.content&&(n+=os(t.content)),t.tool_calls)for(let o of t.tool_calls){n+=4,n+=os(o.function?.name||"");let s=o.function?.arguments;typeof s=="string"?n+=os(s):s&&(n+=os(JSON.stringify(s)))}return n}function qt(t){let e=0;for(let n of t)e+=zs(n);return e}function qb(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let n=t?t.length:0,o=e.length,s=0;for(let r=n;r<o;r++)s+=zs(e[r]);return s}function $i(t){return!t||t.length===0?0:os(JSON.stringify(t))}function yi(){return Bf()?.contextWindow||32768}function Fb(t,e){let n=qt(t),o=$i(e),s=n+o,r=yi(),i=r>0?s/r*100:0,c=0,l=0,u=0;for(let d of t){let f=zs(d);d.role==="system"?c+=f:d.role==="tool"?u+=f:l+=f}return{used:s,limit:r,percentage:Math.round(i*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:o},messageCount:t.length}}var Po=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,Wf=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,Hf=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Kf={essential:.6,standard:.7,full:Po};function Gf(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Po;try{let{getActiveTier:t}=Ro(),e=t();return Kf[e]??Po}catch{return Po}}var Ub=200,Bb=1e3;function Yf(t,e){if(!t||t.length<=e)return t;let o=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=o)return t;let s=t.split(`
|
|
153
153
|
`);if(s.length<=10){let m=Math.floor(o*.6),g=Math.floor(o*.4),y=t.substring(0,m),w=t.substring(t.length-g);return y+`
|
|
154
154
|
...(${t.length} chars total)...
|
|
155
155
|
`+w}let r=Math.floor(s.length*.4),i=Math.floor(s.length*.4),c=[],l=0,u=Math.floor(o*.4);for(let m=0;m<r&&l<u;m++)if(l+s[m].length+1>u&&s[m].trim().startsWith("```")){c.push(s[m]),l+=s[m].length+1;let g=m+1;for(;g<s.length&&l<u*1.5&&!s[g].trim().startsWith("```");)c.push(s[g]),l+=s[g].length+1,g++;g<s.length&&s[g].trim().startsWith("```")&&(c.push(s[g]),l+=s[g].length+1),m=g}else c.push(s[m]),l+=s[m].length+1;let d=[],f=0,p=Math.floor(o*.4);for(let m=s.length-1;m>=s.length-i&&f<p;m--)if(f+s[m].length+1>p&&s[m].trim().startsWith("```")){d.push(s[m]),f+=s[m].length+1;let g=m-1;for(;g>=0&&f<p*1.5&&!s[g].trim().startsWith("```");)d.push(s[g]),f+=s[g].length+1,g--;g>=0&&s[g].trim().startsWith("```")&&(d.push(s[g]),f+=s[g].length+1),m=g}else d.push(s[m]),f+=s[m].length+1;d.reverse();let h=s.length-c.length-d.length;return c.join(`
|
|
156
156
|
`)+`
|
|
157
157
|
...(${h} lines omitted, ${s.length} total)...
|
|
158
158
|
`+d.join(`
|
|
159
|
-
`)}function Ys(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:
|
|
160
|
-
...(truncated)`),s.tool_calls&&e==="aggressive"&&(s.tool_calls=s.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),s}return t}function zf(t,e,n,o){let s=0;if(t.role==="system")return 100;if(t.role==="user")s+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?s+=30:s+=15}else t.role==="assistant"&&(s+=t.tool_calls?20:10);let r=n>1?e/(n-1):1;if(s+=Math.round(r*30),o&&o.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),c=0;for(let l of o)(i.includes(l)||i.includes(
|
|
159
|
+
`)}function Ys(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:Bb,o=e==="aggressive"?50:e==="medium"?100:Ub;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:Yf(s,o)}:t}if(t.role==="assistant"){let s={...t};return s.content&&s.content.length>n&&(s.content=s.content.substring(0,n)+`
|
|
160
|
+
...(truncated)`),s.tool_calls&&e==="aggressive"&&(s.tool_calls=s.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),s}return t}function zf(t,e,n,o){let s=0;if(t.role==="system")return 100;if(t.role==="user")s+=35;else if(t.role==="tool"){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||"");/^(ERROR|BLOCKED|CANCELLED)/i.test(i)?s+=30:s+=15}else t.role==="assistant"&&(s+=t.tool_calls?20:10);let r=n>1?e/(n-1):1;if(s+=Math.round(r*30),o&&o.size>0){let i=typeof t.content=="string"?t.content:JSON.stringify(t.content||""),c=0;for(let l of o)(i.includes(l)||i.includes(Mb.basename(l)))&&c++;s+=Math.min(30,c*10)}return Math.min(100,s)}function Xf(t,e=10){let n=new Set,o=t.slice(-e),s=/(?:\/[\w.-]+)+\.\w+/g;for(let r of o){let c=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(s);c&&c.forEach(l=>n.add(l))}return n}var Gs={msgCount:-1,lastMsgRef:null,result:null};function Wb(){Gs={msgCount:-1,lastMsgRef:null,result:null}}async function Hb(t,e,n={}){let o=t.length>0?t[t.length-1]:null;if(!n.force&&Gs.result&&t.length===Gs.msgCount&&o===Gs.lastMsgRef)return Gs.result;let s=n.threshold??Gf(),r=n.safetyMargin??Wf,i=n.keepRecent??Hf,c=yi(),l=$i(e),u=Math.floor(c*(s-r)),d=u-l,f=qt(t),p=f+l;if(p<=u){let X={messages:t,compressed:!1,compacted:!1,tokensRemoved:0};return Gs={msgCount:t.length,lastMsgRef:o,result:X},X}let h=f,m=null,g=0;t.length>0&&t[0].role==="system"&&(m=t[0],g=1);let y=Math.max(g,t.length-i),w=t.slice(g,y),v=t.slice(y),M=w.filter(X=>!X._compacted);if(M.length>=6)try{let{compactMessages:X}=Ff(),B=await X(M);if(B){let ye=[...w.filter(me=>me._compacted),B.message],be=Pn(m,ye,v),pe=qt(be);if(pe+l<=u)return{messages:be,compressed:!0,compacted:!0,tokensRemoved:h-pe};w=ye}}catch(X){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",X.message)}let C=(p-u)/u,S=w.map(X=>Ys(X,"light")),O=Pn(m,S,v),D=qt(O);if(D+l<=u)return{messages:O,compressed:!0,compacted:!1,tokensRemoved:h-D};if(S=w.map(X=>Ys(X,"medium")),O=Pn(m,S,v),D=qt(O),D+l<=u)return{messages:O,compressed:!0,compacted:!1,tokensRemoved:h-D};if(S=w.map(X=>Ys(X,"aggressive")),O=Pn(m,S,v),D=qt(O),D+l<=u)return{messages:O,compressed:!0,compacted:!1,tokensRemoved:h-D};let K=Xf([...S,...v]),V=S.map((X,B)=>({msg:X,score:zf(X,B,S.length,K),tokens:zs(X)}));for(;V.length>0&&D>d;){let X=0;for(let B=1;B<V.length;B++)V[B].score<V[X].score&&(X=B);D-=V[X].tokens,V.splice(X,1)}return S=V.map(X=>X.msg),O=Pn(m,S,v),D=qt(O),{messages:O,compressed:!0,compacted:!1,tokensRemoved:h-D}}function Pn(t,e,n){let o=[];return t&&o.push(t),o.push(...e,...n),o}function Kb(t,e){if(!t)return"";if(os(t)<=e)return t;let o=e*4,s=t.split(`
|
|
161
161
|
`),r=Math.floor(o*.6),i=Math.floor(o*.4),c="",l=0;for(let h of s){if(c.length+h.length+1>r)break;c+=(c?`
|
|
162
162
|
`:"")+h,l++}let u="",d=0;for(let h=s.length-1;h>=l;h--){let m=s[h]+(u?`
|
|
163
163
|
`:"")+u;if(m.length>i)break;u=m,d++}let p=`
|
|
164
164
|
|
|
165
165
|
... (${s.length-l-d} lines omitted, ${s.length} total) ...
|
|
166
166
|
|
|
167
|
-
`;return c+p+u}var
|
|
167
|
+
`;return c+p+u}var Gb=6;function Yb(t,e,n=!1){let o=yi(),s=$i(e),r=Math.floor(o*(n?.35:.5))-s,i=qt(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:Gb,f=Math.max(u,t.length-d),p=t.slice(u,f),h=t.slice(f),m=p.map(S=>Ys(S,"aggressive"));n&&(h=h.map(S=>Ys(S,"aggressive")));let g=Pn(l,m,h),y=qt(g);for(;m.length>0&&y>r;){let S=m.shift();y-=zs(S)}n&&y>r&&(h=h.filter(O=>O.role==="user").slice(-1),g=Pn(l,[],h),y=qt(g)),g=Pn(l,m,h);let w=t.filter(S=>S.role==="user"),v=S=>{let O=typeof S.content=="string"?S.content:"";return O.startsWith("[SYSTEM WARNING]")||O.startsWith("[SYSTEM:")||O.startsWith("BLOCKED:")},M=w.find(S=>!v(S)),C=[...w].reverse().find(S=>!v(S));if(M&&!g.find(S=>S===M)){let S=g.findIndex(D=>D.role==="system"),O=S>=0?S+1:0;g.splice(O,0,M)}return C&&C!==M&&!g.find(S=>S===C)&&g.push(C),{messages:g,tokensRemoved:i-qt(g)}}Jf.exports={estimateTokens:os,estimateMessageTokens:zs,estimateMessagesTokens:qt,estimateDeltaTokens:qb,estimateToolsTokens:$i,serializeMessage:Db,getContextWindow:yi,getUsage:Fb,compressMessage:Ys,compressToolResult:Yf,scoreMessageRelevance:zf,extractActiveFiles:Xf,fitToContext:Hb,forceCompress:Yb,truncateFileContent:Kb,invalidateTokenRatioCache:jb,invalidateFitToContextCache:Wb,getEffectiveCompressionThreshold:Gf,COMPRESSION_THRESHOLD:Po,TIER_COMPRESSION_THRESHOLDS:Kf,SAFETY_MARGIN:Wf,KEEP_RECENT:Hf}});var xi=Q((tR,yp)=>{var{callStream:zb,getActiveProviderName:bi,getActiveModelId:Vf,getConfiguredProviders:Xb,getProvider:Zf,getActiveProvider:Qf,parseModelSpec:ep}=je(),{parseToolArgs:tp}=Fs(),{filterToolsForModel:Jb,getModelTier:wi}=Ro(),{getModelBriefing:Vb}=gi(),{trackUsage:np,estimateTokens:sp}=qs(),{MultiProgress:Zb,C:eR}=Fe();function op(t){return!t||typeof t!="string"?0:typeof sp=="function"?sp(t):Math.ceil(t.length/4)}var ap=15,Qb=5,rp=3,cp=8,e_=2,_i=new Map,lp=600*1e3;function t_(t,e){let n=_i.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<lp?!1:(_i.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Lo(t){_i.delete(t)}function vc(){_i.clear()}function kc(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 up(t){let e=kc(t);return e==="rate_limit"||e==="server"||e==="network"||e==="timeout"}async function dp(t,e,n){let o;for(let s=0;s<=rp;s++)try{return await zb(t,e,n)}catch(r){o=r;let i=kc(r);if(i==="auth")throw r.message=`Authentication failed \u2014 check your API key or permissions. (${r.message})`,r;if(i==="context_overflow")throw r.message=`Context window exceeded \u2014 reduce message history or use a model with a larger context. (${r.message})`,r;if(s<rp&&up(r)){let l=i==="rate_limit"?Math.min(2e3*Math.pow(2,s),15e3):Math.min(500*Math.pow(2,s),4e3);await new Promise(u=>setTimeout(u,l).unref());continue}throw r}throw o}var ip=new Set(["ask_user","task_list"]);function fp(t){return t>=2?new Set([...ip,"spawn_agents"]):ip}var n_=new Set(["write_file","edit_file","patch_file"]),pp={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:""}},s_=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,o_=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function mp(t){return o_.test(t)?"full":s_.test(t)?"essential":t.length>300?"full":"standard"}function hp(t){let e=Xb(),n=bi(),o=[...e].sort((s,r)=>(s.name===n?-1:1)-(r.name===n?-1:1));for(let s of o)for(let r of s.models)if(wi(r.id,s.name)===t)return{provider:s.name,model:r.id};return null}var r_={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Sc(t){if(t.model){let{provider:s,model:r}=ep(t.model),i=s?Zf(s):Qf(),c=s||bi();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=wi(r,c);return{provider:c,model:r,tier:l}}}let e=mp(t.task),n=r_[e];if(n){let{provider:s,model:r}=ep(n),i=s?Zf(s):Qf(),c=s||bi();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=wi(r,c);return{provider:c,model:r,tier:l}}}let o=hp(e);if(o){let s=wi(o.model,o.provider);return{provider:o.provider,model:o.model,tier:s}}return{provider:null,model:null,tier:null}}async function gp(t,e={},n=0){let o=n===0?ap:cp,s=Math.min(t.max_iterations||10,o),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.
|
|
168
168
|
|
|
169
169
|
TASK: ${t.task}
|
|
170
170
|
${t.context?`
|
|
@@ -188,23 +188,23 @@ ERROR RECOVERY:
|
|
|
188
188
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
189
189
|
- After 2 failed attempts at the same operation, summarize the issue and stop.`,f=t.type&&pp[t.type],p=f&&f.systemSuffix?`
|
|
190
190
|
|
|
191
|
-
${f.systemSuffix}`:"",h=Sc(t),m=h.provider,g=h.model,y=h.tier,w=
|
|
191
|
+
${f.systemSuffix}`:"",h=Sc(t),m=h.provider,g=h.model,y=h.tier,w=Vb(g||Vf()),M=[{role:"system",content:(w?`## Model Briefing
|
|
192
192
|
${w}
|
|
193
193
|
|
|
194
194
|
---
|
|
195
195
|
|
|
196
|
-
`:"")+d+p}];M.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:C,executeTool:S}=Gt(),O=fp(n),D=
|
|
197
|
-
`)}let K={};m&&(K.provider=m),g&&(K.model=g);try{for(let X=0;X<s;X++){let B=await dp(M,D,K);if(!B||typeof B!="object")throw new Error("Empty or invalid response from provider");{let xe=m||bi(),
|
|
198
|
-
...(truncated)`:E,tool_call_id:Re}}).catch(x=>(k&&(Lo(k),l.delete(k)),{role:"tool",content:`ERROR: ${x.message}`,tool_call_id:Re}))}),
|
|
199
|
-
`)}catch(d){return u.stop(),vc(),`ERROR: Sub-agent execution failed: ${d.message}`}}yp.exports={runSubAgent:gp,executeSpawnAgents:$p,clearAllLocks:vc,classifyTask:mp,pickModelForTier:hp,resolveSubAgentModel:Sc,classifyError:kc,isRetryableError:up,callWithRetry:dp,getExcludedTools:fp,LOCK_TIMEOUT_MS:lp,SUB_AGENT_TYPES:pp}});var Do=Q((
|
|
200
|
-
`);for(let r of s){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=o[2]}return{frontmatter:e,body:n}}function _p(t){let e=_n.join(Js(),`${t}.md`);if(!Ye.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=Ye.readFileSync(e,"utf-8"),{frontmatter:o,body:s}=jo(n);return{name:t,content:n,body:s,frontmatter:o}}function
|
|
201
|
-
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of vi(c))e[l]=(e[l]||0)+3}for(let i of vi(o||t))e[i]=(e[i]||0)+1;return e}function Ac(){let t=ki();if(!Ye.existsSync(t))return{documents:{}};try{return JSON.parse(Ye.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Oc(t){wp(ki(),JSON.stringify(t,null,2))}function
|
|
196
|
+
`:"")+d+p}];M.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:C,executeTool:S}=Gt(),O=fp(n),D=Jb(C.filter(V=>!O.has(V.function.name)),y);if(f&&f.allowedTools&&(D=D.filter(V=>f.allowedTools.has(V.function.name))),g&&!t._skipLog){let V=y?` (${y})`:"";process.stderr.write(` [sub-agent: ${m}:${g}${V}]
|
|
197
|
+
`)}let K={};m&&(K.provider=m),g&&(K.model=g);try{for(let X=0;X<s;X++){let B=await dp(M,D,K);if(!B||typeof B!="object")throw new Error("Empty or invalid response from provider");{let xe=m||bi(),he=g||Vf();if(B.usage){let ge=B.usage.prompt_tokens||0,Re=B.usage.completion_tokens||0;c.input+=ge,c.output+=Re,np(xe,he,ge,Re)}else{let ge=B.content||"",Re=M.map(x=>typeof x.content=="string"?x.content:Array.isArray(x.content)?x.content.map(E=>typeof E=="string"?E:E.text||"").join(""):"").join(" "),k=op(Re),j=op(ge);c.input+=k,c.output+=j,c._estimated=!0,np(xe,he,k,j)}}let R=B.content||"",ye=B.tool_calls,be={role:"assistant",content:R||""};if(ye&&ye.length>0&&(be.tool_calls=ye),M.push(be),!ye||ye.length===0){for(let xe of l)Lo(xe);return{task:t.task,status:"done",result:R||"(no response)",toolsUsed:i,tokensUsed:c,modelSpec:m&&g?`${m}:${g}`:null}}let pe=ye.map(xe=>{let he=xe.function.name,ge=tp(xe.function.arguments),Re=xe.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!ge)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${he}`,tool_call_id:Re});let k=null;if(n_.has(he)&&ge.path){let x=require("path"),E=x.isAbsolute(ge.path)?ge.path:x.resolve(process.cwd(),ge.path);if(t._readOnlyFiles&&t._readOnlyFiles.length>0){let A=x.relative(process.cwd(),E);if(t._readOnlyFiles.some(L=>A===L||A.startsWith(L+"/")||E===L||E.startsWith(L+"/")))return Promise.resolve({role:"tool",content:`ERROR: File '${ge.path}' is owned by another agent and is READ ONLY. Write to your own scope files instead.`,tool_call_id:Re})}if(l.has(E)||!t_(E,r))return Promise.resolve({role:"tool",content:`ERROR: File '${ge.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:Re});l.add(E),k=E}return i.push(he),e.onUpdate&&e.onUpdate({type:"tool_call",tool:he,agentId:r}),(he==="spawn_agents"?$p(ge,n+1):S(he,ge,{autoConfirm:!0,silent:!0})).then(x=>{k&&(Lo(k),l.delete(k));let E=String(x??"");return{role:"tool",content:E.length>2e4?E.substring(0,2e4)+`
|
|
198
|
+
...(truncated)`:E,tool_call_id:Re}}).catch(x=>(k&&(Lo(k),l.delete(k)),{role:"tool",content:`ERROR: ${x.message}`,tool_call_id:Re}))}),me=await Promise.all(pe);if(M.push(...me),X>=7&&M.length>12)try{let{compressMessage:xe}=Ct(),he=M.length-6;for(let ge=1;ge<he;ge++)M[ge]._subAgentCompressed||(M[ge]={...xe(M[ge],"light"),_subAgentCompressed:!0})}catch{}for(let xe=0;xe<ye.length;xe++){let he=ye[xe];if(he.function.name==="bash_exec"){let ge=tp(he.function.arguments);if((me[xe]?.content||"").startsWith("ERROR")&&ge&&ge.command){let k=ge.command.replace(/\s+/g," ").trim().slice(0,100);u.set(k,(u.get(k)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${X+1}/${s}`)}for(let X of l)Lo(X);let V=[...u.entries()].filter(([,X])=>X>=3).sort((X,B)=>B[1]-X[1]).slice(0,3).map(([X,B])=>`"${X}" (failed ${B}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:V,result:M[M.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:c,modelSpec:m&&g?`${m}:${g}`:null}}catch(V){for(let X of l)Lo(X);return{task:t.task,status:"failed",result:`Error: ${V.message}`,toolsUsed:i,tokensUsed:c,modelSpec:m&&g?`${m}:${g}`:null}}}async function $p(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?Qb:e_,o=e===0?ap:cp,s=(t.agents||[]).slice(0,n);if(s.length===0)return"ERROR: No agents specified";let r=e>0?" \u21B3 ":"",i=e>0?38:44,c=s.map(d=>Sc(d)),l=s.map((d,f)=>{let p=c[f],h=p.model?` [${p.model}]`:"",m=d.task.substring(0,i-h.length);return`${r}Agent ${f+1}${h}: ${m}${d.task.length>m.length?"...":""}`}),u=new Zb(l);u.start();try{let d=s.map((g,y)=>{let w=c[y],v=Math.min(g.max_iterations||o,o),M=w.model?{...g,model:`${w.provider}:${w.model}`,_skipLog:!0,max_iterations:v}:{...g,_skipLog:!0,max_iterations:v};return gp(M,{onUpdate:()=>{}},e).then(C=>(u.update(y,C.status==="failed"?"error":"done"),C)).catch(C=>(u.update(y,"error"),{task:g.task,status:"failed",result:`Error: ${C.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),f=await Promise.all(d);u.stop(),vc();let p=["Sub-agent results:",""],h=0,m=0;for(let g=0;g<f.length;g++){let y=f[g],w=y.status==="done"?"\u2713":y.status==="truncated"?"\u26A0":"\u2717",v=y.modelSpec?` [${y.modelSpec}]`:"";p.push(`${w} Agent ${g+1}${v}: ${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(""),h+=y.tokensUsed.input,m+=y.tokensUsed.output}return p.push(`Total sub-agent tokens: ${h} input + ${m} output`),p.join(`
|
|
199
|
+
`)}catch(d){return u.stop(),vc(),`ERROR: Sub-agent execution failed: ${d.message}`}}yp.exports={runSubAgent:gp,executeSpawnAgents:$p,clearAllLocks:vc,classifyTask:mp,pickModelForTier:hp,resolveSubAgentModel:Sc,classifyError:kc,isRetryableError:up,callWithRetry:dp,getExcludedTools:fp,LOCK_TIMEOUT_MS:lp,SUB_AGENT_TYPES:pp}});var Do=Q((nR,Np)=>{var Ye=require("fs"),_n=require("path"),{atomicWrite:wp,withFileLockSync:bp}=An(),i_=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 Js(){let t=_n.join(process.cwd(),".nex","brain");return Ye.existsSync(t)||Ye.mkdirSync(t,{recursive:!0}),t}function ki(){return _n.join(Js(),".brain-index.json")}function Rc(){return _n.join(Js(),".embeddings.json")}function Io(){let t=_n.join(process.cwd(),".nex","brain");if(!Ye.existsSync(t))return[];try{return Ye.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let n=_n.join(t,e),o=Ye.statSync(n);return{name:e.replace(/\.md$/,""),path:n,size:o.size,modified:new Date(o.mtimeMs)}}).sort((e,n)=>n.modified-e.modified)}catch{return[]}}function jo(t){let e={},n=t,o=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(o){let s=o[1].split(`
|
|
200
|
+
`);for(let r of s){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=o[2]}return{frontmatter:e,body:n}}function _p(t){let e=_n.join(Js(),`${t}.md`);if(!Ye.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=Ye.readFileSync(e,"utf-8"),{frontmatter:o,body:s}=jo(n);return{name:t,content:n,body:s,frontmatter:o}}function a_(t,e){let n=_n.join(Js(),`${t}.md`);wp(n,e),u_(t,e),c_()}function c_(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Rc();Ye.existsSync(t)&&setImmediate(async()=>{try{await Rp()}catch{}})}function l_(t){let e=_n.join(Js(),`${t}.md`);return Ye.existsSync(e)?(Ye.unlinkSync(e),d_(t),!0):!1}function vi(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!i_.has(e))}function Cc(t){let e={},{frontmatter:n,body:o}=jo(t),s=Array.isArray(n.tags)?n.tags:[];for(let i of s){let c=i.toLowerCase().replace(/[^a-z0-9-]/g,"");c.length>1&&(e[c]=(e[c]||0)+5)}let r=(o||t).split(`
|
|
201
|
+
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of vi(c))e[l]=(e[l]||0)+3}for(let i of vi(o||t))e[i]=(e[i]||0)+1;return e}function Ac(){let t=ki();if(!Ye.existsSync(t))return{documents:{}};try{return JSON.parse(Ye.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Oc(t){wp(ki(),JSON.stringify(t,null,2))}function u_(t,e){bp(ki(),()=>{let n=Ac(),{frontmatter:o}=jo(e),s=Array.isArray(o.tags)?o.tags:[];n.documents[t]={keywords:Cc(e),tags:s,modified:new Date().toISOString()},Oc(n)})}function d_(t){bp(ki(),()=>{let e=Ac();delete e.documents[t],Oc(e)})}function Tc(){let t=Io(),e={documents:{}};for(let n of t){let o=Ye.readFileSync(n.path,"utf-8"),{frontmatter:s}=jo(o),r=Array.isArray(s.tags)?s.tags:[];e.documents[n.name]={keywords:Cc(o),tags:r,modified:n.modified.toISOString()}}return Oc(e),e}function xp(){let t=Ac(),e=Io();for(let n of e){let o=t.documents[n.name];if(!o||new Date(o.modified)<n.modified)return Tc()}for(let n of Object.keys(t.documents))if(!e.some(o=>o.name===n))return Tc();return t}function vp(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=vi(t);if(s.length===0)return[];let r=xp(),i=[];for(let[c,l]of Object.entries(r.documents)){let u=0;for(let d of s){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>=o&&i.push({name:c,score:u})}return i.sort((c,l)=>l.score-c.score),i.slice(0,n)}var kp=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Ec=400,f_=50;async function Sp(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),n=require("https"),o=new URL(`${t}/api/tags`),s=o.protocol==="https:"?n:e;return((await new Promise((c,l)=>{let u=s.get(o.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(kp.split(":")[0]))}catch{return!1}}async function Nc(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",n=require("http"),o=require("https"),s=new URL(`${e}/api/embeddings`),r=s.protocol==="https:"?o:n,i=JSON.stringify({model:kp,prompt:t});return new Promise((c,l)=>{let u=r.request(s,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},d=>{let f="";d.on("data",p=>f+=p),d.on("end",()=>{try{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 Ep(t,e){if(!t||!e||t.length!==e.length)return 0;let n=0,o=0,s=0;for(let i=0;i<t.length;i++)n+=t[i]*e[i],o+=t[i]*t[i],s+=e[i]*e[i];let r=Math.sqrt(o)*Math.sqrt(s);return r===0?0:n/r}function Tp(t){let e=t.split(/\s+/),n=[],o=0;for(;o<e.length;){let s=e.slice(o,o+Ec).join(" ");if(n.push({text:s,offset:o}),o+Ec>=e.length)break;o+=Ec-f_}return n}async function Rp(){let t=Io(),e={documents:{}},n=Rc();if(Ye.existsSync(n))try{e=JSON.parse(Ye.readFileSync(n,"utf-8"))}catch{}for(let o of t){let s=e.documents[o.name];if(s&&new Date(s.modified)>=o.modified)continue;let r=Ye.readFileSync(o.path,"utf-8"),i=Tp(r),c=[];for(let l of i){let u=await Nc(l.text);c.push({text:l.text,embedding:u,offset:l.offset})}e.documents[o.name]={chunks:c,modified:o.modified.toISOString()}}for(let o of Object.keys(e.documents))t.some(s=>s.name===o)||delete e.documents[o];return Ye.writeFileSync(n,JSON.stringify(e),"utf-8"),e}async function Cp(t,e={}){let{topK:n=3,minSimilarity:o=.3}=e,s=Rc();if(!Ye.existsSync(s))return[];let r;try{r=JSON.parse(Ye.readFileSync(s,"utf-8"))}catch{return[]}let i=await Nc(t),c=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,f="";for(let p of u.chunks||[]){let h=Ep(i,p.embedding);h>d&&(d=h,f=p.text)}d>=o&&c.push({name:l,score:d,bestChunk:f})}return c.sort((l,u)=>u.score-l.score),c.slice(0,n)}function Ap(t,e,n={}){let{k:o=60,topK:s=3}=n,r={};return t.forEach((i,c)=>{r[i.name]=(r[i.name]||0)+1/(o+c+1)}),e.forEach((i,c)=>{r[i.name]=(r[i.name]||0)+1/(o+c+1)}),Object.entries(r).map(([i,c])=>({name:i,score:c})).sort((i,c)=>c.score-i.score).slice(0,s)}async function Op(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=vp(t,{topK:n,minScore:o}),r=s;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await Sp()){let c=await Cp(t,{topK:n});r=Ap(s,c,{topK:n})}}catch{}return r.map(i=>{let c=_p(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 Xs={queryKey:null,result:null,ts:0},p_=3e5;async function m_(t){if(!t||!t.trim())return"";let e=_n.join(process.cwd(),".nex","brain");if(!Ye.existsSync(e)||Io().length===0)return"";let o=t.trim().toLowerCase().slice(0,200);if(Xs.result!==null&&Xs.queryKey===o&&Date.now()-Xs.ts<p_)return Xs.result;let s;try{s=await Op(t,{topK:3})}catch{return""}if(!s||s.length===0)return"";let r;try{r=Ct().estimateTokens}catch{r=d=>Math.ceil(d.length/4)}let i=25e3,c=[],l=0;for(let d of s){let f=d.content||"",p=r(f);if(l+p>i){let m=i-l;if(m<100)break;let g=m/p;f=f.slice(0,Math.floor(f.length*g))+`
|
|
202
202
|
...(truncated)`}let h=typeof d.score=="number"?d.score.toFixed(2):String(d.score);if(c.push(`--- ${d.name} (relevance: ${h}) ---
|
|
203
203
|
${f}`),l+=r(f),l>=i)break}if(c.length===0)return Xs={queryKey:o,result:"",ts:Date.now()},"";let u=`KNOWLEDGE BASE (auto-selected):
|
|
204
204
|
|
|
205
205
|
${c.join(`
|
|
206
206
|
|
|
207
|
-
`)}`;return Xs={queryKey:o,result:u,ts:Date.now()},u}Np.exports={getBrainDir:Js,listDocuments:Io,readDocument:_p,writeDocument:
|
|
207
|
+
`)}`;return Xs={queryKey:o,result:u,ts:Date.now()},u}Np.exports={getBrainDir:Js,listDocuments:Io,readDocument:_p,writeDocument:a_,removeDocument:l_,buildIndex:Tc,getIndex:xp,query:Op,getBrainContext:m_,isEmbeddingAvailable:Sp,generateEmbedding:Nc,buildEmbeddingIndex:Rp,semanticQuery:Cp,cosineSimilarity:Ep,_keywordQuery:vp,_extractKeywords:Cc,_chunkText:Tp,parseFrontmatter:jo,tokenize:vi,_fuseResults:Ap}});var un=Q((sR,Hp)=>{var Ke=require("fs"),At=require("path"),h_=require("os"),{atomicWrite:Si,withFileLockSync:Mp}=An(),qo=["user","feedback","project","reference"],g_=50;function rs(){return At.join(process.cwd(),".nex","memory")}function Vs(){return At.join(rs(),"memory.json")}function Pp(){return At.join(rs(),"MEMORY.md")}function $_(){return At.join(process.cwd(),"NEX.md")}function Lp(){return At.join(h_.homedir(),".nex","NEX.md")}function Ei(){let t=rs();Ke.existsSync(t)||Ke.mkdirSync(t,{recursive:!0})}function Ip(t){let e=At.join(rs(),t);return Ke.existsSync(e)||Ke.mkdirSync(e,{recursive:!0}),e}function Fo(){let t=Vs();if(!Ke.existsSync(t))return{};try{return JSON.parse(Ke.readFileSync(t,"utf-8"))}catch{return{}}}function jp(t){Ei(),Si(Vs(),JSON.stringify(t,null,2))}function Dp(){let t=Vs();if(!Ke.existsSync(t))return;let e=Fo(),n=Object.keys(e);if(n.length===0){try{Ke.renameSync(t,t+".bak")}catch{}return}for(let o of n){let s=e[o],r=s.value||String(s),i=o.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!i)continue;let c=Ip("project"),l=At.join(c,`${i}.md`),u=r.split(`
|
|
208
208
|
`)[0].slice(0,100),d=`---
|
|
209
209
|
name: ${o}
|
|
210
210
|
description: ${u}
|
|
@@ -212,7 +212,7 @@ type: project
|
|
|
212
212
|
---
|
|
213
213
|
|
|
214
214
|
${r}
|
|
215
|
-
`;Si(l,d)}Ti();try{Ke.renameSync(t,t+".bak")}catch{}}function
|
|
215
|
+
`;Si(l,d)}Ti();try{Ke.renameSync(t,t+".bak")}catch{}}function y_(t,e,n,o){if(!qo.includes(t))return{ok:!1,path:"",error:`Invalid type: ${t}. Must be one of: ${qo.join(", ")}`};if(!e||typeof e!="string")return{ok:!1,path:"",error:"name must be a non-empty string"};if(!n||typeof n!="string"||n.trim().length<5)return{ok:!1,path:"",error:"content must be at least 5 characters"};let s=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase().replace(/-+/g,"-").replace(/^-|-$/g,"");if(!s)return{ok:!1,path:"",error:"name produces empty slug after sanitization"};let r=Ip(t),i=At.join(r,`${s}.md`);if(Ke.existsSync(i))try{if(Mc(Ke.readFileSync(i,"utf-8")).body.slice(0,200)===n.slice(0,200))return{ok:!0,path:i,updated:!1}}catch{}let c=o||n.split(`
|
|
216
216
|
`)[0].slice(0,100),l=`---
|
|
217
217
|
name: ${e}
|
|
218
218
|
description: ${c}
|
|
@@ -220,9 +220,9 @@ type: ${t}
|
|
|
220
220
|
---
|
|
221
221
|
|
|
222
222
|
${n}
|
|
223
|
-
`;return Si(i,l),Ti(),{ok:!0,path:i,updated:!0}}function
|
|
223
|
+
`;return Si(i,l),Ti(),{ok:!0,path:i,updated:!0}}function w_(t,e){if(!qo.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=At.join(rs(),t,`${n}.md`);if(!Ke.existsSync(o))return!1;try{return Ke.unlinkSync(o),Ti(),!0}catch{return!1}}function Mc(t){let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(!e)return{name:"",description:"",type:"",body:t.trim()};let n=e[1],o=(e[2]||"").trim(),s=r=>{let i=n.match(new RegExp(`^${r}:\\s*(.+)$`,"m"));return i?i[1].trim():""};return{name:s("name"),description:s("description"),type:s("type"),body:o}}function qp(){let t=[],e=rs();for(let n of qo){let o=At.join(e,n);if(!Ke.existsSync(o))continue;let s;try{s=Ke.readdirSync(o).filter(r=>r.endsWith(".md"))}catch{continue}for(let r of s){let i=At.join(o,r);try{let c=Ke.readFileSync(i,"utf-8"),l=Mc(c);t.push({type:n,name:l.name||At.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function Ti(){let t=qp(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=g_+2)break;let o=`${n.type}/${At.basename(n.filePath)}`;e.push(`- [${n.name}](${o}) \u2014 ${n.description||"(no description)"}`)}Ei(),Si(Pp(),e.join(`
|
|
224
224
|
`)+`
|
|
225
|
-
`)}function Fp(){let t=Pp();if(!Ke.existsSync(t))return"";try{return Ke.readFileSync(t,"utf-8").trim()}catch{return""}}function
|
|
225
|
+
`)}function Fp(){let t=Pp();if(!Ke.existsSync(t))return"";try{return Ke.readFileSync(t,"utf-8").trim()}catch{return""}}function b_(t,e){Ei(),Mp(Vs(),()=>{let n=Fo();n[t]={value:e,updatedAt:new Date().toISOString()},jp(n)})}function __(t){let e=Fo();return e[t]?e[t].value:null}function x_(t){return Ei(),Mp(Vs(),()=>{let e=Fo();return t in e?(delete e[t],jp(e),!0):!1})}function Up(){let t=Fo();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function Bp(){let t=Lp();if(!Ke.existsSync(t))return"";try{return Ke.readFileSync(t,"utf-8").trim()}catch{return""}}function Wp(){let t=$_();if(!Ke.existsSync(t))return"";try{return Ke.readFileSync(t,"utf-8").trim()}catch{return""}}function v_(){Dp();let t=[],e=Bp();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
226
226
|
${e}`);let n=Wp();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
227
227
|
${n}`);let o="",s=Fp();if(s)o=s;else{let f=Up();f.length>0&&(o=`PROJECT MEMORY:
|
|
228
228
|
${f.map(h=>` ${h.key}: ${h.value}`).join(`
|
|
@@ -233,27 +233,27 @@ ${f.map(h=>` ${h.key}: ${h.value}`).join(`
|
|
|
233
233
|
`}o=p.trimEnd()+`
|
|
234
234
|
[Memory index truncated \u2014 use delete_memory to prune old entries]`}else o.length>u&&(o="");let d=[...t];return o&&d.push(o),d.length>0&&d.push(i),d.join(`
|
|
235
235
|
|
|
236
|
-
`)}Hp.exports={saveMemory
|
|
236
|
+
`)}Hp.exports={saveMemory:y_,deleteMemory:w_,scanMemories:qp,rebuildIndex:Ti,loadMemoryIndex:Fp,remember:b_,recall:__,forget:x_,listMemories:Up,loadGlobalInstructions:Bp,loadProjectInstructions:Wp,getMemoryContext:v_,_getMemoryDir:rs,_getMemoryFile:Vs,_getGlobalNexMdPath:Lp,_parseMemoryFile:Mc,_migrateIfNeeded:Dp,VALID_TYPES:qo}});var Ic=Q((oR,Xp)=>{var Uo=require("fs"),Pc=require("path"),Lc=process.env.NEX_AUDIT!=="false",is=null;function Kp(){return is||(is=Pc.join(process.cwd(),".nex","audit"),Uo.existsSync(is)||Uo.mkdirSync(is,{recursive:!0}),is)}function Gp(){let t=new Date().toISOString().split("T")[0];return Pc.join(Kp(),`${t}.jsonl`)}function k_(t){if(Lc)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Yp(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)+`
|
|
237
237
|
`;Uo.appendFileSync(Gp(),n,"utf-8")}catch{}}function Yp(t){if(!t||typeof t!="object")return{};let e={};for(let[n,o]of Object.entries(t))/key|token|password|secret|credential/i.test(n)?e[n]="***":typeof o=="string"&&o.length>500?e[n]=o.substring(0,500)+`... (${o.length} chars)`:e[n]=o;return e}function zp(t={}){let e=Kp(),n=t.days||1,o=[];for(let s=0;s<n;s++){let r=t.date||new Date(Date.now()-s*864e5).toISOString().split("T")[0],i=Pc.join(e,`${r}.jsonl`);if(!Uo.existsSync(i))continue;let c=Uo.readFileSync(i,"utf-8").split(`
|
|
238
|
-
`).filter(l=>l.trim());for(let l of c)try{let u=JSON.parse(l);if(t.tool&&u.tool!==t.tool)continue;o.push(u)}catch{}if(t.date)break}return o}function
|
|
238
|
+
`).filter(l=>l.trim());for(let l of c)try{let u=JSON.parse(l);if(t.tool&&u.tool!==t.tool)continue;o.push(u)}catch{}if(t.date)break}return o}function S_(t=1){let e=zp({days:t});if(e.length===0)return{totalCalls:0,byTool:{},avgDuration:0,successRate:1};let n={},o=0,s=0;for(let r of e)n[r.tool]=(n[r.tool]||0)+1,o+=r.duration||0,r.success&&s++;return{totalCalls:e.length,byTool:n,avgDuration:Math.round(o/e.length),successRate:s/e.length}}function E_(t){Lc=t}function T_(){return Lc}function R_(){is=null}Xp.exports={logToolExecution:k_,sanitizeArgs:Yp,readAuditLog:zp,getAuditSummary:S_,setAuditEnabled:E_,isAuditEnabled:T_,getAuditLogPath:Gp,_reset:R_}});var im=Q((aR,rm)=>{var ze=require("fs").promises,Jp=require("fs"),Ie=require("path"),De=require("util").promisify(require("child_process").exec),jc=require("util").promisify(require("child_process").execFile),{spawnSync:C_}=require("child_process"),Dc=require("axios"),{isForbidden:A_,isSSHForbidden:O_,isDangerous:N_,isCritical:Vp,isBashPathForbidden:M_,confirm:Yt}=ft(),{showClaudeDiff:Ri,showClaudeNewFile:P_,showEditDiff:rR,confirmFileChange:Bo}=Od(),{C:fe,Spinner:L_,getToolSpinnerText:I_}=Fe(),{isGitRepo:qc,getCurrentBranch:Zp,getStatus:j_,getDiff:D_}=Nn(),{recordChange:Ci}=yn(),{fuzzyFindText:Qp,findMostSimilar:Ko}=df(),{runDiagnostics:Wo}=pf(),{findFileInIndex:q_,getFileIndex:iR}=mc(),{resolveProfile:Ft,sshExec:xt,scpUpload:F_,scpDownload:U_}=Ks(),{resolveDeployConfig:B_,loadDeployConfigs:W_}=yc(),{getEditMode:em}=Ro(),H_=/^(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/,K_=/^ssh\s/,G_=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function Ot(t){return ze.access(t).then(()=>!0).catch(()=>!1)}async function Ai(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=vt(e);if(n&&await Ot(n))return{fixedPath:n,message:`(auto-fixed path: ${t} \u2192 ${e})`};let o=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],s=Ie.extname(t);if(!s)for(let i of o){let c=vt(t+i);if(c&&await Ot(c))return{fixedPath:c,message:`(auto-fixed: added ${i} extension)`}}if(s){let i=t.replace(/\.[^.]+$/,"");for(let c of o){if(c===s)continue;let l=vt(i+c);if(l&&await Ot(l))return{fixedPath:l,message:`(auto-fixed: ${s} \u2192 ${c})`}}}let r=Ie.basename(t);if(r&&r.length>2)try{let i=q_(r).map(c=>vt(c));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${Ie.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
239
239
|
${i.map(l=>Ie.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
240
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
240
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function Y_(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 sm(t,e){let n=[];if(/command not found|: not found|not recognized/i.test(t)){let o=e.match(/^(\S+)/),s=o?o[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(s)?n.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(s)?n.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):n.push(`HINT: "${s}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let o=t.match(/Cannot find module '([^']+)'/),s=o?o[1]:"";s&&!s.startsWith(".")&&!s.startsWith("/")?n.push(`HINT: Missing npm package "${s}". Run: npm install ${s}`):n.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&n.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let o=t.match(/port (\d+)|:(\d+)/),s=o?o[1]||o[2]:"";n.push(`HINT: Port ${s||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&n.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&n.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&n.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&n.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let o=t.match(/curl:\s*\((\d+)\)/),s=o?parseInt(o[1],10):null;s===6||/Could not resolve host/i.test(t)?n.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):s===7||/Failed to connect|Connection refused/i.test(t)?n.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):s===22||/HTTP error/i.test(t)?n.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):s===28||/timed out/i.test(t)?n.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(s===35||/SSL.*error/i.test(t))&&n.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let o=t.match(/port (\d+)/),s=o?o[1]:"";n.push(`HINT: SSH remote port forwarding failed for port ${s}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${s}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&n.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&n.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),/spawn \/bin\/sh ENOENT|spawn sh ENOENT/i.test(t)&&n.push("HINT: The working directory was deleted during this session \u2014 bash cannot execute commands in a non-existent cwd. Previous rm/delete commands succeeded. Use list_directory or glob to verify the state instead of retrying bash."),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&n.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),n.length===0?t:t+`
|
|
241
241
|
|
|
242
242
|
`+n.join(`
|
|
243
|
-
`)}function om(t,e,n){let o=Ko(t,e);if(!o)return null;let s=Math.max(2,Math.ceil(e.length*.03));return o.distance>s?null:{autoFixed:!0,matchText:o.text,content:t.split(o.text).join(n),distance:o.distance,line:o.line}}var tm=!1,as=null;function Y_(){as&&(as(),as=null)}var Uc=null;function z_(t){Uc=t}async function Fc(){if(!tm){tm=!0;try{let{stdout:t}=await De("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await De('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await De("git stash pop",{cwd:process.cwd(),timeout:1e4}),await De("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var X_=[/\.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 vt(t){let e=Ie.isAbsolute(t)?Ie.resolve(t):Ie.resolve(process.cwd(),t);for(let n of X_)if(n.test(e))return null;return e}var J_=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. You MUST use this tool at least once on a file BEFORE calling edit_file or patch_file on it \u2014 this ensures you have the exact current content and edits will match. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. You MUST call read_file on the target file first to see the exact content \u2014 never guess or recall from memory. COMMON FAILURE: old_text doesn't match because you guessed the content instead of reading the file first. If the edit fails with 'old_text not found', use the line number from the error message to re-read that specific region with line_start/line_end, then retry with the exact text. For multiple changes to the same file, prefer patch_file (single atomic operation).",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Returns paths sorted by modification time. Use this to FIND files before reading them \u2014 never guess file paths, always glob first. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to find the path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Prefer this over bash grep/rg \u2014 this tool returns structured, formatted output. Use output_mode='files_with_matches' when you only need file paths (faster, less output). Use output_mode='content' (default) for matching lines with context. Use head_limit to cap results and avoid overwhelming output on broad searches. Use include to filter by file type (e.g. '*.js'). Supports context lines (context, before_context, after_context), offset for pagination, type filter, and multiline for cross-line patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl, jarvis) that live on almalinux9/jarvis. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/jarvis/jarvis-agent). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt (package_action: check|list|install|remove|update|upgrade); user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "jarvis-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "jarvis-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function Ho(t,{server:e,context:n}={}){let o=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,s=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(s&&(r+=` --context ${s}`),r+=` ${t}`,o){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${o} "${i}"`}return r}async function nm(t,e,n={}){switch(t){case"bash":{let o=e.command,s=C_(o);if(s){let f=G_(o);return`BLOCKED: Command matches forbidden pattern: ${s}${f?`
|
|
244
|
-
HINT: ${f}`:""}`}let r=
|
|
245
|
-
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?Vp(o):
|
|
246
|
-
${h}`}}case"read_file":{let o=vt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Ot(o)){let O=await Ai(e.path);if(O.fixedPath)o=O.fixedPath,console.log(`${
|
|
243
|
+
`)}function om(t,e,n){let o=Ko(t,e);if(!o)return null;let s=Math.max(2,Math.ceil(e.length*.03));return o.distance>s?null:{autoFixed:!0,matchText:o.text,content:t.split(o.text).join(n),distance:o.distance,line:o.line}}var tm=!1,as=null;function z_(){as&&(as(),as=null)}var Uc=null;function X_(t){Uc=t}async function Fc(){if(!tm){tm=!0;try{let{stdout:t}=await De("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await De('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await De("git stash pop",{cwd:process.cwd(),timeout:1e4}),await De("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var J_=[/\.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 vt(t){let e=Ie.isAbsolute(t)?Ie.resolve(t):Ie.resolve(process.cwd(),t);for(let n of J_)if(n.test(e))return null;return e}var V_=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s (commands that exceed this are killed). Use for: running tests, installing packages, git commands, build tools, starting servers, compiling code. AVOID using bash for: cat/head/tail (use read_file), sed/awk (use edit_file), find/ls (use glob or list_directory), grep/rg (use grep tool). Using dedicated tools is faster and produces better-formatted output. Always quote file paths containing spaces with double quotes. Check the exit code in output \u2014 non-zero means the command failed. For long-running commands (large builds, full test suites), warn the user if they may exceed 90s. Destructive or dangerous commands (rm -rf, git push, npm publish, sudo) require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. You MUST use this tool at least once on a file BEFORE calling edit_file or patch_file on it \u2014 this ensures you have the exact current content and edits will match. Auto-truncates at 350 lines for unbounded reads. For large files (>350 lines), use line_start/line_end to read specific sections. Prefer this over bash cat/head/tail \u2014 dedicated tools produce better-formatted output. Files are read with UTF-8 encoding.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. You MUST call read_file on the target file first to see the exact content \u2014 never guess or recall from memory. COMMON FAILURE: old_text doesn't match because you guessed the content instead of reading the file first. If the edit fails with 'old_text not found', use the line number from the error message to re-read that specific region with line_start/line_end, then retry with the exact text. For multiple changes to the same file, prefer patch_file (single atomic operation).",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Returns paths sorted by modification time. Use this to FIND files before reading them \u2014 never guess file paths, always glob first. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src), 'package.json' (find config). Prefer this over bash find/ls. When you need file contents, glob first to find the path, then read_file to read it.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Prefer this over bash grep/rg \u2014 this tool returns structured, formatted output. Use output_mode='files_with_matches' when you only need file paths (faster, less output). Use output_mode='content' (default) for matching lines with context. Use head_limit to cap results and avoid overwhelming output on broad searches. Use include to filter by file type (e.g. '*.js'). Supports context lines (context, before_context, after_context), offset for pagination, type filter, and multiline for cross-line patterns.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter glob (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"},output_mode:{type:"string",enum:["content","files_with_matches","count"],description:"Output mode: content (matching lines), files_with_matches (file paths only), count (match counts). Default: content"},context:{type:"number",description:"Lines of context around each match (like grep -C)"},before_context:{type:"number",description:"Lines before each match (like grep -B)"},after_context:{type:"number",description:"Lines after each match (like grep -A)"},head_limit:{type:"number",description:"Limit output to first N results"},offset:{type:"number",description:"Skip first N results"},type:{type:"string",description:"File type filter (e.g. 'js', 'py', 'ts') \u2014 maps to --include='*.ext'"},multiline:{type:"boolean",description:"Enable multiline matching (grep -Pz)"},staged:{type:"boolean",description:"Search only staged content (git diff --cached). Default: false"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5 at top level, max 2 when called from within a sub-agent). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained. SWARM PATTERN: Sub-agents can call spawn_agents once (max nesting depth 2) to enable Architect\u2192Coder\u2192Reviewer pipelines: a coder agent spawns 1-2 reviewer agents that validate and fix its own output before returning results to the parent.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"remote_agent",description:'Delegate a coding task to nex-code running on a remote server. Use this when the task involves server-side projects (musikschule, stadtkapelle, cahill, schoensgibl, jarvis) that live on almalinux9/jarvis. Runs nex-code --auto on the server and streams output. Server is a profile name from .nex/servers.json or "user@host".',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name from .nex/servers.json (e.g. "almalinux9") or "user@host"'},task:{type:"string",description:"The full task description to run on the remote nex-code"},project_path:{type:"string",description:"Working directory on the remote server (e.g. /home/jarvis/jarvis-agent). Defaults to home directory."},model:{type:"string",description:"Model to use on remote nex-code (e.g. qwen3-coder:480b). Defaults to server default."}},required:["server","task"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"frontend_recon",description:"MANDATORY first step before creating or significantly modifying any frontend file (HTML template, Vue/React component, CSS). Scans the project and returns: (1) design tokens \u2014 CSS variables, Tailwind theme colors/fonts, (2) main layout/index page structure, (3) a reference component of the same type, (4) detected JS/CSS framework stack. Call this BEFORE writing any markup or styles. Never skip it for frontend tasks.",parameters:{type:"object",properties:{type:{type:"string",description:'Type of frontend file you are about to create. Used to find a relevant reference component. Examples: "list", "form", "detail", "dashboard", "modal", "component". Optional but improves reference quality.'}},required:[]}}},{type:"function",function:{name:"deploy",description:'Deploy to a remote server. Supports two methods: "rsync" (sync local files) and "git" (git pull on remote). Can use a named config from .nex/deploy.json. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},method:{type:"string",enum:["rsync","git"],description:'Deploy method: "rsync" syncs local files (default), "git" runs git pull on the remote.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},remote_path:{type:"string",description:"Remote project directory. Required for git method; destination path for rsync."},local_path:{type:"string",description:"Local directory or file to sync. Required for rsync method."},branch:{type:"string",description:"Branch to pull (git method only). Defaults to current remote branch."},deploy_script:{type:"string",description:'Shell command(s) to run on the remote after sync/pull (e.g. "npm ci && systemctl restart myapp"). Optional.'},health_check:{type:"string",description:"URL (HTTP GET) or shell command to verify the service is healthy after deploy. If it fails, the deploy is marked as failed. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from rsync. Optional."},dry_run:{type:"boolean",description:"Show what would happen without executing. Default: false."}},required:[]}}},{type:"function",function:{name:"deployment_status",description:"Check deployment status across all configured servers. Reads .nex/deploy.json configs and checks service health on each server. Returns a status summary table.",parameters:{type:"object",properties:{config:{type:"string",description:"Specific deploy config name to check (optional \u2014 checks all if omitted)"}},required:[]}}},{type:"function",function:{name:"sysadmin",description:"Senior sysadmin operations on a remote (or local) Linux server. Covers: system audit, disk_usage, process_list, network_status, package management (dnf/apt), user management, firewall (firewalld/ufw/iptables), cron, SSL cert checks, log tailing, large file discovery, systemd service management, process kill, journalctl log querying. Read-only actions run without confirmation; state-changing actions require user approval.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},action:{type:"string",enum:["audit","disk_usage","process_list","network_status","package","user_manage","firewall","cron","ssl_check","log_tail","find_large","service","kill_process","journalctl"],description:"Sysadmin operation. audit=full health overview; disk_usage=df+du; process_list=top procs; network_status=open ports; package=dnf/apt (package_action: check|list|install|remove|update|upgrade); user_manage=users/keys; firewall=rules; cron=crontab; ssl_check=cert expiry+days; log_tail=tail any log; find_large=big files; service=systemd unit management; kill_process=kill by PID or name; journalctl=query system journal."},path:{type:"string",description:"File or directory path. For disk_usage (default /), log_tail (required), find_large (default /)."},lines:{type:"number",description:"Lines to tail for log_tail or journalctl. Default: 100."},limit:{type:"number",description:"Result count for process_list (default 20) or find_large (default 20)."},sort_by:{type:"string",enum:["cpu","mem"],description:"Sort order for process_list. Default: cpu."},min_size:{type:"string",description:'Minimum file size for find_large. Default: "100M". Examples: "50M", "1G".'},package_action:{type:"string",enum:["install","remove","update","list","upgrade"],description:"Package sub-action for action=package."},packages:{type:"array",items:{type:"string"},description:"Package name(s) for install/remove/update."},user_action:{type:"string",enum:["list","create","delete","add_ssh_key","info"],description:"User sub-action for action=user_manage."},user:{type:"string",description:"Linux username for user_manage or cron."},groups:{type:"array",items:{type:"string"},description:'Groups to assign on user create (e.g. ["sudo", "docker"]).'},ssh_key:{type:"string",description:"SSH public key string to add for user_action=add_ssh_key."},firewall_action:{type:"string",enum:["status","allow","deny","remove","reload"],description:"Firewall sub-action for action=firewall."},port:{type:"string",description:'Port/protocol for firewall rules, e.g. "80/tcp", "443", "8080/udp".'},cron_action:{type:"string",enum:["list","add","remove"],description:"Cron sub-action for action=cron."},schedule:{type:"string",description:'Cron schedule expression for cron add, e.g. "0 2 * * *".'},command:{type:"string",description:"Command for cron add, or substring to match for cron remove."},domain:{type:"string",description:`Domain for ssl_check (e.g. "example.com"). Auto-detects Let's Encrypt cert on server; falls back to live TLS probe.`},cert_path:{type:"string",description:'Explicit path to cert file on server for ssl_check (e.g. "/etc/letsencrypt/live/x/cert.pem").'},service_name:{type:"string",description:'Systemd unit name for action=service (e.g. "nginx", "jarvis-api", "gunicorn"). .service suffix optional.'},service_action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable","list_failed"],description:"Sub-action for action=service. list_failed shows all failed units."},pid:{type:"number",description:"Process ID to kill for action=kill_process."},process_name:{type:"string",description:"Process name to kill (uses pkill) for action=kill_process. Use with pid for safety."},signal:{type:"string",enum:["SIGTERM","SIGKILL","SIGHUP","SIGINT"],description:"Signal for kill_process. Default: SIGTERM."},unit:{type:"string",description:'Systemd unit to filter for journalctl (e.g. "nginx", "jarvis-api"). Omit for system-wide.'},since:{type:"string",description:'Time filter for journalctl, e.g. "1 hour ago", "today", "2026-03-17 10:00". Default: last 200 lines.'},priority:{type:"string",enum:["emerg","alert","crit","err","warning","notice","info","debug"],description:"Minimum log priority for journalctl. Default: no filter."}},required:["action"]}}},{type:"function",function:{name:"save_memory",description:"Save a typed memory for cross-session persistence. Use this to remember user preferences, feedback, project context, or external references.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type: user (role/prefs), feedback (approach guidance), project (ongoing work), reference (external pointers)"},name:{type:"string",description:"Short slug identifier for this memory (e.g. 'testing-preference', 'deploy-workflow')"},content:{type:"string",description:"Markdown content of the memory"},description:{type:"string",description:"One-line description for the memory index (optional, defaults to first line of content)"}},required:["type","name","content"]}}},{type:"function",function:{name:"delete_memory",description:"Delete a typed memory entry. Use this to prune outdated or incorrect memories.",parameters:{type:"object",properties:{type:{type:"string",enum:["user","feedback","project","reference"],description:"Memory type to delete from"},name:{type:"string",description:"Slug identifier of the memory to delete"}},required:["type","name"]}}}];function Ho(t,{server:e,context:n}={}){let o=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,s=n?n.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(s&&(r+=` --context ${s}`),r+=` ${t}`,o){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${o} "${i}"`}return r}async function nm(t,e,n={}){switch(t){case"bash":{let o=e.command,s=A_(o);if(s){let f=Y_(o);return`BLOCKED: Command matches forbidden pattern: ${s}${f?`
|
|
244
|
+
HINT: ${f}`:""}`}let r=M_(o);if(r)return`BLOCKED: Destructive operation on protected path: ${r}
|
|
245
|
+
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?Vp(o):N_(o)){let f=Vp(o)?"\u26D4":"\u26A0";if(!await Yt(` ${f} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let c;try{c=process.cwd(),Jp.accessSync(c)}catch{c=require("os").homedir(),n.silent||console.log(`${fe.yellow} \u26A0 Working directory no longer exists \u2014 running in ${c}${fe.reset}`)}let l=K_.test(o.trim())&&!G_.test(o.trim());if(H_.test(o.trim())||l){n.silent||console.log(`${fe.dim} \u25B6 interactive: ${o}${fe.reset}`);let f=C_("sh",["-c",o],{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}=Ms(),d=n.silent?null:new u("bash",o.substring(0,40));d&&d.start();try{let{stdout:f,stderr:p}=await De(o,{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),h=sm(p,o);return`EXIT ${f.code||1}
|
|
246
|
+
${h}`}}case"read_file":{let o=vt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Ot(o)){let O=await Ai(e.path);if(O.fixedPath)o=O.fixedPath,console.log(`${fe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ie.relative(process.cwd(),o)}${fe.reset}`);else return`ERROR: File not found: ${e.path}${O.message?`
|
|
247
247
|
`+O.message:""}`}let r=Buffer.alloc(8192),i=await Jp.promises.open(o,"r"),{bytesRead:c}=await i.read(r,0,8192,0);await i.close();for(let O=0;O<c;O++)if(r[O]===0)return`ERROR: ${o} is a binary file (not readable as text)`;let l=await ze.readFile(o,"utf-8");if(!l&&(await ze.stat(o)).size>0)return`WARNING: ${o} is empty or unreadable`;let u=l.split(`
|
|
248
248
|
`),d=await ze.stat(o),f=u.length,p=350,h=!e.line_start&&!e.line_end,m=h&&f>p,g=(e.line_start||1)-1,y=m?p:e.line_end||u.length,w=Ie.relative(process.cwd(),o),v=m?`showing lines 1-${p} of ${f}`:e.line_start||e.line_end?`lines ${g+1}-${y} of ${f}`:`${f} lines`,M=`File: ${w} (${v}, ${d.size} bytes)`,C=u.slice(g,y).map((O,D)=>`${g+D+1}: ${O}`).join(`
|
|
249
249
|
`),S=m?`
|
|
250
250
|
|
|
251
251
|
[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)}]`:!h&&f>p?`
|
|
252
252
|
[Large file (${f} lines total) \u2014 use line_start/line_end for other sections]`:"";return`${M}
|
|
253
|
-
${C}${S}`}case"write_file":{await Fc();let o=vt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=await Ot(o),r=null;if(n.autoConfirm)s&&(r=await ze.readFile(o,"utf-8"));else if(s){r=await ze.readFile(o,"utf-8");let d=await Wo(o,e.content);if(Ri(o,r,e.content,{annotations:d}),!await Bo("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let d=await Wo(o,e.content);if(
|
|
253
|
+
${C}${S}`}case"write_file":{await Fc();let o=vt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=await Ot(o),r=null;if(n.autoConfirm)s&&(r=await ze.readFile(o,"utf-8"));else if(s){r=await ze.readFile(o,"utf-8");let d=await Wo(o,e.content);if(Ri(o,r,e.content,{annotations:d}),!await Bo("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let d=await Wo(o,e.content);if(P_(o,e.content,{annotations:d}),!await Bo("Create"))return"CANCELLED: User declined to create file."}let i=Ie.dirname(o);await Ot(i)||await ze.mkdir(i,{recursive:!0}),await ze.writeFile(o,e.content,"utf-8");let l=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||e.content.startsWith("#!");l&&await ze.chmod(o,493),Ci("write_file",o,r,e.content);let u=l?" [chmod +x applied]":"";return`Written: ${o} (${e.content.length} chars)${u}`}case"edit_file":{await Fc();let o=vt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Ot(o)){let d=await Ai(e.path);if(d.fixedPath)o=d.fixedPath,console.log(`${fe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ie.relative(process.cwd(),o)}${fe.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
254
254
|
`+d.message:""}`}let r=await ze.readFile(o,"utf-8"),i=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let{getActiveModelId:d,getActiveProviderName:f}=je();if(em(d(),f())==="strict"){let m=Ko(r,e.old_text);return m?`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)
|
|
255
255
|
Most similar text (line ${m.line}, distance ${m.distance}):
|
|
256
|
-
${m.text}`:`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)`}let h=Qp(r,e.old_text);if(h)i=h,c=!0,console.log(`${
|
|
256
|
+
${m.text}`:`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)`}let h=Qp(r,e.old_text);if(h)i=h,c=!0,console.log(`${fe.dim} \u2713 fuzzy whitespace match applied${fe.reset}`);else{let m=om(r,e.old_text,e.new_text);if(m){if(!n.autoConfirm){let M=await Wo(o,m.content);if(Ri(o,r,m.content,{annotations:M}),!await Bo(`Apply (auto-fix, line ${m.line}, distance ${m.distance})`))return"CANCELLED: User declined to apply edit."}await ze.writeFile(o,m.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||m.content.startsWith("#!"))&&await ze.chmod(o,493),Ci("edit_file",o,r,m.content);let v=m.matchText.length>80?m.matchText.substring(0,77)+"...":m.matchText;return console.log(`${fe.dim} \u2713 auto-fixed edit: line ${m.line}, distance ${m.distance}${fe.reset}`),`Edited: ${o} (auto-fixed, line ${m.line}, distance ${m.distance}, matched: "${v}")`}let g=Ko(r,e.old_text);if(g){let v=r.split(`
|
|
257
257
|
`),M=Math.max(0,g.line-6),C=Math.min(v.length,g.line+10),S=v.slice(M,C).map((D,K)=>`${M+K+1}: ${D}`).join(`
|
|
258
258
|
`),O=`line_start=${Math.max(1,g.line-5)} line_end=${Math.min(v.length,g.line+15)}`;return`ERROR: old_text not found in ${o} (most similar at line ${g.line}, distance ${g.distance})
|
|
259
259
|
|
|
@@ -276,7 +276,7 @@ Recovery: use grep -n to locate the text, then re-read that section with line_st
|
|
|
276
276
|
`).trim()||"(no matches in staged files)"}let s=["-rn","-E","--null","-H"];e.ignore_case&&s.push("-i"),e.include&&s.push(`--include=${e.include}`),e.type&&s.push(`--include=*.${e.type}`);let r=20;e.context?s.push("-C",String(Math.min(Number(e.context),r))):(e.before_context&&s.push("-B",String(Math.min(Number(e.before_context),r))),e.after_context&&s.push("-A",String(Math.min(Number(e.after_context),r)))),e.output_mode==="files_with_matches"?s.push("-l"):e.output_mode==="count"&&s.push("-c"),s.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),s.push(e.pattern,o);let{ToolProgress:i}=Ms(),c=new i("grep","Searching...");c.start();try{let{stdout:l}=await jc("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),u;if(e.output_mode==="files_with_matches"||e.output_mode==="count")u=l.trim().split(`
|
|
277
277
|
`).filter(p=>p.trim());else{let p=l.split("\0");u=[];for(let h=0;h<p.length;h+=2){let m=p[h],g=p[h+1];if(m&&g){let y=g.split(`
|
|
278
278
|
`).filter(w=>w.trim());for(let w of y)u.push(`${m}:${w}`)}}}let d=e.offset||0,f=e.head_limit||(e.output_mode==="files_with_matches"?200:100);return u=u.slice(d,d+f),c.update({count:u.length,detail:`in ${o}`}),c.stop(),u.join(`
|
|
279
|
-
`).trim()||"(no matches)"}catch(l){return c.stop(),l.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Fc();let o=vt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Ot(o)){let w=await Ai(e.path);if(w.fixedPath)o=w.fixedPath,console.log(`${
|
|
279
|
+
`).trim()||"(no matches)"}catch(l){return c.stop(),l.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Fc();let o=vt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await Ot(o)){let w=await Ai(e.path);if(w.fixedPath)o=w.fixedPath,console.log(`${fe.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ie.relative(process.cwd(),o)}${fe.reset}`);else return`ERROR: File not found: ${e.path}${w.message?`
|
|
280
280
|
`+w.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await ze.readFile(o,"utf-8"),{getActiveModelId:c,getActiveProviderName:l}=je(),u=em(c(),l()),d=[],f=!1,p=!1;for(let w=0;w<r.length;w++){let{old_text:v,new_text:M}=r[w];if(i.includes(v))d.push({old_text:v,new_text:M});else if(u==="strict"){let C=Ko(i,v);return C?`ERROR: Patch ${w+1} old_text not found in ${o} (strict mode \u2014 exact match required)
|
|
281
281
|
Most similar text (line ${C.line}, distance ${C.distance}):
|
|
282
282
|
${C.text}`:`ERROR: Patch ${w+1} old_text not found in ${o} (strict mode \u2014 exact match required)`}else{let C=Qp(i,v);if(C)d.push({old_text:C,new_text:M}),f=!0;else{let S=Ko(i,v);if(S){let O=Math.max(3,Math.ceil(v.length*.05));if(S.distance<=O)d.push({old_text:S.text,new_text:M}),p=!0;else return`ERROR: Patch ${w+1} old_text not found in ${o}
|
|
@@ -287,7 +287,7 @@ ${r}`;return i.length>0&&(c+=`
|
|
|
287
287
|
|
|
288
288
|
Sources:
|
|
289
289
|
`+i.slice(0,o).map((l,u)=>`${u+1}. ${l}`).join(`
|
|
290
|
-
`)),c}catch(s){console.error(`${
|
|
290
|
+
`)),c}catch(s){console.error(`${fe.dim} Perplexity search failed (${s.message}), falling back to DuckDuckGo${fe.reset}`)}try{let r=(await Dc.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<o;){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}
|
|
291
291
|
${u.url}`).join(`
|
|
292
292
|
|
|
293
293
|
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:o}=Ao();try{let s=await o(e.url,{waitFor:e.wait_for}),r=s.links.length>0?`
|
|
@@ -305,9 +305,9 @@ To analyze visually, paste the path into your next message: ${s.path}`}catch(s){
|
|
|
305
305
|
${s.map((l,u)=>` ${u+1}. ${l}`).join(`
|
|
306
306
|
`)}
|
|
307
307
|
`:"";console.log(`
|
|
308
|
-
${
|
|
308
|
+
${fe.cyan}${fe.bold} ? ${o}${fe.reset}${c}`),i.question(`${fe.cyan} > ${fe.reset}`,l=>{as=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await qc())return"ERROR: Not a git repository";let o=await Zp()||"(detached)",s=await j_();if(s.length===0)return`Branch: ${o}
|
|
309
309
|
Clean working tree (no changes)`;let r=[`Branch: ${o}`,`Changed files (${s.length}):`];for(let i of s){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(`
|
|
310
|
-
`)}case"git_diff":{if(!await qc())return"ERROR: Not a git repository";let o;if(e.file){let s=["diff"];e.staged&&s.push("--cached"),s.push("--",e.file);try{o=execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{o=""}}else o=await
|
|
310
|
+
`)}case"git_diff":{if(!await qc())return"ERROR: Not a git repository";let o;if(e.file){let s=["diff"];e.staged&&s.push("--cached"),s.push("--",e.file);try{o=execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{o=""}}else o=await D_(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await qc())return"ERROR: Not a git repository";let s=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&s.push("--",e.file);try{return execFileSync("git",s,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:o,updateTask:s,getTaskList:r,renderTaskList:i,hasActiveTasks:c}=hi(),{getActiveTaskProgress:l}=Fe(),u=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let d=o(e.name,e.tasks);return u||console.log(`
|
|
311
311
|
`+i()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
312
312
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
313
313
|
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":s(e.task_id,e.status,e.result)?(u||console.log(`
|
|
@@ -318,25 +318,25 @@ Clean working tree (no changes)`;let r=[`Branch: ${o}`,`Changed files (${s.lengt
|
|
|
318
318
|
...(truncated)`:"")}let{stdout:o}=await De(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),s=JSON.parse(o),r=[`Run: ${s.name} [${e.run_id}]`,`Branch: ${s.headBranch} Status: ${s.conclusion||s.status}`,`Started: ${s.createdAt} Finished: ${s.updatedAt||"\u2014"}`,"","Jobs:"];for(let i of s.jobs||[]){let 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(`
|
|
319
319
|
`)}catch(o){return`ERROR: ${(o.stderr||o.message||"").toString().split(`
|
|
320
320
|
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:o}=ft(),s=e.branch||await Zp()||"main",r=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",i=`gh workflow run ${e.workflow} --ref ${s} ${r}`.trim();if(console.log(`
|
|
321
|
-
${
|
|
321
|
+
${fe.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${s}${fe.reset}`),!await o(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await De(i,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${s}". Check status with gh_run_list.`}catch(l){return`ERROR: ${(l.stderr||l.message||"").toString().split(`
|
|
322
322
|
`)[0]}`}}case"k8s_pods":{let o=e.namespace?`-n ${e.namespace}`:"-A",s=e.label?`-l ${e.label}`:"",r=Ho(`get pods ${o} ${s} -o wide`.trim(),e);try{let{stdout:i,stderr:c}=await De(r,{timeout:3e4,maxBuffer:2097152});return(i||c||"(no pods)").trim()}catch(i){let c=(i.stderr||i.message||"").toString().split(`
|
|
323
323
|
`)[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 o=e.namespace||"default",s=e.tail||100,r=`logs ${e.pod} -n ${o} --tail=${s}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=Ho(r,e);try{let{stdout:c,stderr:l}=await De(i,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
|
|
324
324
|
...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
325
325
|
`)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let o=e.namespace||"default";if(console.log(`
|
|
326
|
-
${
|
|
326
|
+
${fe.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${o})${fe.reset}`),console.log(`${fe.dim} Command: ${e.command}${fe.reset}`),!await Yt(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${o}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let i=Ho(r,e);try{let{stdout:c,stderr:l}=await De(i,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
327
327
|
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let o=!!e.dry_run;if(!o){let i=e.file;if(console.log(`
|
|
328
|
-
${
|
|
328
|
+
${fe.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${fe.reset}`),!await Yt(" Apply to cluster?"))return"CANCELLED: User declined."}let s=`apply -f ${e.file}`;e.namespace&&(s+=` -n ${e.namespace}`),o&&(s+=" --dry-run=client");let r=Ho(s,e);try{let{stdout:i,stderr:c}=await De(r,{timeout:12e4,maxBuffer:2097152});return(i||c||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
|
|
329
329
|
`)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let o=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let c=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
|
|
330
|
-
${
|
|
330
|
+
${fe.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${o})${fe.reset}`),!await Yt(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${o}`,i=Ho(r,e);try{let{stdout:c,stderr:l}=await De(i,{timeout:12e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
331
331
|
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:o,readDocument:s}=Do(),{name:r,content:i,mode:c}=e;if(c==="create"&&s(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(c==="append"){let l=s(r),u=l.content?l.content+`
|
|
332
332
|
|
|
333
|
-
`+i:i;return o(r,u),`Appended to brain document: ${r}.md`}return o(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 o;try{o=Ft(e.server)}catch(O){return`ERROR: ${O.message}`}let s=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,c=
|
|
333
|
+
`+i:i;return o(r,u),`Appended to brain document: ${r}.md`}return o(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 o;try{o=Ft(e.server)}catch(O){return`ERROR: ${O.message}`}let s=e.command,r=!!e.sudo,i=(e.timeout||30)*1e3,c=O_(s);if(c)return/\bsed\s+-n\s+['"]?\d+,\d+p/.test(s)?`BLOCKED: sed -n line-range is blocked (floods context). To read specific lines from a remote file use:
|
|
334
334
|
grep -n "pattern" /path/to/file -A 50
|
|
335
335
|
or to read the whole file:
|
|
336
336
|
cat /path/to/file
|
|
337
337
|
NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${c}
|
|
338
338
|
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(s=s.replace(/(-[BAC])\s*(\d+)/g,(O,D,K)=>{let V=Math.min(Number(K),20);return`${D} ${V}`}),s=s.replace(/(--(?:before|after|context)=)(\d+)/g,(O,D,K)=>D+Math.min(Number(K),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(s)){let O=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
339
|
-
${
|
|
339
|
+
${fe.yellow} \u26A0 Remote command on ${O}: ${s}${fe.reset}`),!await Yt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:u,stderr:d,exitCode:f,error:p}=await xt(o,s,{timeout:i,sudo:r}),h=[u,d].filter(Boolean).join(`
|
|
340
340
|
`).trim();if(f!==0)return`EXIT ${f}
|
|
341
341
|
${p||h||"(no output)"}`;let m=/\bgrep\b/.test(s),g=h;m&&(g=g.split(`
|
|
342
342
|
`).filter(O=>O!=="--").join(`
|
|
@@ -346,9 +346,9 @@ ${p||h||"(no output)"}`;let m=/\bgrep\b/.test(s),g=h;m&&(g=g.split(`
|
|
|
346
346
|
`));let v=4,M=g.split(`
|
|
347
347
|
`),C=[],S=0;for(;S<M.length;){let O=S+1;for(;O<M.length&&M[O]===M[S];)O++;let D=O-S;if(C.push(M[S]),D>v)C.push(`... (${D-1} identical lines omitted)`);else for(let K=1;K<D;K++)C.push(M[S]);S=O}return C.join(`
|
|
348
348
|
`)||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let o;try{o=Ft(e.server)}catch(i){return`ERROR: ${i.message}`}let s=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
349
|
-
${
|
|
349
|
+
${fe.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${fe.reset}`),!await Yt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await F_(o,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 o;try{o=Ft(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await U_(o,e.remote_path,e.local_path)}catch(s){return`ERROR: ${s.message}`}}case"remote_agent":{let o=require("path").join(process.cwd(),".nex","servers.json"),s=null;try{s=JSON.parse(require("fs").readFileSync(o,"utf-8"))[e.server]||null}catch{}let r=s?`${s.user||"root"}@${s.host}`:e.server,i=s?.key?["-i",s.key]:[],c=e.project_path||s?.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 h=(p.stdout||"")+(p.stderr||"");return p.status!==0?`Remote nex-code exited with code ${p.status}.
|
|
350
350
|
${h.slice(-2e3)}`:h.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let o=["status","start","stop","restart","reload","enable","disable"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let s=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!s)try{i=Ft(e.server)}catch(l){return`ERROR: ${l.message}`}if(!r){let l=s?"local machine":i.user?`${i.user}@${i.host}`:i.host;if(console.log(`
|
|
351
|
-
${
|
|
351
|
+
${fe.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${fe.reset}`),!await Yt(" Execute?"))return"CANCELLED: User declined service action."}let c=`systemctl ${e.action} ${e.service}`;if(s){let u=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:d,stderr:f}=await De(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}
|
|
352
352
|
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await xt(i,c,{timeout:15e3,sudo:!0}),p=[l,u].filter(Boolean).join(`
|
|
353
353
|
`).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}
|
|
354
354
|
${f||p||"(no output)"}`:p||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let o=!e.server||e.server==="local"||e.server==="localhost",s=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${s} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(o)try{let{stdout:m,stderr:g}=await De(c,{timeout:15e3});return(m||g||"(no log output)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
@@ -361,16 +361,16 @@ ${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR
|
|
|
361
361
|
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Ft(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await xt(c,i,{timeout:2e4}),p=[l,u].filter(Boolean).join(`
|
|
362
362
|
`).trim();return d!==0?`EXIT ${d}
|
|
363
363
|
${f||p}`:p||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let o=!e.server||e.server==="local"||e.server==="localhost",s=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!n.autoConfirm&&!s.test(e.command.trim())){let m=o?"local":e.server;if(console.log(`
|
|
364
|
-
${
|
|
364
|
+
${fe.yellow} \u26A0 docker exec in ${e.container} on ${m}: ${e.command}${fe.reset}`),!await Yt(" 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(o)try{let{stdout:m,stderr:g}=await De(c,{timeout:3e4});return(m||g||"(no output)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
365
365
|
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=Ft(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:u,stderr:d,exitCode:f,error:p}=await xt(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
|
|
366
366
|
`).trim();return f!==0?`EXIT ${f}
|
|
367
367
|
${p||h}`:h||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let o=["start","stop","restart","remove","inspect"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let s=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!n.autoConfirm){let m=s?"local":e.server;if(console.log(`
|
|
368
|
-
${
|
|
368
|
+
${fe.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${fe.reset}`),!await Yt(" 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(s)try{let{stdout:m,stderr:g}=await De(c,{timeout:3e4});return(m||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
|
|
369
369
|
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=Ft(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:u,stderr:d,exitCode:f,error:p}=await xt(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
|
|
370
370
|
`).trim();return f!==0?`EXIT ${f}
|
|
371
|
-
${p||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...
|
|
372
|
-
${
|
|
373
|
-
${
|
|
371
|
+
${p||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...B_(e.config),...e},delete e.config,delete e._name}catch(d){return`ERROR: ${d.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.remote_path)return"ERROR: remote_path is required";let o=e.method||"rsync";if(o==="rsync"&&!e.local_path)return"ERROR: local_path is required for rsync method";let s;try{s=Ft(e.server)}catch(d){return`ERROR: ${d.message}`}let r=s.user?`${s.user}@${s.host}`:s.host;if(!e.dry_run&&!n.autoConfirm){if(o==="git"){let f=e.branch?` (branch: ${e.branch})`:"";console.log(`
|
|
372
|
+
${fe.yellow} \u26A0 Deploy [git pull]: ${r}:${e.remote_path}${f}${fe.reset}`)}else{let f=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`;console.log(`
|
|
373
|
+
${fe.yellow} \u26A0 Deploy [rsync]: ${f} \u2192 ${r}:${e.remote_path}${fe.reset}`)}if(e.deploy_script&&console.log(`${fe.yellow} Then run: ${e.deploy_script}${fe.reset}`),e.health_check&&console.log(`${fe.yellow} Health check: ${e.health_check}${fe.reset}`),!await Yt(" Proceed with deployment?"))return"CANCELLED: User declined."}let i="";if(o==="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}:
|
|
374
374
|
${p}${e.deploy_script?`
|
|
375
375
|
${e.deploy_script}`:""}`;let{stdout:h,stderr:m,exitCode:g,error:y}=await xt(s,p,{timeout:12e4});if(i=[h,m].filter(Boolean).join(`
|
|
376
376
|
`).trim(),g!==0)return`ERROR (git pull, exit ${g}):
|
|
@@ -394,7 +394,7 @@ Health check FAILED: ${d} \u2192 ${p.message}`,(o==="git"?"git pull OK":"rsync O
|
|
|
394
394
|
Health check FAILED (exit ${m}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+i+c+l;l=`
|
|
395
395
|
|
|
396
396
|
Health check: \u2713 ${g||"(exit 0)"}`}}let u=o==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${o}] ${u}
|
|
397
|
-
${i}${c}${l}`.trim()}case"deployment_status":{let o=
|
|
397
|
+
${i}${c}${l}`.trim()}case"deployment_status":{let o=W_(),s=e.config?[e.config]:Object.keys(o);if(s.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of s){let c=o[i];if(!c){r.push(`${i}: NOT FOUND`);continue}try{let l=Ft(c.server||i),d=(await xt(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",f="unknown";if(d&&c.deploy_script){let h=c.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(h)try{f=(await xt(l,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{f="inactive"}}let p="N/A";if(c.health_check){let h=c.health_check.trim();if(/^https?:\/\//.test(h))try{let m=require("node-fetch"),g=await Promise.race([m(h),new Promise((y,w)=>setTimeout(()=>w(new Error("timeout")),1e4))]);p=g.ok?"healthy":`HTTP ${g.status}`}catch(m){p=`unhealthy: ${m.message.substring(0,50)}`}else try{p=(await xt(l,h,{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:
|
|
398
398
|
${r.join(`
|
|
399
399
|
`)}`}case"frontend_recon":{let o=process.cwd(),s=(e.type||"").toLowerCase(),r=[],i=async(C,S=120)=>{try{let O=Ie.isAbsolute(C)?C:Ie.join(o,C),K=(await ze.readFile(O,"utf8")).split(`
|
|
400
400
|
`),V=K.slice(0,S).join(`
|
|
@@ -473,8 +473,8 @@ ${d}`:d||"(empty log)"}case"find_large":{let l=e.path||"/",u=e.limit||20,d=e.min
|
|
|
473
473
|
${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}
|
|
474
474
|
${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}
|
|
475
475
|
${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}
|
|
476
|
-
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=un(),s=o(e.type,e.name,e.content,e.description);return s.ok?s.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${s.path}`:`ERROR: ${s.error}`}case"delete_memory":{let{deleteMemory:o}=un();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=oi(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function
|
|
477
|
-
`)}function
|
|
476
|
+
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=un(),s=o(e.type,e.name,e.content,e.description);return s.ok?s.updated===!1?`Memory unchanged (duplicate): ${e.type}/${e.name}`:`Memory saved: ${e.type}/${e.name} \u2192 ${s.path}`:`ERROR: ${s.error}`}case"delete_memory":{let{deleteMemory:o}=un();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=oi(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function Z_(t,e,n={}){let{emit:o}=oi(),{logToolExecution:s}=Ic(),r=Date.now(),i=n.silent?null:I_(t,e);if(!i){let l=await nm(t,e,n);return s({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}let c=new L_(i);c.start();try{let l=await nm(t,e,n);return c.stop(),s({tool:t,args:e,result:l,duration:Date.now()-r,success:!l.startsWith?.("ERROR")}),await o("onToolResult",{tool:t,args:e,result:l}),l}catch(l){throw c.stop(),s({tool:t,args:e,result:l.message,duration:Date.now()-r,success:!1}),l}}rm.exports={TOOL_DEFINITIONS:V_,executeTool:Z_,resolvePath:vt,autoFixPath:Ai,autoFixEdit:om,enrichBashError:sm,cancelPendingAskUser:z_,setAskUserHandler:X_,fileExists:Ot}});var Gt=Q((cR,am)=>{am.exports=im()});var Wc=Q((uR,cm)=>{var{loadServerProfiles:Go,resolveProfile:lR,sshExec:Q_}=Ks(),Bc={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 ex(){let t=Go();if(Object.keys(t).length===0)return null;let n=["## Remote Servers (.nex/servers.json)"];n.push(""),n.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[s,r]of Object.entries(t)){let i=r.user?`${r.user}@${r.host}`:r.host,c=r.port&&Number(r.port)!==22?`:${r.port}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",u=r.sudo?", sudo available":"";n.push(`- **${s}**: ${i}${c}${l}${u}`)}let o=new Set;for(let s of Object.values(t))s.os&&Bc[s.os]&&o.add(s.os);if(o.size>0){n.push("");for(let s of o){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[s]||s;n.push(`### ${r} Notes`);for(let i of Bc[s])n.push(`- ${i}`)}}return n.join(`
|
|
477
|
+
`)}function tx(t){let e=Go();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function nx(){return Object.keys(Go())}function sx(){let t=require("fs"),n=require("path").join(process.cwd(),"NEX.md"),o="";try{o=t.readFileSync(n,"utf-8")}catch{}let s=Go(),r=Object.keys(s);if(r.length===0)return null;let i=["server","deploy","remote","ssh","service","systemctl","production","linux","almalinux","ubuntu","debian"],c=o.toLowerCase();if(!i.some(p=>c.includes(p)))return null;let u=r.map(p=>{let h=s[p],m=h.user?`${h.user}@${h.host}`:h.host,g=h.port&&Number(h.port)!==22?`:${h.port}`:"";return` - **${p}**: ${m}${g}${h.os?` (${h.os})`:""}`}).join(`
|
|
478
478
|
`),d=r.map(p=>s[p].log_path).filter(Boolean),f=d.length>0?`
|
|
479
479
|
- Server log paths: ${d.join(", ")}`:"";return`# Deployment Context (Auto-detected)
|
|
480
480
|
|
|
@@ -492,7 +492,7 @@ ${u}
|
|
|
492
492
|
- \u274C Do NOT \`read_file\` on paths like \`logs/\` \u2014 these files do not exist locally
|
|
493
493
|
- \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
|
|
494
494
|
|
|
495
|
-
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${
|
|
495
|
+
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.${ox(s)}`}function ox(t){return Object.values(t).some(n=>n.host==="94.130.37.43")?`
|
|
496
496
|
|
|
497
497
|
## Jarvis Debugging Rules
|
|
498
498
|
|
|
@@ -503,31 +503,31 @@ ${u}
|
|
|
503
503
|
- CRITICAL: When the user pastes a Jarvis error message ("jarvisFehler:", "jarvisEinige Fehler", 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.
|
|
504
504
|
- LOG FILES: Always check the CURRENT log first: /home/jarvis/jarvis-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.
|
|
505
505
|
- 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.
|
|
506
|
-
- 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
|
|
507
|
-
`+i.trim()}catch{return null}}cm.exports={getServerContext:
|
|
508
|
-
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function
|
|
509
|
-
`)}var Hc=new Map,Qs=new Map,Ni=null,
|
|
506
|
+
- 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 rx(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=Go();if(Object.keys(n).length===0)return null;let o=null,s=null;for(let[,i]of e){let c=i.toLowerCase().split(".");for(let[l,u]of Object.entries(n))if(c.includes(l.toLowerCase())){o=u,s=l;break}if(o)break;for(let[l,u]of Object.entries(n))if(u.host===i){o=u,s=l;break}if(o)break}if(!o||!s)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 Q_(o,r,{timeout:4e3});if(!i||i.trim().length<5)return null;let c=o.user?`${o.user}@${o.host}`:o.host;return`[Server context for "${s}" (${c}) \u2014 probed at task start]
|
|
507
|
+
`+i.trim()}catch{return null}}cm.exports={getServerContext:ex,getDeploymentContextBlock:sx,hasServerOS:tx,getProfileNames:nx,probeUrlServer:rx,OS_HINTS:Bc}});var Mi=Q((dR,dm)=>{var zt=require("fs").promises,lm=require("fs"),$t=require("path"),Oi=require("util").promisify(require("child_process").exec),{C:Zs}=Fe(),{getMergeConflicts:um}=Nn(),{getServerContext:ix}=Wc(),ax=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function cx(t){try{return lm.readFileSync(t,"utf-8").split(`
|
|
508
|
+
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function lx(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 ux(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=$t.join(t,".gitignore"),r=[...o,...cx(s)],i=0,c=[$t.basename(t)+"/"];function l(u,d,f){if(f>e||i>=n)return;let p;try{p=lm.readdirSync(u,{withFileTypes:!0})}catch{return}p.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let h=p.filter(m=>!(ax.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||lx(m.name,r)));for(let m=0;m<h.length;m++){if(i>=n){c.push(`${d}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[m],y=m===h.length-1,w=y?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",v=d+(y?" ":"\u2502 "),M=g.isDirectory()?g.name+"/":g.name;c.push(`${d}${w}${M}`),i++,g.isDirectory()&&l($t.join(u,g.name),v,f+1)}}return l(t,"",1),c.join(`
|
|
509
|
+
`)}var Hc=new Map,Qs=new Map,Ni=null,dx=3e4;async function Ln(t){try{return await t()}catch{return null}}async function fx(){if(!Ni||Date.now()>Ni)return!1;let t=[$t.join(process.cwd(),"package.json"),$t.join(process.cwd(),"README.md"),$t.join(process.cwd(),".gitignore")];for(let e of t)try{let n=await zt.stat(e),o=Qs.get(e);if(!o||n.mtimeMs!==o)return!1}catch{if(Qs.has(e))return!1}try{let e=$t.join(process.cwd(),".git","HEAD"),n=await zt.stat(e),o=Qs.get(e);if(!o||n.mtimeMs!==o)return!1}catch{}return!0}async function px(){let t=[$t.join(process.cwd(),"package.json"),$t.join(process.cwd(),"README.md"),$t.join(process.cwd(),".gitignore"),$t.join(process.cwd(),".git","HEAD")];for(let e of t)try{let n=await zt.stat(e);Qs.set(e,n.mtimeMs)}catch{Qs.delete(e)}}async function mx(t){let e="fileContext",n=Hc.get(e),o=!1;if(n&&await fx()&&(o=!0),!o){let u=[],d=$t.join(t,"package.json");if(await Ln(()=>zt.access(d).then(()=>!0).catch(()=>!1)))try{let y=await zt.readFile(d,"utf-8"),w=JSON.parse(y),v={name:w.name,version:w.version};w.scripts&&(v.scripts=Object.keys(w.scripts).slice(0,15)),w.dependencies&&(v.deps=Object.keys(w.dependencies).length),w.devDependencies&&(v.devDeps=Object.keys(w.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(v)}`)}catch{}let p=$t.join(t,"README.md");if(await Ln(()=>zt.access(p).then(()=>!0).catch(()=>!1))){let w=(await zt.readFile(p,"utf-8")).split(`
|
|
510
510
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
511
511
|
${w.join(`
|
|
512
512
|
`)}`)}let m=$t.join(t,".gitignore");if(await Ln(()=>zt.access(m).then(()=>!0).catch(()=>!1))){let y=await zt.readFile(m,"utf-8");u.push(`GITIGNORE:
|
|
513
513
|
${y.trim()}`)}n=u.join(`
|
|
514
514
|
|
|
515
|
-
`),Hc.set(e,n),Ni=Date.now()+
|
|
515
|
+
`),Hc.set(e,n),Ni=Date.now()+dx,await px()}let s=[n],[r,i,c,l]=await Promise.all([Ln(async()=>{let{stdout:u}=await Oi("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Ln(async()=>{let{stdout:u}=await Oi("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Ln(async()=>{let{stdout:u}=await Oi("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),um()]);if(r&&s.push(`GIT BRANCH: ${r}`),i&&s.push(`GIT STATUS:
|
|
516
516
|
${i}`),c&&s.push(`RECENT COMMITS:
|
|
517
517
|
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
518
518
|
`);s.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
519
|
-
${u}`)}try{let u=
|
|
519
|
+
${u}`)}try{let u=ix();u&&s.push(u)}catch{}return s.join(`
|
|
520
520
|
|
|
521
|
-
`)}async function mx(t){let e=$t.join(t,"package.json"),n="";if(await Ln(()=>zt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await zt.readFile(e,"utf-8"),c=JSON.parse(i);n=`${c.name||"?"} v${c.version||"?"}`}catch{}let[s,r]=await Promise.all([Ln(async()=>{let{stdout:i}=await Oi("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),um()]);if(r&&r.length>0){console.log(`${Zs.red} \u26A0 ${r.length} unresolved merge conflict(s):${Zs.reset}`);for(let i of r)console.log(`${Zs.red} ${i.file}${Zs.reset}`);console.log(`${Zs.yellow} \u2192 Resolve conflicts before starting tasks${Zs.reset}`)}console.log()}dm.exports={gatherProjectContext:px,printContext:mx,generateFileTree:lx,_clearContextCache:()=>{Hc.clear(),Qs.clear(),Ni=null}}});var Jt=Q((dR,mm)=>{var Xt=require("fs"),Pi=require("path"),{atomicWrite:hx}=An();function zo(){return Pi.join(process.cwd(),".nex","sessions")}function Kc(){let t=zo();Xt.existsSync(t)||Xt.mkdirSync(t,{recursive:!0})}function Gc(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Pi.join(zo(),`${e}.json`)}function Yc(t,e,n={}){Kc();let o=Gc(t),s={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return hx(o,JSON.stringify(s,null,2)),{path:o,name:t}}function fm(t){let e=Gc(t);if(!Xt.existsSync(e))return null;try{return JSON.parse(Xt.readFileSync(e,"utf-8"))}catch{return null}}function pm(){Kc();let t=zo(),e=Xt.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(Xt.readFileSync(Pi.join(t,o),"utf-8"));n.push({name:s.name||o.replace(".json",""),createdAt:s.createdAt,updatedAt:s.updatedAt,messageCount:s.messageCount||0,model:s.model,provider:s.provider,score:s.score!=null?s.score:null,scoreGrade:s.scoreGrade||null})}catch{}return n.sort((o,s)=>(s.updatedAt||"").localeCompare(o.updatedAt||""))}function gx(t){let e=Gc(t);return Xt.existsSync(e)?(Xt.unlinkSync(e),!0):!1}function $x(){let t=pm();return t.length===0?null:fm(t[0].name)}var cs=null,xn=null,Yo=null;function yx(t,e={}){t.length!==0&&(cs&&clearTimeout(cs),xn=t,Yo=e||{},cs=setTimeout(()=>{xn&&xn.length>0&&Yc("_autosave",xn,Yo),cs=null,xn=null,Yo=null},5e3))}function wx(){cs&&(clearTimeout(cs),cs=null),xn&&xn.length>0&&(Yc("_autosave",xn,Yo),xn=null,Yo=null)}function bx(){Kc();let t=zo(),e=Xt.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,o=new Date(n.getTime()-720*60*60*1e3),s=0;for(let r of e){let i=Pi.join(t,r);try{let c=Xt.statSync(i);new Date(c.mtime)<o&&(Xt.unlinkSync(i),s++)}catch{}}return s}mm.exports={saveSession:Yc,loadSession:fm,listSessions:pm,deleteSession:gx,getLastSession:$x,autoSave:yx,flushAutoSave:wx,clearOldSessions:bx,_getSessionsDir:zo}});var Li=Q((fR,xm)=>{"use strict";var Xo=require("fs"),hm=require("path");function gm(t){let e=[];return t.forEach((n,o)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_use"&&e.push({name:s.name||"",input:s.input||{},index:o,id:s.id||null})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(s=>{let r=s.function?.name||s.name||"",i={};try{i=typeof s.function?.arguments=="string"?JSON.parse(s.function.arguments):s.function?.arguments||s.input||{}}catch{}e.push({name:r,input:i,index:o,id:s.id||null})}))}),e}function _x(t){let e=new Set;return t.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&e.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_result"&&o.tool_use_id&&typeof o.content=="string"&&o.content.startsWith("BLOCKED:")&&e.add(o.tool_use_id)})}),e}function $m(t){let e=[];return t.forEach((n,o)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{if(s&&s.type==="tool_result"){let r=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(s.content||"");e.push({content:r,index:o})}}),n.role==="tool"){let s=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:s,index:o})}}),e}function ym(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let o=n.content.filter(s=>s&&(s.type==="text"||typeof s=="string")).map(s=>typeof s=="string"?s:s.text||"").join("").trim();if(o)return o}}}return""}function wm(t,e){let n=[];for(let o=t.length-1;o>=0&&n.length<e;o--){let s=t[o];if(s.role!=="assistant")continue;let r="";typeof s.content=="string"?r=s.content.trim():Array.isArray(s.content)&&(r=s.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function bm(t){let e=new Map;for(let n of t){let o;try{o=JSON.stringify(n.input)}catch{o=String(n.input)}let s=`${n.name}|${o}`;e.set(s,(e.get(s)||0)+1)}return e}function _m(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,n=[],o=gm(t),s=$m(t),r=o.length,i=_x(t),c=o.filter(k=>!k.id||!i.has(k.id));t.some(k=>k.role==="user"&&typeof k.content=="string"&&k.content.startsWith("[SYSTEM WARNING]")&&(k.content.includes("edited")||k.content.includes("bash command")||k.content.includes("grep pattern")||k.content.includes("re-read")||k.content.includes("already in your context")))&&(e-=2,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let u=o.find(k=>{let j=k.input?.command||k.input?.cmd||"";return/\bsed\s+-n\b/.test(j)});if(u){let k=(u.input?.command||u.input?.cmd||"").slice(0,80);s.some(x=>x.content.includes("BLOCKED: sed -n is forbidden")||x.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${k}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${k}`))}o.find(k=>{if(k.name!=="grep"&&k.name!=="bash"&&k.name!=="ssh_exec")return!1;let j=k.input?.command||k.input?.cmd||"",x=k.input?.pattern||"",E=`${j} ${x}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(E)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(E)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let f=t.some(k=>k.role==="assistant"),p=ym(t),m=wm(t,3).some(k=>k.length>100&&!/^[^.!]{0,40}\?$/.test(k));if(f&&!m&&(p.length<80||/^[^.!]{0,40}\?$/.test(p))){e-=2;let k=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: ${k}`)}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(k=>{let j=typeof k.content=="string"?k.content:Array.isArray(k.content)?k.content.map(x=>typeof x=="string"?x:x.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(j)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let w=bm(c),v=0,M="";for(let[k,j]of w)j>v&&(v=j,M=k);if(v>=3){let[k]=M.split("|");e-=1,n.push(`Same tool call repeated ${v}\xD7 (tool: ${k})`)}let C=!1,S=t.findIndex(k=>k.role==="user"&&typeof k.content=="string"&&k.content.includes("[SYSTEM STOP]")&&k.content.includes('"valid":true'));S>=0&&o.filter(j=>j.index>S).length>0&&(C=!0),C&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let O=o.filter(k=>k.name==="ssh_exec");if(O.length>=8){let k=0,j=1;for(let x=1;x<O.length;x++)O[x].index<=O[x-1].index+2?j++:(k=Math.max(k,j),j=1);k=Math.max(k,j),k>=8&&(e-=.5,n.push(`SSH reconnect storm: ${k} consecutive SSH calls`))}f&&O.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 D=new Map;for(let k of c)if(k.name==="read_file"&&k.input?.path){let j=k.input.path;D.has(j)||D.set(j,{count:0,ranges:[]});let x=D.get(j);if(x.count++,k.input.line_start!=null){let E=k.input.line_start||1,A=k.input.line_end||E+350;x.ranges.push([E,A])}}function K(k,j,x){for(let[E,A]of x){let T=Math.max(k,E),L=Math.min(j,A);if(L>T){let ie=L-T,se=j-k||1;if(ie/se>=.7)return!0}}return!1}let V=0,X="";for(let[k,j]of D){if(j.count<3)continue;if(j.ranges.length===j.count){let A=!1,T=[];for(let[L,ie]of j.ranges){if(T.length>0&&K(L,ie,T)){A=!0;break}T.push([L,ie])}if(!A)continue}if(j.count-j.ranges.length<=2&&j.ranges.length>=1){let A=!1,T=[];for(let[L,ie]of j.ranges){if(T.length>0&&K(L,ie,T)){A=!0;break}T.push([L,ie])}if(!A)continue}j.count>V&&(V=j.count,X=k)}if(V>=3){e-=1;let k=X.split("/").slice(-2).join("/");n.push(`read_file loop: "${k}" read ${V}\xD7 (file already in context)`)}let B=0,R="";for(let[k,j]of D){if(j.ranges.length<4)continue;let x=[],E=!1;for(let[A,T]of j.ranges){if(x.length>0&&K(A,T,x)){E=!0;break}x.push([A,T])}!E&&j.ranges.length>B&&(B=j.ranges.length,R=k)}if(B>=4){e-=.5;let k=R.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${k}" read in ${B} sequential sections \u2014 use grep instead`)}let ye=new Map;for(let k of c)if(k.name==="grep"&&k.input?.path&&k.input?.pattern){let j=k.input.path;ye.has(j)||ye.set(j,new Set),ye.get(j).add(k.input.pattern)}let be=0,fe="";for(let[k,j]of ye)k.split("/").pop().includes(".")&&j.size>be&&(be=j.size,fe=k);if(be>=3){e-=.75;let k=fe.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${k}" searched ${be}\xD7 with different patterns (file already in context)`)}{let k=new Set,j=new Set,x=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let A of o){if(A.name==="write_file"&&A.input?.path){let T=A.input.path.split("/").pop(),L=A.input.path.includes("/tests/");x.test(T)&&!L&&k.add(A.input.path)}if((A.name==="bash"||A.name==="ssh_exec")&&A.input?.command){let T=A.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(T)for(let L of T){let ie=L.split(/\s+/),se=ie[ie.length-1];for(let ge of k)(ge.endsWith(se)||se.endsWith(ge.split("/").pop()))&&j.add(ge)}}}let E=j.size;if(E>=1){let A=Math.min(E*.25,.5);e-=A;let T=[...j].map(L=>L.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${T} \u2014 write inline logic or use tests/ instead`)}}let pe=s.filter(k=>k.content.startsWith("EXIT")).length;pe>=10?(e-=1,n.push(`Bash exit-error storm: ${pe} tool results started with EXIT (repeated failing commands)`)):pe>=5&&(e-=.5,n.push(`Repeated bash errors: ${pe} tool results with non-zero exit code`));for(let k of t){if(k.role!=="assistant")continue;let j="";if(typeof k.content=="string"?j=k.content:Array.isArray(k.content)&&(j=k.content.filter(se=>se&&(se.type==="text"||typeof se=="string")).map(se=>typeof se=="string"?se:se.text||"").join("")),j.length<=5e3)continue;let x=j.split(/(?<=\. )/).filter(se=>se.trim().length>0);if(x.length<6)continue;let E=new Map;for(let se=0;se<=x.length-3;se++){let ge=x.slice(se,se+3).join("").trim();ge.length>30&&E.set(ge,(E.get(ge)||0)+1)}let A=0,T="";for(let[se,ge]of E)ge>A&&(A=ge,T=se);if(A<3)continue;let ie=T.length*A/j.length;if(ie>=.4||A>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${A}\xD7 same paragraph, ${Math.round(ie*100)}% repeated)`);break}}{let k=new Set(["read_file","list_directory","search_files","glob","grep"]),j=t.some(E=>Array.isArray(E.tool_calls)?E.tool_calls.some(A=>k.has(A.function?.name)):Array.isArray(E.content)?E.content.some(A=>A.type==="tool_use"&&k.has(A.name)):!1);t.some(E=>E.role==="assistant"&&typeof E.content=="string"&&(E.content.includes("## Steps")||E.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 xe=s.filter(k=>k.content.startsWith("BLOCKED:")&&!k.content.includes("BLOCKED: sed -n")&&!k.content.includes("SSH paused")&&!k.content.includes("SSH temporarily paused"));if(xe.length>0){let k=Math.min(xe.length*.5,1.5);e-=k,n.push(`${xe.length} tool call${xe.length===1?"":"s"} blocked (agent attempted denied actions)`)}let me=t.filter(k=>{let j=typeof k.content=="string"?k.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(j)}).length;if(me>0){let k=Math.min(me*1,2);e-=k,n.push(`Super-nuclear context wipe fired ${me}\xD7 (context collapse \u2014 task too large or read loops)`)}{let k=!1,j=!1,x=!1;for(let A of o){if(A.name!=="bash")continue;let T=(A.input?.command||A.input?.cmd||"").trim();!(/cat\s*>/.test(T)||/<</.test(T))&&/\bcat\s+\S/.test(T)&&(k=!0),/^\s*ls(\s|$)/.test(T)&&!/npm|yarn|pnpm|make|git\b/.test(T)&&(j=!0),/\bfind\s+\S/.test(T)&&!/git\b|npm\b|-exec\b/.test(T)&&(x=!0)}let E=[k,j,x].filter(Boolean).length;if(E>0){let A=Math.min(E*.25,.75);e-=A;let T=[];k&&T.push("cat (use read_file)"),j&&T.push("ls (use list_directory)"),x&&T.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${T.join(", ")}`)}}{let k=o.some(T=>(T.name==="write_file"||T.name==="Write")&&T.input?.path&&(T.input.path.endsWith("requirements.txt")||T.input.path.endsWith("Pipfile")||T.input.path.endsWith("pyproject.toml"))),j=o.some(T=>(T.name==="write_file"||T.name==="Write")&&T.input?.path&&T.input.path.endsWith("package.json")),x=o.filter(T=>(T.name==="bash"||T.name==="Bash")&&T.input?.command).map(T=>T.input.command),E=x.some(T=>/pip\s+install|python\s+-m\s+venv/.test(T)),A=x.some(T=>/npm\s+install/.test(T));k&&!E?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):j&&!A&&o.some(L=>(L.name==="write_file"||L.name==="Write")&&L.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(L.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(f){let k=t.find(T=>T.role==="assistant"),j="";k&&(typeof k.content=="string"?j=k.content:Array.isArray(k.content)&&(j=k.content.filter(T=>T&&(T.type==="text"||typeof T=="string")).map(T=>typeof T=="string"?T:T.text||"").join("")));let x=j.slice(0,400),E=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,A=x.split(`
|
|
521
|
+
`)}async function hx(t){let e=$t.join(t,"package.json"),n="";if(await Ln(()=>zt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await zt.readFile(e,"utf-8"),c=JSON.parse(i);n=`${c.name||"?"} v${c.version||"?"}`}catch{}let[s,r]=await Promise.all([Ln(async()=>{let{stdout:i}=await Oi("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),um()]);if(r&&r.length>0){console.log(`${Zs.red} \u26A0 ${r.length} unresolved merge conflict(s):${Zs.reset}`);for(let i of r)console.log(`${Zs.red} ${i.file}${Zs.reset}`);console.log(`${Zs.yellow} \u2192 Resolve conflicts before starting tasks${Zs.reset}`)}console.log()}dm.exports={gatherProjectContext:mx,printContext:hx,generateFileTree:ux,_clearContextCache:()=>{Hc.clear(),Qs.clear(),Ni=null}}});var Jt=Q((fR,mm)=>{var Xt=require("fs"),Pi=require("path"),{atomicWrite:gx}=An();function zo(){return Pi.join(process.cwd(),".nex","sessions")}function Kc(){let t=zo();Xt.existsSync(t)||Xt.mkdirSync(t,{recursive:!0})}function Gc(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Pi.join(zo(),`${e}.json`)}function Yc(t,e,n={}){Kc();let o=Gc(t),s={name:t,createdAt:n.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:n.model||null,provider:n.provider||null,messages:e};return gx(o,JSON.stringify(s,null,2)),{path:o,name:t}}function fm(t){let e=Gc(t);if(!Xt.existsSync(e))return null;try{return JSON.parse(Xt.readFileSync(e,"utf-8"))}catch{return null}}function pm(){Kc();let t=zo(),e=Xt.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(Xt.readFileSync(Pi.join(t,o),"utf-8"));n.push({name:s.name||o.replace(".json",""),createdAt:s.createdAt,updatedAt:s.updatedAt,messageCount:s.messageCount||0,model:s.model,provider:s.provider,score:s.score!=null?s.score:null,scoreGrade:s.scoreGrade||null})}catch{}return n.sort((o,s)=>(s.updatedAt||"").localeCompare(o.updatedAt||""))}function $x(t){let e=Gc(t);return Xt.existsSync(e)?(Xt.unlinkSync(e),!0):!1}function yx(){let t=pm();return t.length===0?null:fm(t[0].name)}var cs=null,xn=null,Yo=null;function wx(t,e={}){t.length!==0&&(cs&&clearTimeout(cs),xn=t,Yo=e||{},cs=setTimeout(()=>{xn&&xn.length>0&&Yc("_autosave",xn,Yo),cs=null,xn=null,Yo=null},5e3))}function bx(){cs&&(clearTimeout(cs),cs=null),xn&&xn.length>0&&(Yc("_autosave",xn,Yo),xn=null,Yo=null)}function _x(){Kc();let t=zo(),e=Xt.readdirSync(t).filter(r=>r.endsWith(".json")),n=new Date,o=new Date(n.getTime()-720*60*60*1e3),s=0;for(let r of e){let i=Pi.join(t,r);try{let c=Xt.statSync(i);new Date(c.mtime)<o&&(Xt.unlinkSync(i),s++)}catch{}}return s}mm.exports={saveSession:Yc,loadSession:fm,listSessions:pm,deleteSession:$x,getLastSession:yx,autoSave:wx,flushAutoSave:bx,clearOldSessions:_x,_getSessionsDir:zo}});var Li=Q((pR,xm)=>{"use strict";var Xo=require("fs"),hm=require("path");function gm(t){let e=[];return t.forEach((n,o)=>{n.role==="assistant"&&(Array.isArray(n.content)&&n.content.forEach(s=>{s&&s.type==="tool_use"&&e.push({name:s.name||"",input:s.input||{},index:o,id:s.id||null})}),Array.isArray(n.tool_calls)&&n.tool_calls.forEach(s=>{let r=s.function?.name||s.name||"",i={};try{i=typeof s.function?.arguments=="string"?JSON.parse(s.function.arguments):s.function?.arguments||s.input||{}}catch{}e.push({name:r,input:i,index:o,id:s.id||null})}))}),e}function xx(t){let e=new Set;return t.forEach(n=>{n.role==="tool"&&typeof n.content=="string"&&n.content.startsWith("BLOCKED:")&&n.tool_call_id&&e.add(n.tool_call_id),n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(o=>{o&&o.type==="tool_result"&&o.tool_use_id&&typeof o.content=="string"&&o.content.startsWith("BLOCKED:")&&e.add(o.tool_use_id)})}),e}function $m(t){let e=[];return t.forEach((n,o)=>{if(n.role==="user"&&Array.isArray(n.content)&&n.content.forEach(s=>{if(s&&s.type==="tool_result"){let r=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(i=>typeof i=="string"?i:i.text||"").join(""):JSON.stringify(s.content||"");e.push({content:r,index:o})}}),n.role==="tool"){let s=typeof n.content=="string"?n.content:JSON.stringify(n.content||"");e.push({content:s,index:o})}}),e}function ym(t){for(let e=t.length-1;e>=0;e--){let n=t[e];if(n.role==="assistant"){if(typeof n.content=="string")return n.content.trim();if(Array.isArray(n.content)){let o=n.content.filter(s=>s&&(s.type==="text"||typeof s=="string")).map(s=>typeof s=="string"?s:s.text||"").join("").trim();if(o)return o}}}return""}function wm(t,e){let n=[];for(let o=t.length-1;o>=0&&n.length<e;o--){let s=t[o];if(s.role!=="assistant")continue;let r="";typeof s.content=="string"?r=s.content.trim():Array.isArray(s.content)&&(r=s.content.filter(i=>i&&(i.type==="text"||typeof i=="string")).map(i=>typeof i=="string"?i:i.text||"").join("").trim()),r&&n.push(r)}return n}function bm(t){let e=new Map;for(let n of t){let o;try{o=JSON.stringify(n.input)}catch{o=String(n.input)}let s=`${n.name}|${o}`;e.set(s,(e.get(s)||0)+1)}return e}function _m(t){if(!Array.isArray(t)||t.length===0)return{score:0,issues:["Empty or invalid session \u2014 no messages to analyse"],summary:"No messages found"};let e=10,n=[],o=gm(t),s=$m(t),r=o.length,i=xx(t),c=o.filter(k=>!k.id||!i.has(k.id));t.some(k=>k.role==="user"&&typeof k.content=="string"&&k.content.startsWith("[SYSTEM WARNING]")&&(k.content.includes("edited")||k.content.includes("bash command")||k.content.includes("grep pattern")||k.content.includes("re-read")||k.content.includes("already in your context")))&&(e-=2,n.push("Loop-warning was fired during session (repeated file edits, bash commands, or re-reads)"));let u=o.find(k=>{let j=k.input?.command||k.input?.cmd||"";return/\bsed\s+-n\b/.test(j)});if(u){let k=(u.input?.command||u.input?.cmd||"").slice(0,80);s.some(x=>x.content.includes("BLOCKED: sed -n is forbidden")||x.content.includes("BLOCKED: sed -n"))?(e-=.25,n.push(`sed -n attempted but blocked by agent guard: ${k}`)):(e-=1.5,n.push(`sed -n anti-pattern used: ${k}`))}o.find(k=>{if(k.name!=="grep"&&k.name!=="bash"&&k.name!=="ssh_exec")return!1;let j=k.input?.command||k.input?.cmd||"",x=k.input?.pattern||"",E=`${j} ${x}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(E)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(E)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let f=t.some(k=>k.role==="assistant"),p=ym(t),m=wm(t,3).some(k=>k.length>100&&!/^[^.!]{0,40}\?$/.test(k));if(f&&!m&&(p.length<80||/^[^.!]{0,40}\?$/.test(p))){e-=2;let k=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: ${k}`)}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(k=>{let j=typeof k.content=="string"?k.content:Array.isArray(k.content)?k.content.map(x=>typeof x=="string"?x:x.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(j)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let w=bm(c),v=0,M="";for(let[k,j]of w)j>v&&(v=j,M=k);if(v>=3){let[k]=M.split("|");e-=1,n.push(`Same tool call repeated ${v}\xD7 (tool: ${k})`)}let C=!1,S=t.findIndex(k=>k.role==="user"&&typeof k.content=="string"&&k.content.includes("[SYSTEM STOP]")&&k.content.includes('"valid":true'));S>=0&&o.filter(j=>j.index>S).length>0&&(C=!0),C&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let O=o.filter(k=>k.name==="ssh_exec");if(O.length>=8){let k=0,j=1;for(let x=1;x<O.length;x++)O[x].index<=O[x-1].index+2?j++:(k=Math.max(k,j),j=1);k=Math.max(k,j),k>=8&&(e-=.5,n.push(`SSH reconnect storm: ${k} consecutive SSH calls`))}f&&O.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 D=new Map;for(let k of c)if(k.name==="read_file"&&k.input?.path){let j=k.input.path;D.has(j)||D.set(j,{count:0,ranges:[]});let x=D.get(j);if(x.count++,k.input.line_start!=null){let E=k.input.line_start||1,A=k.input.line_end||E+350;x.ranges.push([E,A])}}function K(k,j,x){for(let[E,A]of x){let T=Math.max(k,E),L=Math.min(j,A);if(L>T){let ae=L-T,se=j-k||1;if(ae/se>=.7)return!0}}return!1}let V=0,X="";for(let[k,j]of D){if(j.count<3)continue;if(j.ranges.length===j.count){let A=!1,T=[];for(let[L,ae]of j.ranges){if(T.length>0&&K(L,ae,T)){A=!0;break}T.push([L,ae])}if(!A)continue}if(j.count-j.ranges.length<=2&&j.ranges.length>=1){let A=!1,T=[];for(let[L,ae]of j.ranges){if(T.length>0&&K(L,ae,T)){A=!0;break}T.push([L,ae])}if(!A)continue}j.count>V&&(V=j.count,X=k)}if(V>=3){e-=1;let k=X.split("/").slice(-2).join("/");n.push(`read_file loop: "${k}" read ${V}\xD7 (file already in context)`)}let B=0,R="";for(let[k,j]of D){if(j.ranges.length<4)continue;let x=[],E=!1;for(let[A,T]of j.ranges){if(x.length>0&&K(A,T,x)){E=!0;break}x.push([A,T])}!E&&j.ranges.length>B&&(B=j.ranges.length,R=k)}if(B>=4){e-=.5;let k=R.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${k}" read in ${B} sequential sections \u2014 use grep instead`)}let ye=new Map;for(let k of c)if(k.name==="grep"&&k.input?.path&&k.input?.pattern){let j=k.input.path;ye.has(j)||ye.set(j,new Set),ye.get(j).add(k.input.pattern)}let be=0,pe="";for(let[k,j]of ye)k.split("/").pop().includes(".")&&j.size>be&&(be=j.size,pe=k);if(be>=3){e-=.75;let k=pe.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${k}" searched ${be}\xD7 with different patterns (file already in context)`)}{let k=new Set,j=new Set,x=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let A of o){if(A.name==="write_file"&&A.input?.path){let T=A.input.path.split("/").pop(),L=A.input.path.includes("/tests/");x.test(T)&&!L&&k.add(A.input.path)}if((A.name==="bash"||A.name==="ssh_exec")&&A.input?.command){let T=A.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(T)for(let L of T){let ae=L.split(/\s+/),se=ae[ae.length-1];for(let ie of k)(ie.endsWith(se)||se.endsWith(ie.split("/").pop()))&&j.add(ie)}}}let E=j.size;if(E>=1){let A=Math.min(E*.25,.5);e-=A;let T=[...j].map(L=>L.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${T} \u2014 write inline logic or use tests/ instead`)}}let me=s.filter(k=>k.content.startsWith("EXIT")).length;me>=10?(e-=1,n.push(`Bash exit-error storm: ${me} tool results started with EXIT (repeated failing commands)`)):me>=5&&(e-=.5,n.push(`Repeated bash errors: ${me} tool results with non-zero exit code`));for(let k of t){if(k.role!=="assistant")continue;let j="";if(typeof k.content=="string"?j=k.content:Array.isArray(k.content)&&(j=k.content.filter(se=>se&&(se.type==="text"||typeof se=="string")).map(se=>typeof se=="string"?se:se.text||"").join("")),j.length<=5e3)continue;let x=j.split(/(?<=\. )/).filter(se=>se.trim().length>0);if(x.length<6)continue;let E=new Map;for(let se=0;se<=x.length-3;se++){let ie=x.slice(se,se+3).join("").trim();ie.length>30&&E.set(ie,(E.get(ie)||0)+1)}let A=0,T="";for(let[se,ie]of E)ie>A&&(A=ie,T=se);if(A<3)continue;let ae=T.length*A/j.length;if(ae>=.4||A>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${A}\xD7 same paragraph, ${Math.round(ae*100)}% repeated)`);break}}{let k=new Set(["read_file","list_directory","search_files","glob","grep"]),j=t.some(E=>Array.isArray(E.tool_calls)?E.tool_calls.some(A=>k.has(A.function?.name)):Array.isArray(E.content)?E.content.some(A=>A.type==="tool_use"&&k.has(A.name)):!1);t.some(E=>E.role==="assistant"&&typeof E.content=="string"&&(E.content.includes("## Steps")||E.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 xe=s.filter(k=>k.content.startsWith("BLOCKED:")&&!k.content.includes("BLOCKED: sed -n")&&!k.content.includes("SSH paused")&&!k.content.includes("SSH temporarily paused"));if(xe.length>0){let k=Math.min(xe.length*.5,1.5);e-=k,n.push(`${xe.length} tool call${xe.length===1?"":"s"} blocked (agent attempted denied actions)`)}let he=t.filter(k=>{let j=typeof k.content=="string"?k.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(j)}).length;if(he>0){let k=Math.min(he*1,2);e-=k,n.push(`Super-nuclear context wipe fired ${he}\xD7 (context collapse \u2014 task too large or read loops)`)}{let k=!1,j=!1,x=!1;for(let A of o){if(A.name!=="bash")continue;let T=(A.input?.command||A.input?.cmd||"").trim();!(/cat\s*>/.test(T)||/<</.test(T))&&/\bcat\s+\S/.test(T)&&(k=!0),/^\s*ls(\s|$)/.test(T)&&!/npm|yarn|pnpm|make|git\b/.test(T)&&(j=!0),/\bfind\s+\S/.test(T)&&!/git\b|npm\b|-exec\b/.test(T)&&(x=!0)}let E=[k,j,x].filter(Boolean).length;if(E>0){let A=Math.min(E*.25,.75);e-=A;let T=[];k&&T.push("cat (use read_file)"),j&&T.push("ls (use list_directory)"),x&&T.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${T.join(", ")}`)}}{let k=o.some(T=>(T.name==="write_file"||T.name==="Write")&&T.input?.path&&(T.input.path.endsWith("requirements.txt")||T.input.path.endsWith("Pipfile")||T.input.path.endsWith("pyproject.toml"))),j=o.some(T=>(T.name==="write_file"||T.name==="Write")&&T.input?.path&&T.input.path.endsWith("package.json")),x=o.filter(T=>(T.name==="bash"||T.name==="Bash")&&T.input?.command).map(T=>T.input.command),E=x.some(T=>/pip\s+install|python\s+-m\s+venv/.test(T)),A=x.some(T=>/npm\s+install/.test(T));k&&!E?(e-=1,n.push("wrote requirements.txt but never ran pip install \u2014 environment not bootstrapped")):j&&!A&&o.some(L=>(L.name==="write_file"||L.name==="Write")&&L.input?.path&&/(\/src\/|index\.js|App\.js|main\.js)/.test(L.input.path))&&(e-=.75,n.push("created new React/Node project but never ran npm install \u2014 project is not runnable"))}if(f){let k=t.find(T=>T.role==="assistant"),j="";k&&(typeof k.content=="string"?j=k.content:Array.isArray(k.content)&&(j=k.content.filter(T=>T&&(T.type==="text"||typeof T=="string")).map(T=>typeof T=="string"?T:T.text||"").join("")));let x=j.slice(0,400),E=/^[\d\s\+\-\*\/×÷\(\)\.]+\s*=\s*[\d\s\+\-\*\/×÷\(\)\.]+[.\n]/m,A=x.split(`
|
|
522
522
|
`).find(T=>{let L=T.trim();return L.length>0&&L.length<=30&&/^\d/.test(L)&&/=/.test(L)&&!/[a-zA-Z]/.test(L)});if(E.test(x)||A){e-=1.5;let T=(A||x.split(`
|
|
523
|
-
`)[0]).trim().slice(0,40);n.push(`Thinking-chain leak: non-sequitur artifact at response start: "${T}"`)}}if(f&&r>0){let k=t.findIndex(x=>x.role==="assistant"),j=t.findIndex(x=>!!(Array.isArray(x.tool_calls)&&x.tool_calls.length>0||Array.isArray(x.content)&&x.content.some(E=>E&&E.type==="tool_use")));if(k!==-1&&j!==-1&&k<j){let x=t[k],E="";typeof x.content=="string"?E=x.content:Array.isArray(x.content)&&(E=x.content.filter(L=>L&&(L.type==="text"||typeof L=="string")).map(L=>typeof L=="string"?L:L.text||"").join(""));let A=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(E),T=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(E);(A||T)&&(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 k=p;if(k.length>100){let x=(k.match(/^```/gm)||[]).length%2!==0,E=/"\s*:\s*$/.test(k.trimEnd()),A=/[,\[{]\s*$/.test(k.trimEnd());(x||E||A)&&(e-=.75,n.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let k=[];t.forEach((x,E)=>{let A=[];Array.isArray(x.tool_calls)&&x.tool_calls.forEach(T=>{if((T.function?.name||T.name||"")==="read_file"){let
|
|
524
|
-
`).filter(T=>T.trim()).length<5&&/^\s*\[/.test(E)&&!/\]\s*$/.test(E.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 k=s.filter(j=>/argument errors?/i.test(j.content)||/missing required (argument|parameter)/i.test(j.content)||/invalid argument/i.test(j.content));k.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${k.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):k.length>=2&&(e-=.25,n.push(`Tool argument errors: ${k.length} tool calls returned argument errors`))}{let k=!1,j=0,x=0;for(let E of c){if((E.name==="bash"||E.name==="Bash")&&E.input?.command&&/git\s+commit\b/.test(E.input.command)){k&&(x=Math.max(x,j)),k=!0,j=0;continue}k&&(E.name==="bash"||E.name==="Bash")&&E.input?.command&&/git\s+(status|diff|log|show)\b/.test(E.input.command)&&j++}x=Math.max(x,j),x>=3&&(e-=.75,n.push(`Post-commit verification waste: ${x} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let
|
|
523
|
+
`)[0]).trim().slice(0,40);n.push(`Thinking-chain leak: non-sequitur artifact at response start: "${T}"`)}}if(f&&r>0){let k=t.findIndex(x=>x.role==="assistant"),j=t.findIndex(x=>!!(Array.isArray(x.tool_calls)&&x.tool_calls.length>0||Array.isArray(x.content)&&x.content.some(E=>E&&E.type==="tool_use")));if(k!==-1&&j!==-1&&k<j){let x=t[k],E="";typeof x.content=="string"?E=x.content:Array.isArray(x.content)&&(E=x.content.filter(L=>L&&(L.type==="text"||typeof L=="string")).map(L=>typeof L=="string"?L:L.text||"").join(""));let A=/ssh\s+\S+@\S+\s+"[^"]*\/[^"]*\./.test(E),T=/\/(?:home|var|etc|usr|opt|root|srv|data)\/[a-zA-Z0-9_.\-\/]+\.[a-zA-Z]{2,5}/.test(E);(A||T)&&(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 k=p;if(k.length>100){let x=(k.match(/^```/gm)||[]).length%2!==0,E=/"\s*:\s*$/.test(k.trimEnd()),A=/[,\[{]\s*$/.test(k.trimEnd());(x||E||A)&&(e-=.75,n.push("Truncated response: last assistant message ends mid-code-block or mid-JSON (model hit token limit)"))}}{let k=[];t.forEach((x,E)=>{let A=[];Array.isArray(x.tool_calls)&&x.tool_calls.forEach(T=>{if((T.function?.name||T.name||"")==="read_file"){let ae={};try{ae=typeof T.function?.arguments=="string"?JSON.parse(T.function.arguments):T.function?.arguments||{}}catch{}(ae.path||"").endsWith(".json")&&A.push({id:T.id,path:ae.path})}}),Array.isArray(x.content)&&x.content.forEach(T=>{T&&T.type==="tool_use"&&T.name==="read_file"&&(T.input?.path||"").endsWith(".json")&&A.push({id:T.id,path:T.input.path})}),A.forEach(T=>k.push({...T,msgIdx:E}))});let j=0;for(let x of k){let E=null;for(let T of t){if(T.role==="tool"&&T.tool_call_id===x.id&&typeof T.content=="string"){E=T.content;break}if(T.role==="user"&&Array.isArray(T.content)){let L=T.content.find(ae=>ae&&ae.type==="tool_result"&&ae.tool_use_id===x.id);if(L){E=typeof L.content=="string"?L.content:"";break}}}if(!E)continue;E.split(`
|
|
524
|
+
`).filter(T=>T.trim()).length<5&&/^\s*\[/.test(E)&&!/\]\s*$/.test(E.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 k=s.filter(j=>/argument errors?/i.test(j.content)||/missing required (argument|parameter)/i.test(j.content)||/invalid argument/i.test(j.content));k.length>=3?(e-=.75,n.push(`Repeated tool argument errors: ${k.length} tool calls returned argument errors \u2014 model couldn't correct its tool usage`)):k.length>=2&&(e-=.25,n.push(`Tool argument errors: ${k.length} tool calls returned argument errors`))}{let k=!1,j=0,x=0;for(let E of c){if((E.name==="bash"||E.name==="Bash")&&E.input?.command&&/git\s+commit\b/.test(E.input.command)){k&&(x=Math.max(x,j)),k=!0,j=0;continue}k&&(E.name==="bash"||E.name==="Bash")&&E.input?.command&&/git\s+(status|diff|log|show)\b/.test(E.input.command)&&j++}x=Math.max(x,j),x>=3&&(e-=.75,n.push(`Post-commit verification waste: ${x} git status/diff/log calls after commit`))}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let ge=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:ge,issues:n,summary:Re}}function vx(t){try{let{loadSession:e}=Jt(),n=e(t);return n?_m(n.messages||[]):null}catch{return null}}function kx(t,e=null){let{score:n,issues:o}=t,s=e?.dim||"",r=e?.reset||"",i=e?.yellow||"";if(n>=8||o.length===0)return"";let c=o.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})`),`
|
|
525
525
|
${s}${p}${r}`}let l="";for(let d of c.slice(0,4))l+=`
|
|
526
526
|
${i}\u26A0${r} ${s}${d}${r}`;let u=c.length-4;return u>0&&(l+=`
|
|
527
|
-
${s}(+${u} more)${r}`),l}function
|
|
527
|
+
${s}(+${u} more)${r}`),l}function Sx(t,e={}){try{let n=hm.join(process.cwd(),".nex");Xo.existsSync(n)||Xo.mkdirSync(n,{recursive:!0});let o=hm.join(n,"benchmark-history.json"),s=[];if(Xo.existsSync(o))try{s=JSON.parse(Xo.readFileSync(o,"utf-8"))}catch{s=[]}Array.isArray(s)||(s=[]);let r=t>=9?"A":t>=8?"B":t>=7?"C":t>=6?"D":"F",i={date:new Date().toISOString(),version:e.version||null,model:e.model||null,score:t,grade:r,sessionName:e.sessionName||null,issues:Array.isArray(e.issues)?e.issues:[]};s.push(i),s.length>100&&(s=s.slice(s.length-100)),Xo.writeFileSync(o,JSON.stringify(s,null,2))}catch{}}xm.exports={scoreMessages:_m,scoreSession:vx,formatScore:kx,appendScoreHistory:Sx,_extractToolCalls:gm,_extractToolResults:$m,_getLastAssistantText:ym,_getLastNAssistantTexts:wm,_countDuplicateToolCalls:bm}});var In=Q((mR,Rm)=>{"use strict";var Ex=require("os"),vm=require("path"),Jo=require("fs"),Vo=vm.join(Ex.homedir(),".nex-code","model-routing.json"),Ii={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}},km=["agentic","frontend","sysadmin","data","coding"];function Tx(t){if(!t||t.length<8)return null;for(let e of km){let n=Ii[e];if(!n.pattern||n.pattern.test(t))return n}return Ii.coding}function Zo(){try{if(Jo.existsSync(Vo))return JSON.parse(Jo.readFileSync(Vo,"utf-8"))}catch{}return{}}function Sm(t){let e=Ii[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:Zo()[t]||null}var Em={plan:10,implement:35,verify:8},zc={plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function Tm(){let t=Zo();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=je();if(e()==="ollama")return zc}catch{}return process.env.NEX_PHASE_ROUTING==="1"?zc:null}function Rx(t,e){let n=Tm();return n?.[t]?n[t]:e?Sm(e):null}function Cx(t){return Zo().phaseBudgets?.[t]||Em[t]||20}function Ax(){return process.env.NEX_PHASE_ROUTING==="0"?!1:Tm()!==null}function Ox(t){let e=vm.dirname(Vo);Jo.existsSync(e)||Jo.mkdirSync(e,{recursive:!0});let n=Zo(),o={...n,...t};!t.phases&&n.phases&&(o.phases=n.phases),!t.phaseBudgets&&n.phaseBudgets&&(o.phaseBudgets=n.phaseBudgets),Jo.writeFileSync(Vo,JSON.stringify(o,null,2))}Rm.exports={CATEGORIES:Ii,DETECTION_ORDER:km,detectCategory:Tx,getModelForCategory:Sm,getModelForPhase:Rx,getPhaseBudget:Cx,isPhaseRoutingEnabled:Ax,DEFAULT_PHASE_BUDGETS:Em,BUILTIN_PHASE_DEFAULTS:zc,saveRoutingConfig:Ox,loadRoutingConfig:Zo,ROUTING_CONFIG_PATH:Vo}});var Nm=Q((hR,Om)=>{"use strict";var ls=require("fs"),Qo=require("path"),Nx=require("os"),{detectCategory:Mx}=In(),eo=Qo.join(Nx.homedir(),".nex-code","examples"),Xc=Qo.join(__dirname,"..","examples");function Cm(t){try{let n=ls.readFileSync(t,"utf-8").replace(/<!--[\s\S]*?-->/g,"").trim(),o=n.match(/^user:\s*(.+)$/m);if(!o)return null;let s=o[1].trim(),r=n.indexOf(`
|
|
528
528
|
A: |`);if(r===-1)return null;let i=n.slice(r+5),c=[],l=0;for(let d of i.split(`
|
|
529
529
|
`))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(`
|
|
530
|
-
`).trim();return{user:s,assistant:u}}catch{return null}}function Am(t){let e=`${t}.md`,n=Qo.join(eo,e);if(ls.existsSync(n)){let s=Cm(n);if(s)return s}let o=Qo.join(Xc,e);return ls.existsSync(o)?Cm(o):null}function
|
|
530
|
+
`).trim();return{user:s,assistant:u}}catch{return null}}function Am(t){let e=`${t}.md`,n=Qo.join(eo,e);if(ls.existsSync(n)){let s=Cm(n);if(s)return s}let o=Qo.join(Xc,e);return ls.existsSync(o)?Cm(o):null}function Px(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=Mx(t);return e?Am(e.id):null}function Lx(){let t=new Set;for(let e of[eo,Xc])try{for(let n of ls.readdirSync(e))n.endsWith(".md")&&t.add(n.replace(".md",""))}catch{}return[...t].sort()}function Ix(t,e){ls.existsSync(eo)||ls.mkdirSync(eo,{recursive:!0});let n=`<!-- Auto-extracted from high-scoring session \u2014 edit as needed -->
|
|
531
531
|
|
|
532
532
|
user: ${e.user}
|
|
533
533
|
|
|
@@ -535,10 +535,10 @@ A: |
|
|
|
535
535
|
${e.assistant.split(`
|
|
536
536
|
`).map(o=>` ${o}`).join(`
|
|
537
537
|
`)}
|
|
538
|
-
`;ls.writeFileSync(Qo.join(eo,`${t}.md`),n,"utf-8")}Om.exports={getFewShotForInput:
|
|
538
|
+
`;ls.writeFileSync(Qo.join(eo,`${t}.md`),n,"utf-8")}Om.exports={getFewShotForInput:Px,loadExampleForCategory:Am,listAvailableExamples:Lx,savePrivateExample:Ix,PRIVATE_EXAMPLES_DIR:eo,BUNDLED_EXAMPLES_DIR:Xc}});var tr=Q(($R,jm)=>{var Nt=require("fs"),to=require("path"),{C:gR}=Fe(),{atomicWrite:jx,withFileLockSync:Dx}=An(),ji={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"},no={...ji};function Mm(){let t=to.join(process.cwd(),".nex","config.json");if(Nt.existsSync(t))try{let e=JSON.parse(Nt.readFileSync(t,"utf-8"));e.permissions&&(no={...ji,...e.permissions})}catch{}}function qx(){let t=to.join(process.cwd(),".nex"),e=to.join(t,"config.json");Nt.existsSync(t)||Nt.mkdirSync(t,{recursive:!0}),Dx(e,()=>{let n={};if(Nt.existsSync(e))try{n=JSON.parse(Nt.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=no,jx(e,JSON.stringify(n,null,2))})}function Pm(t){return no[t]||"ask"}function Fx(t,e){return["allow","ask","deny"].includes(e)?(no[t]=e,!0):!1}function Ux(t){return Pm(t)}function Bx(){return Object.entries(no).map(([t,e])=>({tool:t,mode:e}))}function Wx(){no={...ji}}var er={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 Lm(){let t=to.join(process.cwd(),".nex","config.json");try{return Nt.existsSync(t)&&JSON.parse(Nt.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function Hx(t){let e=to.join(process.cwd(),".nex"),n=to.join(e,"config.json");Nt.existsSync(e)||Nt.mkdirSync(e,{recursive:!0});let o={};try{Nt.existsSync(n)&&(o=JSON.parse(Nt.readFileSync(n,"utf-8")))}catch{o={}}o.teamPermissions=t,Nt.writeFileSync(n,JSON.stringify(o,null,2),"utf-8")}function Im(){let t=Lm();if(!t)return er.admin;let e=t.role||"admin",n=er[e]||er.admin;return{...n,...t.overrides,blockedTools:[...n.blockedTools||[],...t.overrides?.blockedTools||[]]}}function Kx(t){let e=Im();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 Gx(){return Object.entries(er).map(([t,e])=>({name:t,description:e.description,toolCount:e.allowedTools?`${e.allowedTools.length} allowed`:"all allowed",blockedCount:e.blockedTools.length}))}Mm();jm.exports={getPermission:Pm,setPermission:Fx,checkPermission:Ux,listPermissions:Bx,loadPermissions:Mm,savePermissions:qx,resetPermissions:Wx,DEFAULT_PERMISSIONS:ji,PERMISSION_PRESETS:er,loadPresetConfig:Lm,savePresetConfig:Hx,getEffectivePreset:Im,isToolAllowed:Kx,listPresets:Gx}});var Vt=Q((wR,Bm)=>{var ds=require("fs"),Di=require("path"),yR=require("readline"),{C:Me}=Fe(),Oe=null,Vc=!1,Zc=null,Dm=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function qi(){return Di.join(process.cwd(),".nex","plans")}function qm(){let t=qi();ds.existsSync(t)||ds.mkdirSync(t,{recursive:!0})}function Yx(t,e=[]){return Oe={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()},Oe}function zx(){return Oe}function Xx(t){Vc=t}function Jx(){return Vc}function Vx(){return!Oe||Oe.status!=="draft"?!1:(Oe.status="approved",Oe.updatedAt=new Date().toISOString(),!0)}function Zx(){return!Oe||Oe.status!=="approved"?!1:(Oe.status="executing",!0)}function Jc(t,e){return!Oe||t<0||t>=Oe.steps.length?!1:(Oe.steps[t].status=e,Oe.updatedAt=new Date().toISOString(),Oe.steps.every(n=>n.status==="done"||n.status==="skipped")&&(Oe.status="completed"),!0)}function Qx(t){if(!t)return`${Me.dim}No active plan${Me.reset}`;let e={draft:`${Me.yellow}DRAFT${Me.reset}`,approved:`${Me.green}APPROVED${Me.reset}`,executing:`${Me.blue}EXECUTING${Me.reset}`,completed:`${Me.green}COMPLETED${Me.reset}`},n=[];n.push(`
|
|
539
539
|
${Me.bold}${Me.cyan}Plan: ${t.task}${Me.reset}`),n.push(`${Me.dim}Status: ${e[t.status]||t.status}${Me.reset}
|
|
540
540
|
`);for(let o=0;o<t.steps.length;o++){let s=t.steps[o],r;switch(s.status){case"done":r=`${Me.green}\u2713${Me.reset}`;break;case"in_progress":r=`${Me.blue}\u2192${Me.reset}`;break;case"skipped":r=`${Me.dim}\u25CB${Me.reset}`;break;default:r=`${Me.dim} ${Me.reset}`}n.push(` ${r} ${Me.bold}Step ${o+1}:${Me.reset} ${s.description}`),s.files.length>0&&n.push(` ${Me.dim}Files: ${s.files.join(", ")}${Me.reset}`)}return n.push(""),n.join(`
|
|
541
|
-
`)}function
|
|
541
|
+
`)}function ev(t){if(t||(t=Oe),!t)return null;qm();let e=Di.join(qi(),`${t.name}.json`);return ds.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function tv(t){let e=Di.join(qi(),`${t}.json`);if(!ds.existsSync(e))return null;try{let n=JSON.parse(ds.readFileSync(e,"utf-8"));return Oe=n,n}catch{return null}}function nv(){qm();let t=qi(),e=ds.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(ds.readFileSync(Di.join(t,o),"utf-8"));n.push({name:s.name,task:s.task,status:s.status,steps:s.steps?s.steps.length:0,createdAt:s.createdAt})}catch{}return n.sort((o,s)=>(s.createdAt||"").localeCompare(o.createdAt||""))}function sv(t){if(!t)return[];let e=[],n=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),o=n?n[1]:t,s=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=s.exec(o))!==null;){let 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 ov(t){Zc=t}function rv(){return Zc}function iv(){Oe=null,Vc=!1,Zc=null,uv()}function av(){return`
|
|
542
542
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
543
543
|
|
|
544
544
|
# Allowed Tools (read-only)
|
|
@@ -586,12 +586,12 @@ Bullet list of potential issues and mitigations.
|
|
|
586
586
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
587
587
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
588
588
|
- Do NOT make any file changes \u2014 your role is analysis and planning only.
|
|
589
|
-
- 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 us=0;function
|
|
589
|
+
- 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 us=0;function cv(){!Oe||Oe.status!=="executing"||(us>0&&Jc(us-1,"done"),us<Oe.steps.length&&(Jc(us,"in_progress"),us++))}function lv(){if(!Oe||Oe.status!=="executing"||Oe.steps.length===0)return null;let t=Math.min(us,Oe.steps.length),e=Oe.steps.length,n=Math.max(0,t-1),o=Oe.steps[n]?.description||"";return{current:t,total:e,description:o}}function uv(){us=0}var Fm=["interactive","semi-auto","autonomous"],Um="interactive";function dv(t){return Fm.includes(t)?(Um=t,!0):!1}function fv(){return Um}Bm.exports={createPlan:Yx,getActivePlan:zx,setPlanMode:Xx,isPlanMode:Jx,approvePlan:Vx,startExecution:Zx,updateStep:Jc,formatPlan:Qx,savePlan:ev,loadPlan:tv,listPlans:nv,clearPlan:iv,getPlanModePrompt:av,setPlanContent:ov,getPlanContent:rv,extractStepsFromText:sv,advancePlanStep:cv,getPlanStepInfo:lv,PLAN_MODE_ALLOWED_TOOLS:Dm,setAutonomyLevel:dv,getAutonomyLevel:fv,AUTONOMY_LEVELS:Fm}});var Qm=Q((bR,Zm)=>{var{C:N}=Fe();function Wm(){return Math.max(10,(process.stdout.columns||80)-2)}function pv(t){if(!t)return"";let e=t.split(`
|
|
590
590
|
`),n=[],o=!1,s="";for(let r of e){let i=Wm();if(r.trim().startsWith("```")){if(o)n.push(`${N.dim}${"\u2500".repeat(40)}${N.reset}`),o=!1,s="";else{o=!0,s=r.trim().substring(3).trim();let c=s?` ${s} `:"";n.push(`${N.dim}${"\u2500".repeat(3)}${c}${"\u2500".repeat(Math.max(0,37-c.length))}${N.reset}`)}continue}if(o){n.push(` ${el(r,s)}`);continue}if(r.startsWith("### ")){n.push(`${N.bold}${N.cyan} ${fs(r.substring(4))}${N.reset}`);continue}if(r.startsWith("## ")){n.push(`${N.bold}${N.cyan} ${fs(r.substring(3))}${N.reset}`);continue}if(r.startsWith("# ")){n.push(`${N.bold}${N.cyan}${fs(r.substring(2))}${N.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let c=r.match(/^(\s*)/)[1],l=r.replace(/^\s*[-*]\s/,""),u=`${c}${N.cyan}\u2022${N.reset} ${ps(l)}`;n.push(ms(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}${N.cyan}${u}.${N.reset} ${ps(d)}`,p=l+" ".repeat(u.length+2);n.push(ms(f,i,p));continue}}n.push(ms(ps(r),i))}return n.join(`
|
|
591
591
|
`)}function fs(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function ps(t){return t?t.replace(/`([^`]+)`/g,`${N.cyan}$1${N.reset}`).replace(/\*\*([^*]+)\*\*/g,`${N.bold}$1${N.reset}`).replace(/\*([^*]+)\*/g,`${N.dim}$1${N.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${N.cyan}$1${N.reset} ${N.dim}($2)${N.reset}`):""}function el(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Hm(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Km(t):e==="json"||e==="jsonc"?Gm(t):e==="python"||e==="py"?Ym(t):e==="go"||e==="golang"?zm(t):e==="rust"||e==="rs"?Xm(t):e==="css"||e==="scss"||e==="less"?Jm(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Vm(t):t:""}function Hm(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,s=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(s,`${N.yellow}$1${N.reset}`),r=r.replace(e,`${N.magenta}$1${N.reset}`),r=r.replace(n,`${N.green}$&${N.reset}`),r=r.replace(o,`${N.dim}$1${N.reset}`),r}function Km(t){let e=/^(\s*)([\w-]+)/,n=/(--?\w[\w-]*)/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(#.*$)/,r=t;return r=r.replace(n,`${N.cyan}$1${N.reset}`),r=r.replace(e,`$1${N.green}$2${N.reset}`),r=r.replace(o,`${N.yellow}$&${N.reset}`),r=r.replace(s,`${N.dim}$1${N.reset}`),r}function Gm(t){let e=/("[\w-]+")\s*:/g,n=/:\s*("(?:[^"\\]|\\.)*")/g,o=/:\s*(\d+\.?\d*)/g,s=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${N.cyan}$1${N.reset}:`),r=r.replace(n,`: ${N.green}$1${N.reset}`),r=r.replace(o,`: ${N.yellow}$1${N.reset}`),r=r.replace(s,`: ${N.magenta}$1${N.reset}`),r}function Ym(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,n=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,o=/(#.*$)/,s=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(s,`${N.yellow}$1${N.reset}`),i=i.replace(e,`${N.magenta}$1${N.reset}`),i=i.replace(r,`${N.cyan}$1${N.reset}`),i=i.replace(n,`${N.green}$&${N.reset}`),i=i.replace(o,`${N.dim}$1${N.reset}`),i}function zm(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,n=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,o=/(["'`])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${N.yellow}$1${N.reset}`),i=i.replace(n,`${N.cyan}$1${N.reset}`),i=i.replace(e,`${N.magenta}$1${N.reset}`),i=i.replace(o,`${N.green}$&${N.reset}`),i=i.replace(s,`${N.dim}$1${N.reset}`),i}function Xm(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,n=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,c=t;return c=c.replace(r,`${N.yellow}$1${N.reset}`),c=c.replace(n,`${N.cyan}$1${N.reset}`),c=c.replace(e,`${N.magenta}$1${N.reset}`),c=c.replace(i,`${N.yellow}$1${N.reset}`),c=c.replace(o,`${N.green}$&${N.reset}`),c=c.replace(s,`${N.dim}$1${N.reset}`),c}function Jm(t){let e=/^(\s*)([\w-]+)\s*:/,n=/:\s*([^;]+)/,o=/^(\s*[.#@][\w-]+)/,s=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(i,`${N.yellow}$1${N.reset}`),c=c.replace(s,`${N.yellow}$1${N.reset}`),c=c.replace(e,`$1${N.cyan}$2${N.reset}:`),c=c.replace(o,`$1${N.magenta}$&${N.reset}`),c=c.replace(r,`${N.dim}$1${N.reset}`),c}function Vm(t){let e=/<\/?(\w[\w-]*)/g,n=/\s([\w-]+)=/g,o=/(["'])(?:(?=(\\?))\2.)*?\1/g,s=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(s,`${N.dim}$1${N.reset}`),i=i.replace(o,`${N.green}$&${N.reset}`),i=i.replace(e,`<${N.magenta}$1${N.reset}`),i=i.replace(n,` ${N.cyan}$1${N.reset}=`),i=i.replace(r,`${N.yellow}$1${N.reset}`),i}function ms(t,e,n=""){if(!e||e<10)return t;let o="",s=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),s++,s>e&&r!==-1){o+=t.slice(c,r)+`
|
|
592
592
|
`+n,c=r+1,i=c,s=n.length,r=-1;continue}s>e&&r===-1&&(o+=t.slice(c,i)+`
|
|
593
|
-
`+n,c=i,s=n.length+1),i++}return o+=t.slice(c),o}function
|
|
594
|
-
`)}function
|
|
593
|
+
`+n,c=i,s=n.length+1),i++}return o+=t.slice(c),o}function mv(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)}),o=n.map(i=>"\u2500".repeat(i+2)).join("\u253C"),s=t.map((i,c)=>` ${N.bold}${i.padEnd(n[c])}${N.reset} `).join("\u2502"),r=[];r.push(`${N.dim}\u250C${o.replace(/┼/g,"\u252C")}\u2510${N.reset}`),r.push(`${N.dim}\u2502${N.reset}${s}${N.dim}\u2502${N.reset}`),r.push(`${N.dim}\u251C${o}\u2524${N.reset}`);for(let i of e){let c=t.map((l,u)=>` ${(i[u]||"").padEnd(n[u])} `).join(`${N.dim}\u2502${N.reset}`);r.push(`${N.dim}\u2502${N.reset}${c}${N.dim}\u2502${N.reset}`)}return r.push(`${N.dim}\u2514${o.replace(/┼/g,"\u2534")}\u2518${N.reset}`),r.join(`
|
|
594
|
+
`)}function hv(t,e,n,o=30){let s=n>0?Math.round(e/n*100):0,r=Math.round(s/100*o),i=o-r,c=s>=100?N.green:s>50?N.yellow:N.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${N.dim}${"\u2591".repeat(i)}${N.reset} ${s}% (${e}/${n})`}var Qc=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{this.lineCount+=(e.match(/\n/g)||[]).length,process.stdout.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}_cursorWrite(e){try{process.stderr.write(e)}catch(n){if(n.code!=="EPIPE")throw n}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}_renderCursor(){let n=[0,1,2,3,4,3,2,1],o=n[this._cursorFrame%n.length],s="";for(let r=0;r<5;r++)s+=r===o?"\x1B[36m\u25CF\x1B[0m":" ";this._cursorWrite(`\x1B[2K\r${s}`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let n;for(;(n=this.buffer.indexOf(`
|
|
595
595
|
`))!==-1;){let o=this.buffer.substring(0,n);this.buffer=this.buffer.substring(n+1),this._renderLine(o)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${N.dim}${"\u2500".repeat(40)}${N.reset}
|
|
596
596
|
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=Wm();if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${N.dim}${"\u2500".repeat(40)}${N.reset}
|
|
597
597
|
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${N.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${N.reset}
|
|
@@ -602,7 +602,7 @@ Bullet list of potential issues and mitigations.
|
|
|
602
602
|
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${s}${N.cyan}\u2022${N.reset} ${ps(r)}`,c=ms(i,n,s+" ");this._safeWrite(`${c}
|
|
603
603
|
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){let r=s[1],i=s[2],c=s[3],l=`${r}${N.cyan}${i}.${N.reset} ${ps(c)}`,u=r+" ".repeat(i.length+2),d=ms(l,n,u);this._safeWrite(`${d}
|
|
604
604
|
`);return}}let o=ms(ps(e),n);this._safeWrite(`${o}
|
|
605
|
-
`)}};Zm.exports={renderMarkdown:
|
|
605
|
+
`)}};Zm.exports={renderMarkdown:pv,renderInline:ps,stripHeadingMarkers:fs,highlightCode:el,highlightJS:Hm,highlightBash:Km,highlightJSON:Gm,highlightPython:Ym,highlightGo:zm,highlightRust:Xm,highlightCSS:Jm,highlightHTML:Vm,renderTable:mv,renderProgress:hv,wrapAnsi:ms,StreamRenderer:Qc}});var sl=Q((_R,sh)=>{var{execSync:gv}=require("child_process"),tl=require("path"),nr=require("fs"),nl=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function eh(){return tl.join(process.cwd(),".nex","hooks")}function $v(){return tl.join(process.cwd(),".nex","config.json")}function th(){let t=$v();if(!nr.existsSync(t))return{};try{return JSON.parse(nr.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Fi(t){if(!nl.includes(t))return[];let e=[],n=eh(),o=tl.join(n,t);nr.existsSync(o)&&e.push(o);let s=th();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function nh(t,e={},n=3e4){try{return{success:!0,output:gv(t,{cwd:process.cwd(),encoding:"utf-8",timeout:n,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(o){return{success:!1,error:o.stderr?o.stderr.trim():o.message}}}function yv(t,e={}){let n=Fi(t);if(n.length===0)return[];let o={};for(let[r,i]of Object.entries(e))o[`NEX_${r.toUpperCase()}`]=String(i);let s=[];for(let r of n){let i=nh(r,o);if(s.push({command:r,...i}),!i.success&&t.startsWith("pre-"))break}return s}function wv(t){return Fi(t).length>0}function bv(){let t=[];for(let e of nl){let n=Fi(e);n.length>0&&t.push({event:e,commands:n})}return t}function _v(){let t=eh();return nr.existsSync(t)||nr.mkdirSync(t,{recursive:!0}),t}sh.exports={HOOK_EVENTS:nl,loadHookConfig:th,getHooksForEvent:Fi,executeHook:nh,runHooks:yv,hasHooks:wv,listHooks:bv,initHooksDir:_v}});var sr=Q((SR,gh)=>{"use strict";var{callWithRetry:rh,runSubAgent:xv,clearAllLocks:vv}=xi(),{parseModelSpec:ih,getActiveProviderName:xR,getActiveModelId:vR}=je(),{detectCategory:kv,getModelForCategory:oh}=In(),{MultiProgress:Sv,C:$e}=Fe(),{getModelBriefing:kR}=gi(),ah=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Ui=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),ch="devstral-2:123b",lh="kimi-k2.5",uh=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
|
|
606
606
|
|
|
607
607
|
RULES:
|
|
608
608
|
- Output ONLY a JSON array, no markdown fences, no explanation.
|
|
@@ -631,16 +631,16 @@ ORIGINAL REQUEST:
|
|
|
631
631
|
{prompt}
|
|
632
632
|
|
|
633
633
|
SUB-AGENT RESULTS:
|
|
634
|
-
{results}`;async function fh(t,e=1,n=2e3){for(let o=0;o<=e;o++)try{return await t()}catch(s){if(o===e)throw s;await new Promise(r=>setTimeout(r,n))}}function ph(t){let e=0,n=[];return function(){return new Promise(s=>{let r=()=>{e<t?(e++,s(()=>{e--,n.length>0&&n.shift()()})):n.push(r)};r()})}}function
|
|
634
|
+
{results}`;async function fh(t,e=1,n=2e3){for(let o=0;o<=e;o++)try{return await t()}catch(s){if(o===e)throw s;await new Promise(r=>setTimeout(r,n))}}function ph(t){let e=0,n=[];return function(){return new Promise(s=>{let r=()=>{e<t?(e++,s(()=>{e--,n.length>0&&n.shift()()})):n.push(r)};r()})}}function Ev(t){if(!t||typeof t!="string")return{isComplex:!1,estimatedGoals:0,reason:"empty"};let e=0,n=[],o=t.match(/(?:(?:^|\n)\s*|\s)(?:\d+[.)]\s|[(]\d+[)][\s,]|[(][a-z][)][\s,])/g);o&&o.length>=2&&(e=Math.max(e,o.length),n.push(`${o.length} numbered items`));let s=t.match(/(?:^|\n)\s*[-*]\s+\S/g);s&&s.length>=3&&(e=Math.max(e,s.length),n.push(`${s.length} bullet points`));let r=t.split(/;\s*/).filter(u=>u.trim().length>10);r.length>=3&&(e=Math.max(e,r.length),n.push(`${r.length} semicolon-separated goals`));let i=t.match(/\b(also|additionally|and\s+(?:fix|add|update|create|implement|remove|refactor))\b/gi);i&&i.length>=2&&(e=Math.max(e,i.length+1),n.push(`${i.length} transition keywords`));let c=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);return{isComplex:e>=c,estimatedGoals:e,reason:n.length>0?n.join(", "):"single goal"}}function ol(t){if(!t||typeof t!="string")throw new Error("Empty response from orchestrator model");let e=t.trim();try{return JSON.parse(e)}catch{}let n=e.match(/```(?:json)?\s*\n?([\s\S]*?)\n?\s*```/);if(n)try{return JSON.parse(n[1].trim())}catch{}let o=e.search(/[[\{]/);if(o>=0){let s=e.slice(o);try{return JSON.parse(s)}catch{}}throw new Error(`Could not extract valid JSON from response:
|
|
635
635
|
${e.slice(0,200)}`)}async function mh(t,e,n={}){let o=n.maxSubTasks||Ui,r=[{role:"system",content:uh.replace("{maxSubTasks}",String(o)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=ih(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let l=(await rh(r,[],i)).content||"",u=ol(l);if(!Array.isArray(u))throw new Error(`Decompose returned non-array: ${typeof u}`);let d=10,p=u.slice(0,o).map((g,y)=>({id:g.id||`t${y+1}`,task:String(g.task||""),scope:Array.isArray(g.scope)?g.scope:[],estimatedCalls:typeof g.estimatedCalls=="number"?Math.min(g.estimatedCalls,d):8,priority:typeof g.priority=="number"?g.priority:y+1})).filter(g=>g.task.length>0),h=p.reduce((g,y)=>g+y.estimatedCalls,0),m=Ui*d;if(h>m){let{debugLog:g}=Xr();g(`\x1B[33m \u26A0 Orchestrator: total estimated calls ${h} > ${m} \u2014 consider raising maxSubTasks\x1B[0m`)}return p}async function hh(t,e,n){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",resourcesChanged:[]};let o=t.map((d,f)=>{let p=d.status==="done"?"SUCCESS":d.status==="truncated"?"PARTIAL":"FAILED";return`--- Agent ${f+1} [${p}] ---
|
|
636
636
|
Task: ${d.task}
|
|
637
637
|
Result: ${d.result}
|
|
638
638
|
Tools: ${(d.toolsUsed||[]).join(", ")||"none"}`}).join(`
|
|
639
639
|
|
|
640
|
-
`),r=[{role:"system",content:dh.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let d=ih(n);d.provider&&(i.provider=d.provider),d.model&&(i.model=d.model)}let l=(await rh(r,[],i)).content||"",u=ol(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
|
|
640
|
+
`),r=[{role:"system",content:dh.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let d=ih(n);d.provider&&(i.provider=d.provider),d.model&&(i.model=d.model)}let l=(await rh(r,[],i)).content||"",u=ol(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 Tv(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||lh,o=e.workerModel||ch,s=e.maxParallel||ah,r=e.maxSubTasks||Ui,i=e.onProgress||(()=>{}),c={input:0,output:0};console.log(`
|
|
641
641
|
${$e.bold}Orchestrator${$e.reset} ${$e.dim}model: ${n} | workers: ${o} | max parallel: ${s}${$e.reset}
|
|
642
642
|
`),i("decomposing"),console.log(`${$e.dim}Phase 1: Decomposing prompt into sub-tasks...${$e.reset}`);let l;try{l=await mh(t,n,{maxSubTasks:r})}catch(B){return console.log(`${$e.red}Decompose failed: ${B.message}${$e.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${B.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 B of l){console.log(` ${$e.dim}${B.id}:${$e.reset} ${B.task}`);let R=B.scope.filter(Boolean);R.length>0&&console.log(` ${$e.dim}scope: ${R.join(", ")}${$e.reset}`)}console.log("");let u=new Map;for(let B=0;B<l.length;B++)for(let R of l[B].scope)R&&!u.has(R)&&u.set(R,B);i("executing"),console.log(`${$e.dim}Phase 2: Running ${l.length} sub-agents (max ${s} parallel)...${$e.reset}
|
|
643
|
-
`);let d=Date.now(),f=ph(s),p={findings:[],_lock:!1},h=l.map(B=>{let R=
|
|
643
|
+
`);let d=Date.now(),f=ph(s),p={findings:[],_lock:!1},h=l.map(B=>{let R=kv(B.task);return(R?oh(R.id):null)||o}),m=l.map((B,R)=>{let ye=`Agent ${R+1} [${h[R]}]: `,be=Math.max(20,60-ye.length),pe=B.task.substring(0,be)+(B.task.length>be?"...":"");return ye+pe}),g=new Sv(m);g.start();let y=`
|
|
644
644
|
You are a focused coding agent executing ONE specific sub-task.
|
|
645
645
|
Your scope is limited to the files listed in your task definition.
|
|
646
646
|
|
|
@@ -662,35 +662,35 @@ RULES:
|
|
|
662
662
|
- Max 10 tool calls. If you need more, you are doing too much \u2014 narrow your scope.
|
|
663
663
|
- When done: stop calling tools and write a one-line summary of what you changed.
|
|
664
664
|
`,w=l.map(async(B,R)=>{let ye=await f();try{let be=p.findings.filter(x=>x.agentId!==B.id).map(x=>`Agent ${x.agentId} found: ${x.summary}`).join(`
|
|
665
|
-
`),
|
|
665
|
+
`),pe=[...u.entries()].filter(([,x])=>x===R).map(([x])=>x),me=[...u.entries()].filter(([,x])=>x!==R).map(([x])=>x),xe=[be?`Prior agent findings:
|
|
666
666
|
${be}
|
|
667
|
-
`:"",B.scope.length>0?`Focus on files: ${B.scope.join(", ")}`:"",
|
|
668
|
-
`)),Re++;let E=x&&
|
|
669
|
-
`):void 0,max_iterations:Math.min(B.estimatedCalls||10,15),model:E,_skipLog:!0,_systemPrompt:y,_readOnlyFiles:
|
|
667
|
+
`:"",B.scope.length>0?`Focus on files: ${B.scope.join(", ")}`:"",pe.length>0?`You OWN these files (may read+write): ${pe.join(", ")}`:"",me.length>0?`READ ONLY (owned by other agents, do NOT write): ${me.join(", ")}`:""].filter(Boolean),he=h[R],ge=process.env.NEX_FALLBACK_MODEL||oh("agentic")||o,Re=0,k=await fh(async()=>{let x=Re>0;x&&(g.update(R,"retry"),process.stderr.write(` ${$e.dim}[Agent ${R+1}] retrying after error...${$e.reset}
|
|
668
|
+
`)),Re++;let E=x&&he!==ge?ge:he;return xv({task:B.task,context:xe.length>0?xe.join(`
|
|
669
|
+
`):void 0,max_iterations:Math.min(B.estimatedCalls||10,15),model:E,_skipLog:!0,_systemPrompt:y,_readOnlyFiles:me},{onUpdate:A=>{if(A&&A.type==="tool_call"&&process.stderr.isTTY){let T=`Agent ${R+1} [${E}]`,L=A.tool||"...";g.labels[R]=`${T}: ${L}`}}})},1,2e3),j=typeof k.result=="string"?k.result.slice(0,200):String(k.result||"").slice(0,200);return p.findings.push({agentId:B.id,summary:j,files:Array.isArray(B.scope)?B.scope:[]}),g.labels[R]=m[R],g.update(R,k.status==="failed"?"error":"done"),c.input+=k.tokensUsed?.input||0,c.output+=k.tokensUsed?.output||0,k.tokensUsed?._estimated&&(c._estimated=!0),{...k,_scope:B.scope,_idx:R}}catch(be){return g.labels[R]=m[R],g.update(R,"error"),{task:B.task,status:"failed",result:`Error: ${be.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}finally{ye()}}),v;try{v=await Promise.all(w)}finally{g.stop({silent:!0}),vv()}console.log("");let M=Math.round((Date.now()-d)/1e3),C=M>=60?`${Math.floor(M/60)}m ${M%60}s`:`${M}s`;for(let B=0;B<v.length;B++){let R=v[B],be=R.status==="done"||R.status==="truncated"&&R.result&&!R.result.startsWith("Error")?`${$e.green}\u2713${$e.reset}`:`${$e.red}\u2717${$e.reset}`,pe=R._scope&&R._scope.length>0?R._scope.map(he=>he.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],me=pe.length>0?pe.join(", "):R.task.substring(0,35)+(R.task.length>35?"...":""),xe=B===v.length-1;console.log(` ${be} Agent ${B+1} ${$e.dim}${me}${$e.reset}${xe?` ${$e.dim}${C}${$e.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${$e.dim}Phase 3: Synthesizing results...${$e.reset}`);let S;try{S=await hh(v,t,n)}catch(B){console.log(`${$e.yellow}Synthesize failed: ${B.message} \u2014 using raw results.${$e.reset}`),S={summary:v.map(R=>R.result).join(`
|
|
670
670
|
`),conflicts:[],commitMessage:"",resourcesChanged:[]}}let O=p.findings.flatMap(B=>B.files),D=new Map;for(let B of O)D.set(B,(D.get(B)||0)+1);let K=[...D.values()].some(B=>B>1),V=p.findings.length>1&&K?` ${$e.dim}(agents shared context)${$e.reset}`:"";if(console.log(`
|
|
671
671
|
${$e.bold}Summary:${$e.reset} ${S.summary}${V}`),S.conflicts.length>0){console.log(`${$e.yellow}Conflicts:${$e.reset}`);for(let B of S.conflicts)console.log(` - ${B}`)}S.commitMessage&&console.log(`${$e.dim}Suggested commit: ${S.commitMessage}${$e.reset}`);let X=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: ${X}${$e.reset}
|
|
672
|
-
`),{results:v,synthesis:S,totalTokens:c}}gh.exports={runOrchestrated:
|
|
673
|
-
`)}var Sh=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function
|
|
672
|
+
`),{results:v,synthesis:S,totalTokens:c}}gh.exports={runOrchestrated:Tv,decompose:mh,synthesize:hh,detectComplexPrompt:Ev,extractJSON:ol,createSemaphore:ph,DECOMPOSE_PROMPT:uh,SYNTHESIZE_PROMPT:dh,DEFAULT_ORCHESTRATOR_MODEL:lh,DEFAULT_WORKER_MODEL:ch,DEFAULT_MAX_PARALLEL:ah,DEFAULT_MAX_SUBTASKS:Ui,withRetry:fh}});var ve=Q((OR,qh)=>{var{C:$,Spinner:oo,TaskProgress:Rv,formatToolCall:Cv,formatToolSummary:Oh,formatSectionHeader:Bi,formatMilestone:Av,setActiveTaskProgress:ER}=Fe(),{debugLog:W,warnLog:TR}=Xr(),{MilestoneTracker:Ov}=Td(),{callStream:$h}=je(),{parseToolArgs:Nv}=Fs(),{executeTool:Mv}=Gt(),{gatherProjectContext:Pv}=Mi(),{fitToContext:Lv,forceCompress:dn,getUsage:Zt,estimateTokens:Iv}=Ct(),{autoSave:jv,flushAutoSave:Dv}=Jt(),{scoreMessages:qv,formatScore:Fv,appendScoreHistory:Uv}=Li(),{detectCategory:Bv,getModelForPhase:ml,getPhaseBudget:hs,isPhaseRoutingEnabled:Wv}=In();function Ze(t){jv(t),Dv()}function Hv(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 yh(t){try{if(!t.some(o=>o.role!=="assistant"?!1:!!(Array.isArray(o.content)&&o.content.some(s=>s&&s.type==="tool_use")||Array.isArray(o.tool_calls)&&o.tool_calls.length>0)))return;let n=qv(t);if(!n)return;console.log(Fv(n,$));try{let{_getSessionsDir:o}=Jt(),s=require("fs"),r=require("path").join(o(),"_autosave.json");if(s.existsSync(r)){let i=JSON.parse(s.readFileSync(r,"utf-8"));i.score=n.score,i.scoreGrade=n.grade,i.scoreIssues=n.issues,s.writeFileSync(r,JSON.stringify(i,null,2))}}catch{}try{let{getActiveModel:o}=Fs(),s=As();Uv(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:Kv}=un(),{getDeploymentContextBlock:Gv,probeUrlServer:Yv}=Wc(),{getFewShotForInput:zv}=Nm(),{checkPermission:Xv,setPermission:Jv,savePermissions:Vv}=tr(),{confirm:Nh,setAllowAlwaysHandler:Zv,getAutoConfirm:Qv}=ft(),{isPlanMode:fr,getPlanModePrompt:ek,PLAN_MODE_ALLOWED_TOOLS:Mh,setPlanContent:tk,extractStepsFromText:nk,createPlan:sk,getActivePlan:RR,startExecution:CR,advancePlanStep:ok,getPlanStepInfo:rk}=Vt(),{StreamRenderer:ik}=Qm(),{runHooks:wh}=sl(),{routeMCPCall:ak,getMCPToolDefinitions:ck}=ni(),{getSkillInstructions:lk,getSkillToolDefinitions:uk,routeSkillCall:dk,matchSkillTriggers:fk}=Mn(),{trackUsage:bh,estimateTokens:_h}=qs();function xh(t){return!t||typeof t!="string"?0:typeof _h=="function"?_h(t):Math.ceil(t.length/4)}var{validateToolArgs:pk}=cc(),{filterToolsForModel:vh,getModelTier:mk,PROVIDER_DEFAULT_TIER:AR}=Ro(),{getConfiguredProviders:hk,getActiveProviderName:ro,getActiveModelId:pn,setActiveModel:kh,MODEL_EQUIVALENTS:ta}=je(),{getModelProfile:gk,getModelBriefing:$k}=gi(),Sl=require("fs"),El=require("path"),yk=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function wk(t){let e=Av(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
|
|
673
|
+
`)}var Sh=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function bk(t){let e=[],n;for(Sh.lastIndex=0;(n=Sh.exec(t))!==null;){let o=n[1].trim(),s=o.startsWith("~")?o.replace("~",process.env.HOME||""):El.resolve(o);Sl.existsSync(s)&&e.push({raw:o,abs:s})}return e}function _k(t){let e=Sl.readFileSync(t),n=El.extname(t).toLowerCase().replace(".",""),o=n==="jpg"||n==="jpeg"?"image/jpeg":n==="png"?"image/png":n==="gif"?"image/gif":n==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:o}}function Ph(t){let e=bk(t);if(e.length===0)return t;let n=[{type:"text",text:t}];for(let o of e)try{let{data:s,media_type:r}=_k(o.abs);n.push({type:"image",media_type:r,data:s})}catch{}return n.length>1?n:t}function xk(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 o=new Map;for(let l=0;l<=n.length-3;l++){let u=n.slice(l,l+3).join("").trim();u.length>30&&o.set(u,(o.get(u)||0)+1)}let s=0,r="";for(let[l,u]of o)u>s&&(s=u,r=l);if(s<3)return{text:t,truncated:!1,repeatCount:s};let i=`
|
|
674
674
|
|
|
675
675
|
[SYSTEM: Output repetition detected \u2014 response truncated (${s}\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:s}}function hl(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let n=t.split(`
|
|
676
676
|
`),o=new Map;for(let f of n){let p=f.trim();p.length>=20&&o.set(p,(o.get(p)||0)+1)}let s=0,r="";for(let[f,p]of o)p>s&&(s=p,r=f);if(s<=e)return{text:t,truncated:!1,repeatCount:s};let i=`
|
|
677
677
|
|
|
678
|
-
\u26A0 [Response truncated: repeated paragraph detected (${s}\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:s}}var rl=null,il=null,al=null;function pt(){if(rl===null){let{TOOL_DEFINITIONS:t}=Gt();rl=t}return il===null&&(il=
|
|
678
|
+
\u26A0 [Response truncated: repeated paragraph detected (${s}\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:s}}var rl=null,il=null,al=null;function pt(){if(rl===null){let{TOOL_DEFINITIONS:t}=Gt();rl=t}return il===null&&(il=uk()),al===null&&(al=ck()),[...rl,...il,...al]}var gl=50;function vk(t){Number.isFinite(t)&&t>0&&(gl=t)}var Ki=()=>null;function kk(t){Ki=t}var ir=null,$l=null,io=null,Gi=new Map,Sk=1e4,Ek=6e3,Tk=/\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 Rk(t){return!t||typeof t!="string"?t:t.replace(Tk,(e,n)=>`${n}=***REDACTED***`)}var Ck=7e3,Ak=4e3;function Ok(t,e=null){let n=Rk(t),o=Iv(n),s=e==="read_file"?Ck:Sk,r=e==="read_file"?Ak:Ek;if(o>s)try{let{compressToolResult:i}=Ct();return i(n,r)}catch{return n}return n}function Lh(t){try{let{getActiveModel:e}=je(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(Gi.has(o))return Gi.get(o);let s=vh(t);return Gi.set(o,s),s}catch{return vh(t)}}function Nk(){Gi.clear()}var ar={hash:null,ts:0},Mk=3e4;async function Ih(){if(ar.hash&&Date.now()-ar.ts<Mk)return ar.hash;try{let t=require("fs").promises,e=require("path"),n=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],s=(await Promise.allSettled(n.map(i=>t.stat(i).then(c=>`${i}:${c.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=un(),c=i();c&&s.push(`memory:${c}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Sl.existsSync(i)){let c=await t.stat(i);s.push(`brain:${c.mtimeMs}`)}}catch{}let r=s.join("|");return ar={hash:r,ts:Date.now()},r}catch{return`fallback:${Date.now()}`}}function yl(){ir=null,$l=null,ar={hash:null,ts:0},io=null}var Pk=new Set(["spawn_agents"]),cl=5,ll=3,Wi=2,Eh=6e4,ul=12e4,Lk=process.env.NEX_STALE_AUTO_SWITCH!=="0";function Ik(t){try{let e=require("fs"),n=require("path"),o=n.join(process.cwd(),".nex","plans");e.existsSync(o)||e.mkdirSync(o,{recursive:!0});let s=n.join(o,"current-plan.md");e.writeFileSync(s,t,"utf-8")}catch{}}Zv(t=>{Jv(t,"allow"),Vv(),console.log(`${$.green} \u2713 ${t}: always allow${$.reset}`)});async function jk(t){let e=t.function.name,n=Nv(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!n){let d=pt().find(p=>p.function.name===e),f=d?JSON.stringify(d.function.parameters,null,2):"unknown";return W(`${$.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${$.reset}`),{callId:o,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
679
679
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
680
680
|
|
|
681
681
|
Expected JSON schema for "${e}":
|
|
682
682
|
${f}
|
|
683
683
|
|
|
684
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}let s=
|
|
684
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}let s=pk(e,n);if(!s.valid){W(`${$.yellow} \u26A0 ${e}: ${s.error.split(`
|
|
685
685
|
`)[0]}${$.reset}`);let u=(Ch.get(e)||0)+1;Ch.set(e,u);let d=u>=2?`${s.error}
|
|
686
686
|
|
|
687
|
-
[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.]`:s.error;return{callId:o,fnName:e,args:n,canExecute:!1,errorResult:{role:"tool",content:d,tool_call_id:o}}}let r=s.corrected||n;if(s.corrected){let u=Object.keys(n),d=Object.keys(s.corrected),f=u.filter(p=>!d.includes(p));f.length&&console.log(`${$.dim} \u2713 ${e}: corrected args (${f.join(", ")})${$.reset}`)}if(fr()&&!Mh.has(e))return console.log(`${$.yellow} \u2717 ${e}: blocked in plan mode${$.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:o}};let i=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),c=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]);if(Te&&Xe==="plan"&&!i.has(e))return qn++,W(`${$.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${qn})${$.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${e}' is blocked. Analyze the codebase using read-only tools, then present your findings as text. Edits happen in the next phase.`,tool_call_id:o}};if(Te&&Xe==="verify"&&!c.has(e))return W(`${$.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${$.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${e}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:o}};let l=
|
|
687
|
+
[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.]`:s.error;return{callId:o,fnName:e,args:n,canExecute:!1,errorResult:{role:"tool",content:d,tool_call_id:o}}}let r=s.corrected||n;if(s.corrected){let u=Object.keys(n),d=Object.keys(s.corrected),f=u.filter(p=>!d.includes(p));f.length&&console.log(`${$.dim} \u2713 ${e}: corrected args (${f.join(", ")})${$.reset}`)}if(fr()&&!Mh.has(e))return console.log(`${$.yellow} \u2717 ${e}: blocked in plan mode${$.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:o}};let i=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),c=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]);if(Te&&Xe==="plan"&&!i.has(e))return qn++,W(`${$.yellow} \u2717 ${e}: blocked in plan phase (read-only, block #${qn})${$.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN PHASE: '${e}' is blocked. Analyze the codebase using read-only tools, then present your findings as text. Edits happen in the next phase.`,tool_call_id:o}};if(Te&&Xe==="verify"&&!c.has(e))return W(`${$.yellow} \u2717 ${e}: blocked in verify phase (read + bash only)${$.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`VERIFY PHASE: '${e}' is blocked. Use read_file and bash (for tests/linters) to verify changes. Report PASS or FAIL.`,tool_call_id:o}};let l=Xv(e);if(l==="deny")return console.log(`${$.red} \u2717 ${e}: denied by permissions${$.reset}`),{callId:o,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:o}};if(l==="ask"){let u=` Allow ${e}?`;return e==="bash"&&r.command&&(u=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await Nh(u,{toolName:e})?{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:o,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:o}}}return{callId:o,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function Dk(t,e,n={}){let o=await dk(t,e);if(o!==null)return o;let s=await ak(t,e);return s!==null?s:Mv(t,e,n)}function qk(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(Cv(t.fnName,t.args));let n=wh("pre-tool",{tool_name:t.fnName});if(!e&&n.length>0)for(let h of n)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}`);mn?.onToolStart&&mn.onToolStart(t.fnName,t.args);let o=await Dk(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),s=String(o??""),r=s.length>5e4?s.substring(0,5e4)+`
|
|
688
688
|
...(truncated ${s.length-5e4} chars)`:s,i=r.split(`
|
|
689
|
-
`)[0],c=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),l=Oh(t.fnName,t.args,r,c);e||console.log(l),mn?.onToolEnd&&mn.onToolEnd(t.fnName,l,!c);let u=wh("post-tool",{tool_name:t.fnName});if(!e&&u.length>0)for(let h of u)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 f=
|
|
689
|
+
`)[0],c=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),l=Oh(t.fnName,t.args,r,c);e||console.log(l),mn?.onToolEnd&&mn.onToolEnd(t.fnName,l,!c);let u=wh("post-tool",{tool_name:t.fnName});if(!e&&u.length>0)for(let h of u)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 f=Ok(r,t.fnName);if(t.fnName==="bash"&&t.args?.command){let h=t.args.command.trim();!/cat\s*>|<</.test(h)&&/\bcat\s+\S/.test(h)?f+=`
|
|
690
690
|
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)?f+=`
|
|
691
691
|
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)&&(f+=`
|
|
692
|
-
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:f,tool_call_id:t.callId},summary:l}}var
|
|
693
|
-
`)):(wl=t,zi=1,W(`${e} \u26A0 ${t}${$.reset}`))}var ea=[];function
|
|
692
|
+
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:f,tool_call_id:t.callId},summary:l}}var Fk=[{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 fl(t){for(let{re:e,label:n}of Fk){let o=t.match(e);if(o){let s=(o[1]||"").trim();return s?`${n}: ${s}`:n}}return null}async function Uk(t,e=!1,n={}){let o=new Array(t.length),s=[],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=qk(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 oo(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);o[l]=u,s.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++)o[r[d]]=u[d].msg,s.push(u[d].summary)}r=[]}}for(let l=0;l<t.length;l++){let u=t[l];if(!u.canExecute){await c(),o[l]=u.errorResult,s.push(Oh(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(Pk.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await dl(u,e);o[l]=d,s.push(f)}else r.push(l)}if(await c(),i&&i.stop(),e&&s.length>0&&!n.skipSummaries)for(let l of s)console.log(l);return{results:o,summaries:s}}var H=[],Th=300,jh=900*1e3;function gs(t,e){let n=t.get(e);return n?Date.now()-n.ts>jh?(t.delete(e),0):n.count:0}function $s(t,e){let n=t.get(e),o=n&&Date.now()-n.ts<=jh?n.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function Rh(t,e,n){t.set(e,{count:n,ts:Date.now()})}var Tl=new Map,Rl=new Map,pr=new Map,Cl=new Map,mr=new Map,xs=new Map,Dn=new Map,Al=new Map,ys=new Map,vs=new Map,Ch=new Map,na=new Map,sa=new Map,Ut=0,cr=0,Yi=0,wl="",zi=0,Mt=!1,Hi=0,Xi=0,ws=-1,bl=!1,Ji=0,Vi=!1,fn=0,Qt=!1,vn=0,en=0,st=!1,kt="",lr=0,jn=0,Zi="",bs=0,_s=0,Qi="",Bt=!1,_l=!1,hr=new Map,gr=new Set,ur=null,pl=!1,or=0,Ah=!1,Xe="plan",oa=0,Te=!1,qn=0,kn=null,xl=null,vl=null,dr=0,ao=null;function so(t,e){t===wl?(zi++,Xr().DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${zi})${$.reset}
|
|
693
|
+
`)):(wl=t,zi=1,W(`${e} \u26A0 ${t}${$.reset}`))}var ea=[];function Bk(t){ea.push(t.trim())}function Wk(){return ea.length===0?null:ea.splice(0,ea.length).join(`
|
|
694
694
|
`)}function rr(t,e,n,o){if(!Te)return null;let s=Xe;Xe=t,oa=0,kn=ml(t,ao),fn=0,Qt=!1,vn=0,en=0,xs.clear(),Dn.clear(),vs.clear(),na.clear(),sa.clear(),Rl.clear(),pr.clear(),Cl.clear(),mr.clear(),Tl.clear(),Al.clear();let r;if(t==="implement")xl=e?.slice(0,800)||"",r=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
|
|
695
695
|
${xl}
|
|
696
696
|
|
|
@@ -702,18 +702,18 @@ Now implement the fix/changes. Do not investigate further \u2014 edit files dire
|
|
|
702
702
|
Report PASS (all good) or FAIL (list specific issues).
|
|
703
703
|
|
|
704
704
|
Files modified: ${i}
|
|
705
|
-
Summary: ${vl}`}return W(`${$.cyan} \u21B3 Phase transition: ${s} \u2192 ${t} (model: ${kn||"default"})${$.reset}`),r?{role:"user",content:r}:null}function
|
|
705
|
+
Summary: ${vl}`}return W(`${$.cyan} \u21B3 Phase transition: ${s} \u2192 ${t} (model: ${kn||"default"})${$.reset}`),r?{role:"user",content:r}:null}function Hk(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,n=process.env.NEX_COMMIT_LANGUAGE,o=!t||t==="auto"?null:t,s=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
706
706
|
`];o?s.push(`RESPONSE LANGUAGE: You MUST always respond in ${o}. 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. ${o} only.`):s.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."),s.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),s.push("COMPLETENESS RULES:"),s.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),s.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."),s.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),s.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),s.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),s.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),s.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.'),s.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."),s.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."),s.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.'),s.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).'),s.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)."),s.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."),s.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."),s.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.'),s.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";s.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let i=n||"English";return s.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),o&&s.push(`
|
|
707
707
|
This is a hard requirement. Always respond in ${o}. 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 ${o}.`),s.join(`
|
|
708
708
|
`)+`
|
|
709
709
|
|
|
710
|
-
`}function
|
|
710
|
+
`}function Kk(){if(io!==null)return io;try{let e=hk().flatMap(s=>s.models.map(r=>({spec:`${s.name}:${r.id}`,tier:mk(r.id,s.name),name:r.name})));if(e.length<2)return io="","";let n={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},o=`
|
|
711
711
|
# Sub-Agent Model Routing
|
|
712
712
|
|
|
713
713
|
`;o+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',o+=`| Model | Tier | Auto-assigned for |
|
|
714
714
|
|---|---|---|
|
|
715
715
|
`;for(let s of e)o+=`| ${s.spec} | ${s.tier} | ${n[s.tier]||s.tier} |
|
|
716
|
-
`;return io=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),io="",""}}async function kl(){let t=await Ih()+":"+pn();if(ir!==null&&t===$l)return ir;let e=await
|
|
716
|
+
`;return io=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),io="",""}}async function kl(){let t=await Ih()+":"+pn();if(ir!==null&&t===$l)return ir;let e=await Pv(process.cwd()),n=Kv(),o=lk(),s=fr()?ek():"",r=Hk(),i=Gv(),c=$k(pn());return ir=`${c?`## Model Briefing
|
|
717
717
|
${c}
|
|
718
718
|
|
|
719
719
|
---
|
|
@@ -734,7 +734,7 @@ ${s}
|
|
|
734
734
|
${r?`${r}
|
|
735
735
|
`:""}${i?`${i}
|
|
736
736
|
|
|
737
|
-
`:""}${
|
|
737
|
+
`:""}${Qv()?`# YOLO Mode \u2014 Auto-Execute
|
|
738
738
|
|
|
739
739
|
You are in YOLO mode (autoConfirm=true). All tool calls are pre-approved.
|
|
740
740
|
- NEVER ask for confirmation \u2014 just execute tasks directly
|
|
@@ -959,7 +959,7 @@ You have a soft budget of ~30 tool calls per task. Sessions with >40 tool calls
|
|
|
959
959
|
- Instead: use bash with inline node -e '...' for quick one-off checks.
|
|
960
960
|
- If the test is worth keeping, write it to tests/ with a proper name.
|
|
961
961
|
- Write-then-delete patterns waste 3 tool calls and leave orphans if the session is interrupted.
|
|
962
|
-
${
|
|
962
|
+
${Kk()}
|
|
963
963
|
|
|
964
964
|
# Edit Protocol (Mandatory \u2014 Follow These Steps Exactly)
|
|
965
965
|
|
|
@@ -1150,66 +1150,66 @@ class ErrorBoundary extends React.Component {
|
|
|
1150
1150
|
- Use migrations for schema changes, never manual ALTER TABLE
|
|
1151
1151
|
- Add database-level constraints (unique, foreign key, check) not just app-level
|
|
1152
1152
|
|
|
1153
|
-
`,$l=t,ir}function Dh(){Tl.clear(),Rl.clear(),pr.clear(),Cl.clear(),mr.clear(),xs.clear(),Dn.clear(),Al.clear(),ys.clear(),vs.clear(),na.clear(),sa.clear(),Ut=0,cr=0,Yi=0,Mt=!1,Xi=0,ws=-1,bl=!1,Ji=0,Vi=!1,fn=0,Qt=!1,vn=0,en=0,
|
|
1153
|
+
`,$l=t,ir}function Dh(){Tl.clear(),Rl.clear(),pr.clear(),Cl.clear(),mr.clear(),xs.clear(),Dn.clear(),Al.clear(),ys.clear(),vs.clear(),na.clear(),sa.clear(),Ut=0,cr=0,Yi=0,Mt=!1,Xi=0,ws=-1,bl=!1,Ji=0,Vi=!1,fn=0,Qt=!1,vn=0,en=0,st=!1,kt="",lr=0,Zi="",bs=0,Qi="",_s=0,Bt=!1,_l=!1,Xe="plan",oa=0,Te=!1,kn=null,xl=null,vl=null,dr=0,qn=0,ao=null,hr.clear(),gr.clear(),wl="",zi=0}function Gk(){H=[],ur=null,Dh()}function Yk(){H.length>Th&&H.splice(0,H.length-Th)}function zk(){return H.length}function Xk(){return H}function Jk(t){H=t}async function Vk(){let{execFile:t}=require("child_process"),e=require("fs"),n=process.cwd(),o=(f,p)=>new Promise(h=>{t(f,p,{cwd:n,timeout:3e3},(m,g)=>{h(m?"":(g||"").trim())})}),[s]=await Promise.all([o("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),i=(s?s.split(`
|
|
1154
1154
|
`):[]).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=El.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 h=p.slice(0,5).join(" \xB7 "),m=p.length>5?` +${p.length-5}`:"";u+=`
|
|
1155
|
-
\u{1F4E6} ${h}${m}`}}catch{}return u}function
|
|
1156
|
-
${$.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`;
|
|
1157
|
-
`),p==="")return c({action:"quit"});let m=i.find(g=>g.key===h);!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 mn=null;async function
|
|
1155
|
+
\u{1F4E6} ${h}${m}`}}catch{}return u}function Zk(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 Qe(t,e,n,o,s,{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(s){let u=Date.now()-s;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(`
|
|
1156
|
+
${$.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`;Zk(u)}if(gr.size>0&&hr.size>0)for(let u of gr){let d=hr.get(u);d&&console.log(`${$.dim} \u2714 task #${u} auto-matched: ${d.slice(0,60)}${$.reset}`)}n.size>0?console.log(`${$.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${$.reset}`):!r&&o.size>=5&&n.size===0&&t>=3?console.log(`${$.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${$.reset}`):o.size>0&&t>=2&&console.log(`${$.dim} \u{1F4A1} /save \xB7 /clear${$.reset}`)}async function Qk(){if(!process.stdout.isTTY)return{action:"quit"};let t=ro(),e=pn(),n=ta.fast?.[t],o=ta.strong?.[t],s=n&&n!==e,r=o&&o!==e&&o!==n,i=[];i.push({key:"r",label:`Retry with current model ${$.dim}(${e})${$.reset}`}),s&&i.push({key:"f",label:`Switch to ${$.bold}${n}${$.reset} ${$.dim}\u2014 fast, low latency${$.reset}`,model:n}),r&&i.push({key:"s",label:`Switch to ${$.bold}${o}${$.reset} ${$.dim}\u2014 reliable tool-calling, medium speed${$.reset}`,model:o}),i.push({key:"q",label:`${$.dim}Quit${$.reset}`}),console.log(),console.log(`${$.yellow} Stream stale \u2014 all retries exhausted.${$.reset} What would you like to do?`);for(let 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 h=p.toLowerCase().trim();if(process.stdout.write(`${h}
|
|
1157
|
+
`),p==="")return c({action:"quit"});let m=i.find(g=>g.key===h);!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 mn=null;async function eS(t,e=null,n={}){let o=gk(pn());Eh=o.staleWarn,ul=o.staleAbort,mn=e;let s=t;ur&&typeof t=="string"&&(s=`${ur}
|
|
1158
1158
|
|
|
1159
|
-
${t}`,ur=null);let r=Ph(s);H.push({role:"user",content:r}),
|
|
1159
|
+
${t}`,ur=null);let r=Ph(s);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:Ae,runOrchestrated:Ne}=sr(),qe=Ae(typeof t=="string"?t:"");if(i&&qe.isComplex&&qe.estimatedGoals>=c)return console.log(`${$.yellow}\u26A1 Auto-orchestrate: ${qe.estimatedGoals} goals \u2192 parallel agents${$.reset}`),await Ne(t,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});qe.isComplex&&process.stdout.isTTY&&console.log(`${$.dim}Hint: ~${qe.estimatedGoals} goals detected. Disable with NEX_AUTO_ORCHESTRATE=false${$.reset}`)}catch{}let{setOnChange:l}=hi(),u=null,d=0;l((Ae,Ne)=>{Ae==="create"?(u&&u.stop(),u=new Rv(Ne.name,Ne.tasks),u.setStats({tokens:d}),u.start()):Ae==="update"&&u?u.updateTask(Ne.id,Ne.status):Ae==="clear"&&u&&(u.stop(),u=null)});let f=await kl(),p=f;try{let{getBrainContext:Ae}=Do(),Ne=await Ae(t);Ne&&(p=f+`
|
|
1160
1160
|
`+Ne+`
|
|
1161
|
-
`)}catch(Ae){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",Ae.message)}let m=
|
|
1161
|
+
`)}catch(Ae){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",Ae.message)}let m=fk(typeof t=="string"?t:"");if(m.length>0){let Ae=m.map(Ne=>`[Triggered: ${Ne.name}]
|
|
1162
1162
|
${Ne.instructions}`).join(`
|
|
1163
1163
|
`);p+=`
|
|
1164
1164
|
`+Ae+`
|
|
1165
|
-
`}let g=[{role:"system",content:p},...H],y=new oo("Thinking...");y.start();let w=H.length===1,v=w?
|
|
1166
|
-
${X}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...R.slice(1)]),w){let Ae=
|
|
1167
|
-
`),Ne=fl(Ae);Ne&&(
|
|
1168
|
-
`+ee.map(
|
|
1169
|
-
`));let te=H.filter(
|
|
1165
|
+
`}let g=[{role:"system",content:p},...H],y=new oo("Thinking...");y.start();let w=H.length===1,v=w?Vk().catch(()=>null):Promise.resolve(null),M=w?Yv(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),C=pt(),[{messages:S,compressed:O,compacted:D,tokensRemoved:K},V,X]=await Promise.all([Lv(g,C),v,M]),B=Zt(g,C);if(y.stop(),V&&console.log(`${$.dim}${V}${$.reset}`),D)console.log(`${$.dim} [context compacted \u2014 summary (~${K} tokens freed)]${$.reset}`);else if(O){let Ae=B.limit>0?Math.round(K/B.limit*100):0;W(`${$.dim} [context compressed \u2014 ~${K} tokens freed (${Ae}%)]${$.reset}`)}B.percentage>85&&W(`${$.yellow} \u26A0 Context ${Math.round(B.percentage)}% used (${Math.round(100-B.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${$.reset}`);let R=S;if(X&&w&&(R=[R[0],{role:"user",content:`[Server probe at task start]
|
|
1166
|
+
${X}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...R.slice(1)]),w){let Ae=zv(typeof t=="string"?t:"");Ae&&(R=[R[0],{role:"user",content:Ae.user},{role:"assistant",content:Ae.assistant},...R.slice(1)])}if(Zt(R,pt()).percentage>=65){let{messages:Ne,tokensRemoved:qe}=dn(R,pt());qe>0&&(R=Ne,console.log(`${$.dim} [pre-flight compress \u2014 ${qe} tokens freed, now ${Math.round(Zt(R,pt()).percentage)}% used]${$.reset}`))}let ye=0,be=0,pe=0,me=0,xe=0,he=9,ge=0,Re=(()=>{let Ae=H.find(Ne=>Ne.role==="user");return typeof Ae?.content=="string"?Ae.content:""})(),k=/set_reminder|google.?auth|cron:|api\.log|jarvis.{0,30}(fehler|error|fail|broken|crash|nicht.{0,10}(funktioniert|läuft)|debug)|(?:fehler|error|crash|broken|gecrasht|abgestürzt).{0,30}jarvis|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(!st){let Ae=H.filter(qe=>qe.role==="user"||qe.role==="tool").map(qe=>typeof qe.content=="string"?qe.content:"").join(`
|
|
1167
|
+
`),Ne=fl(Ae);Ne&&(st=!0,kt=Ne.slice(0,120),W(`${$.yellow} \u26A1 Root cause in briefing: ${kt} \u2014 fix phase active from start (read budget: 3)${$.reset}`))}!st&&!Bt&&/\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)&&(Bt=!0,W(`${$.cyan} \u26A1 Creation task detected \u2014 tight investigation cap (4 pre-edit, 2 post-edit)${$.reset}`)),H.length<=1&&!n.skipPhaseRouting&&(Te=Wv(),Te&&(ao=Bv(Re)?.id||"coding",Xe="plan",kn=ml("plan",ao),oa=0,dr=0,qn=0,process.stdout.isTTY&&console.log(`${$.dim} \u21B3 Phase routing: plan(${kn||"default"}) \u2192 implement \u2192 verify${$.reset}`),W(`${$.cyan} \u26A1 Phase routing enabled \u2014 plan phase with ${kn||"default model"} (category: ${ao})${$.reset}`)));let x=0,E=new Map,A=new Set,T=new Set,L=Date.now(),ae=new Ov(yk),se=Al,ie=n.skillLoop?10:1,Ce=3*ie,at=5*ie,et=Tl,Tn=5*ie,ba=8*ie,_a=Rl,a$=(Te?6:4)*ie,c$=(Te?10:7)*ie,fu=pr,l$=(Te?5:3)*ie,pu=(Te?8:5)*ie,u$=Cl,d$=(Te?4:3)*ie,f$=(Te?6:4)*ie,p$=3*ie,m$=4*ie,Er=xs,h$=(Te?3:2)*ie,g$=(Te?5:3)*ie,ho=(Te?6:4)*ie,$$=25,Hn=0,y$=6*ie,w$=10*ie,Kn=0,mu=5*ie,Gn=0,b$=2*ie,_$=3,xa=0,go=10,x$=16,hu=n.skillLoop?999:o.investigationCap,Ve,sn=n.maxIterations||(Te?hs(Xe):gl),va=0,gu=3,ka=!1,Tr=0;e:for(;;){for(ka=!1,Ve=0;Ve<sn&&!Ki()?.aborted;Ve++){{let _=pt(),b=Zt(R,_),re=x===0?65:78;if(b.percentage>=re){let{messages:I,tokensRemoved:F}=dn(R,_,x===0);if(F>0&&(R=I,F>50&&console.log(`${$.dim} [auto-compressed \u2014 ~${F} tokens freed, now ${Math.round(Zt(R,_).percentage)}%]${$.reset}`),Bt&&A.size>=3)){let ce=[...A].map(we=>we.split("/").pop()).slice(0,10).join(", "),G={role:"user",content:`[FRAMEWORK \u2014 context compressed] Task is IN PROGRESS. Already created ${A.size} files: ${ce}. DO NOT restart or re-investigate what was already done. Continue from where you left off.`};R.push(G)}}}if(Mt&&!st&&lr<2){lr++;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."};R.push(_),H.push(_),W(`${$.yellow} \u26A0 Pre-call SSH-blocked nudge #${lr} injected \u2014 model told to synthesize${$.reset}`)}Mt||(lr=0);let Ne=!0;x>0&&ok();let qe=null;if(u&&u.isActive())u._paused&&u.resume();else if(!u){let _,b=rk();if(b&&b.total>1){let re=b.description.length>40?b.description.slice(0,37)+"\u2026":b.description;_=`Plan step ${b.current}/${b.total}: ${re}`}else _=x>0?`Thinking... (step ${x+1})`:"Thinking...";qe=new oo(_),qe.start()}let Es=!0,Et="",Ts=!1,ct=new ik,on,Sa=Date.now(),Rr=!1,Ea=new AbortController,$u=setInterval(()=>{let _=Date.now()-Sa;if(_>=ul)ct._clearCursorLine(),W(`${$.yellow} \u26A0 Stream stale for ${Math.round(_/1e3)}s \u2014 aborting and retrying${$.reset}`),Ea.abort();else if(_>=Eh&&!Rr){Rr=!0,ct._clearCursorLine();let b=ta.fast?.[ro()],re=pe>0?` (retry ${pe+1}/${Wi})`:"",I=Math.round((ul-_)/1e3);W(`${$.yellow} \u26A0 No tokens received for ${Math.round(_/1e3)}s \u2014 waiting...${re}${$.reset}`),b&&b!==pn()?console.log(`${$.dim} \u{1F4A1} Will auto-switch to ${b} in ~${I}s if no tokens arrive${$.reset}`):console.log(`${$.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${I}s${$.reset}`)}},5e3),jt="",hn=null;try{let _=Lh(pt()),b=new Set(["read_file","list_directory","search_files","glob","grep","git_status","git_diff","git_log","git_show","ssh_exec"]),re=new Set(["read_file","list_directory","glob","grep","bash","git_status","git_diff","git_log","ssh_exec"]),I;fr()?I=_.filter(G=>Mh.has(G.function.name)):Te&&Xe==="plan"?I=_.filter(G=>b.has(G.function.name)):Te&&Xe==="verify"?I=_.filter(G=>re.has(G.function.name)):I=_;let F=Ki(),ce=new AbortController;F&&F.addEventListener("abort",()=>ce.abort(),{once:!0}),Ea.signal.addEventListener("abort",()=>ce.abort(),{once:!0}),on=await $h(R,I,{signal:ce.signal,...kn?{model:kn}:{},onThinkingToken:()=>{Sa=Date.now(),Rr=!1,mn?.onThinkingToken&&mn.onThinkingToken()},onToken:G=>{if(Sa=Date.now(),Rr=!1,mn?.onToken){mn.onToken(G),Et+=G;return}if(Et+=G,!Ts&&Et.length>400&&Et.length%250<G.length+1){let we=hl(Et,3);we.truncated&&(Ts=!0,ct._clearCursorLine?.(),W(`${$.yellow} \u26A0 LLM stream loop detected (${we.repeatCount}\xD7 repeated) \u2014 suppressing display${$.reset}`))}Ts||(jt+=G,process.stdout.isTTY?hn||(hn=setTimeout(()=>{jt&&ct&&ct.push(jt),jt="",hn=null},50)):(ct.push(jt),jt=""),Es&&(u&&!u._paused?u.pause():qe&&qe.stop(),Ne||(Ne=!0),ct.startCursor(),Es=!1))}})}catch(_){if(clearInterval($u),hn&&(clearTimeout(hn),hn=null),jt&&ct&&(ct.push(jt),jt=""),u&&!u._paused&&u.pause(),qe&&qe.stop(),ct.stopCursor(),Ea.signal.aborted&&!Ki()?.aborted){if(pe++,pe>Wi){if(me<1){me++,so("Stale retries exhausted \u2014 last-resort force-compress...",$.yellow);let we=pt(),{messages:U,tokensRemoved:Y}=dn(R,we);R=U,Y>50&&W(`${$.dim} [force-compressed \u2014 ~${Y} tokens freed]${$.reset}`),pe=0,Ve--;continue}u&&(u.stop(),u=null);let G=await Qk();if(G.action==="quit"){l(null),Qe(x,E,A,T,L),Ze(H);break}G.action==="switch"&&(kh(`${G.provider}:${G.model}`),console.log(`${$.green} \u2713 Switched to ${G.provider}:${G.model}${$.reset}`)),pe=0,Ve--;continue}let F=pe===1?3e3:5e3;if(pe>=1&&ge<1){ge++,so(`Stale retry ${pe}/${Wi} \u2014 force-compressing before retry...`,$.yellow);let G=pt(),{messages:we,tokensRemoved:U}=dn(R,G,!0);if(R=we,U>0&&U>50&&W(`${$.dim} [force-compressed \u2014 ~${U} tokens freed]${$.reset}`),Lk){let Y=ta.fast?.[ro()];Y&&Y!==pn()&&(kh(`${ro()}:${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 W(`${$.yellow} \u26A0 Stale retry ${pe}/${Wi} \u2014 retrying in ${F/1e3}s...${$.reset}`);let ce=new oo(`Waiting ${F/1e3}s before retry...`);ce.start(),await new Promise(G=>setTimeout(G,F)),ce.stop(),Ve--;continue}if(_.name==="AbortError"||_.name==="CanceledError"||_.message?.includes("canceled")||_.message?.includes("aborted")){u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L),Ze(H);break}let b=_.message;if(_.code==="ECONNREFUSED"||_.message.includes("ECONNREFUSED"))b="Connection refused \u2014 please check your internet connection or API endpoint";else if(_.code==="ENOTFOUND"||_.message.includes("ENOTFOUND"))b="Network error \u2014 could not reach the API server. Please check your connection";else if(_.code==="ETIMEDOUT"||_.message.includes("timeout"))b="Request timed out \u2014 the API server took too long to respond. Please try again";else if(_.message.includes("401")||_.message.includes("Unauthorized"))b="Authentication failed \u2014 please check your API key in the .env file";else if(_.message.includes("403")||_.message.includes("Forbidden"))b="Access denied \u2014 your API key may not have permission for this model";else if(_.message.includes("404")){b=`Model not found (404): ${pn?pn():"unknown"} \u2014 check your .env MODEL setting or run /models to list available models`,console.log(`${$.red} \u2717 ${b}${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L),Ze(H);break}else if(_.message.includes("400")){if(me<3&&xe<he){me++,xe++;let F=x===0&&me===1,ce=F||me===3||ge>0;if(F){me=3;let Y=_.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);so(`Bad request (400) \u2014 ${Y||"system prompt too large"}, compressing...`,$.yellow)}else so(ce?`Bad request (400) \u2014 nuclear compression (attempt ${me}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${me}/3)`,$.yellow);let G=pt(),{messages:we,tokensRemoved:U}=dn(R,G,ce);R=we,U>50&&W(`${$.dim} [force-compressed \u2014 ~${U} tokens freed]${$.reset}`),Ve--;continue}{let F=R.find(z=>z.role==="system"),ce=R.find(z=>z.role==="user"&&!String(z.content).startsWith("[SYSTEM")&&!String(z.content).startsWith("BLOCKED:")),G=[F,ce].filter(Boolean),{getUsage:we}=Ct(),U=Ct().estimateMessagesTokens(G),Y=Ct().estimateMessagesTokens(R);if(U<Y){let z=[],ee=H.filter(le=>le.role==="assistant"&&typeof le.content=="string"&&le.content.trim().length>30).slice(-5).map(le=>le.content.trim().slice(0,300).replace(/\n+/g," "));ee.length>0&&z.push(`Key findings:
|
|
1168
|
+
`+ee.map(le=>`- ${le}`).join(`
|
|
1169
|
+
`));let te=H.filter(le=>le.role==="tool"&&typeof le.content=="string"&&!le.content.startsWith("BLOCKED:")&&le.content.trim().length>10).slice(-5).map(le=>le.content.trim().split(`
|
|
1170
1170
|
`).slice(0,8).join(`
|
|
1171
1171
|
`).slice(0,500));if(te.length>0&&z.push(`Tool results summary:
|
|
1172
|
-
`+te.map(
|
|
1173
|
-
`)),A.size>0){let
|
|
1174
|
-
${JSON.stringify($n,null,2)}`)}if(z.length>0){let
|
|
1172
|
+
`+te.map(le=>`- ${le}`).join(`
|
|
1173
|
+
`)),A.size>0){let le=[...A].map(He=>He.split("/").slice(-2).join("/")).join(", ");z.unshift(`Already modified: ${le} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(T.size>0){let le=[...T].map(He=>He.split("/").slice(-2).join("/")).join(", ");z.push(`Files already investigated: ${le}`)}let ue=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(ue,JSON.stringify({filesWritten:[...A].map(le=>le.split("/").slice(-2).join("/")),filesRead:[...T].map(le=>le.split("/").slice(-2).join("/")),isCreationTask:Bt,wipeNumber:cr+1,timestamp:Date.now()},null,2)),z.push(`Session checkpoint: ${ue} \u2014 read it for exact file list`)}catch{}let _e=0;{let He=((typeof ce?.content=="string"?ce.content:Array.isArray(ce?.content)?ce.content.filter(ut=>ut.type==="text").map(ut=>ut.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(ut=>ut.trim()).filter(Boolean),lt=[...A],Kt=He.filter(ut=>!lt.some(Rs=>Rs.endsWith(ut)||ut.endsWith(Rs.split("/").pop())));_e=Kt.length;let Tt=[...H].reverse().find(ut=>ut.role==="tool"&&typeof ut.content=="string"&&!ut.content.startsWith("BLOCKED:")&&ut.content.length>5),$n={completed:lt.map(ut=>ut.split("/").slice(-2).join("/")),pending:Kt.length>0?Kt:lt.length===0?["(task files not yet identified)"]:[],lastEdit:Tt?Tt.content.trim().slice(0,120):null};($n.completed.length>0||$n.pending.length>0)&&z.unshift(`Work manifest:
|
|
1174
|
+
${JSON.stringify($n,null,2)}`)}if(z.length>0){let le={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
|
|
1175
1175
|
${z.join(`
|
|
1176
1176
|
`)}
|
|
1177
|
-
Continue implementing the fixes based on these findings.`};G.push(
|
|
1178
|
-
Files modified so far: ${[...A].map(He=>He.split("/").slice(-1)[0]).join(", ")}`:"";W(`${$.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.${
|
|
1177
|
+
Continue implementing the fixes based on these findings.`};G.push(le)}if(cr>=3){let le=A.size>0?`
|
|
1178
|
+
Files modified so far: ${[...A].map(He=>He.split("/").slice(-1)[0]).join(", ")}`:"";W(`${$.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.${le?$.dim+le:""}${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);break}R=G,cr++,ws=12+Math.min(_e*3,15),bl=!0,Ji=A.size,Vi=!1,Ut=0,j=0;for(let[le,He]of xs){let lt=He?.count??He??0;Rh(xs,le,lt>=2?lt:1)}for(let[le]of Dn)gs(xs,le)<2&&Dn.delete(le);ys.clear(),vs.clear(),Bt&&en>0&&(Qt=!0,W(`${$.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${en} edits already made)${$.reset}`));for(let[le]of pr)Rh(pr,le,pu-1);if(so(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${Y-U} tokens freed)`,$.yellow),cr>=1){let le=[...xs.entries()].filter(([,Tt])=>Tt>=ho).map(([Tt])=>Tt.split("/").slice(-1)[0]),He=le.length>0?`
|
|
1179
1179
|
|
|
1180
|
-
Files already at read cap \u2014 use grep_search instead: ${
|
|
1181
|
-
Use /undo to revert changes made during this session.${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L),Ze(H);break}let F=Math.min(2e3*Math.pow(2,be-1),3e4),
|
|
1180
|
+
Files already at read cap \u2014 use grep_search instead: ${le.join(", ")}`:"",Kt={role:"user",content:Mt&&!st?"[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.${He}`};H.push(Kt),R.push(Kt)}me=0,Ve--;continue}}b="Context too large to compress \u2014 use /clear to start fresh"}else _.message.includes("500")||_.message.includes("502")||_.message.includes("503")||_.message.includes("504")?b="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(_.message.includes("fetch failed")||_.message.includes("fetch"))&&(b="Network request failed \u2014 please check your internet connection");if(console.log(`${$.red} \u2717 ${b}${$.reset}`),_.message.includes("429")){if(ye++,ye>cl){console.log(`${$.red} Rate limit: max retries (${cl}) exceeded. Try again later or use /budget to check your limits.${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L),Ze(H);break}let F=Math.min(1e4*Math.pow(2,ye-1),12e4),ce=new oo(`Rate limit \u2014 waiting ${Math.round(F/1e3)}s (retry ${ye}/${cl})`);ce.start(),await new Promise(G=>setTimeout(G,F)),ce.stop();continue}let re=process.env.NEX_PHASE_ROUTING!=="0"&&(()=>{try{return je().getActiveProviderName()==="ollama"}catch{return!1}})();if(_.message.includes("socket disconnected")||_.message.includes("TLS")||_.message.includes("ECONNRESET")||_.message.includes("ECONNABORTED")||_.message.includes("ETIMEDOUT")||re&&(_.message.includes("500")||_.message.includes("502")||_.message.includes("503")||_.message.includes("504")||_.message.includes("401")||_.message.includes("Unauthorized"))||_.code==="ECONNRESET"||_.code==="ECONNABORTED"){if(be++,be>ll){console.log(`${$.red} Network error: max retries (${ll}) exceeded. Check your connection and try again.
|
|
1181
|
+
Use /undo to revert changes made during this session.${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L),Ze(H);break}let F=Math.min(2e3*Math.pow(2,be-1),3e4),ce=new oo(`API temporarily unavailable \u2014 retrying in ${Math.round(F/1e3)}s (${be}/${ll}). Your changes are safe.`);ce.start(),await new Promise(G=>setTimeout(G,F)),ce.stop(),Ve--;continue}u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L),Ze(H);break}if(clearInterval($u),ye=0,be=0,Es&&(u&&!u._paused&&u.pause(),qe&&qe.stop()),hn&&(clearTimeout(hn),hn=null),jt&&ct&&(ct.push(jt),jt=""),Et&&ct.flush(),be=0,pe=0,on&&on.usage){let _=on.usage.prompt_tokens||0,b=on.usage.completion_tokens||0;bh(ro(),pn(),_,b),d+=_+b,u&&u.setStats({tokens:d})}else if(on&&!on.usage){let _=R.map(I=>typeof I.content=="string"?I.content:Array.isArray(I.content)?I.content.map(F=>typeof F=="string"?F:F.text||"").join(""):"").join(" "),b=xh(_),re=xh(on.content||Et||"");bh(ro(),pn(),b,re),d+=b+re,u&&u.setStats({tokens:d})}let{content:yu,tool_calls:gn}=on,Cr=hl(yu||""),wu=Cr.truncated?Cr.text:yu;Cr.truncated&&W(`${$.yellow} \u26A0 LLM output loop detected (${Cr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${$.reset}`);let Ar=xk(wu||""),rn=Ar.truncated?Ar.text:wu;Ar.truncated&&W(`${$.yellow} \u26A0 LLM output loop detected (${Ar.repeatCount}\xD7 repeated window) \u2014 response truncated${$.reset}`);let Ta={role:"assistant",content:rn||""};if(gn&&gn.length>0&&(Ta.tool_calls=gn),H.push(Ta),R.push(Ta),!st&&rn&&gn&&gn.length>0){let _=fl(rn);if(_){st=!0,kt=_.slice(0,120),fn=0,Qt=!1,vn=0,W(`${$.yellow} \u26A1 Root cause in model analysis: ${kt} \u2014 fix phase (read budget: 3)${$.reset}`);let b={role:"user",content:`[SYSTEM] Root cause identified: ${kt}. Read only the file that needs fixing, then edit it. Do not read other files.`};H.push(b),R.push(b)}}if(!gn||gn.length===0){let _=(rn||"").trim().length>0||Et.trim().length>0,b=!1;if(Mt&&_&&(Hi>=2?W(`${$.yellow} \u26A0 SSH permanently blocked after ${Hi} storm warnings \u2014 no further SSH calls allowed${$.reset}`):(Mt=!1,Ut=go-4,b=!0)),b&&_){let I=(rn||"").trim();if(I.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(I.slice(-200))){let ce={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};R.push(ce),H.push(ce);continue}}if(!_&&x>0&&Ve<gl-1){let I={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."};R.push(I),H.push(I);continue}let re=/keine.*Tool|can.?t use.*tool|Tool.?Budget|nicht.*zugreifen|cannot.*access|no.*tool.*access|keine.*Werkzeug|da ich keine.*kann/i;if(_&&Ve<3&&re.test((rn||"").slice(0,600)))if(bl&&ws<=0||Mt){W(`${$.yellow} \u26A0 Tool avoidance (constrained context) \u2014 telling model to ask user${$.reset}`);let F={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."};R.push(F),H.push(F);continue}else{W(`${$.yellow} \u26A0 Tool avoidance detected \u2014 nudging model to use tools${$.reset}`);let F={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."};R.push(F),H.push(F);continue}if(n.skillLoop&&_&&x>3&&Tr<5){let I=(rn||Et||"").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(I.slice(-600))){Tr=(Tr||0)+1,W(`${$.yellow} \u26A0 Skill loop: model tried to stop \u2014 continuation nudge #${Tr}${$.reset}`);let ce={role:"user",content:"[SYSTEM] Do NOT stop. You are in an autonomous experiment loop. The user is away and expects you to keep running experiments indefinitely until they interrupt with Ctrl+C. Start the next experiment NOW: hypothesize a new change, checkpoint, edit, run, measure, keep or revert. Think harder \u2014 try a completely different optimization approach."};R.push(ce),H.push(ce);continue}}if(Te&&Xe==="plan"&&qn>=2){W(`${$.cyan} \u21B3 Plan phase: ${qn} consecutive blocks \u2014 auto-advancing to implement${$.reset}`),qn=0;let I=rr("implement","[auto-advance: task only requires direct action]");if(I){H.push(I),R.push(I),Ve=0,sn=hs("implement");continue}}if(Te&&_){let I=(rn||Et||"").trim();if(Xe==="plan"){let F=rr("implement",I);if(F){H.push(F),R.push(F),Ve=0,sn=hs("implement");continue}}else if(Xe==="implement"&&A.size>0){let F=H.find(we=>we.role==="user"),ce=typeof F?.content=="string"?F.content:"",G=rr("verify",I,A,ce);if(G){H.push(G),R.push(G),Ve=0,sn=Math.min(hs("verify")+Math.max(0,(A.size-2)*2),20);continue}}else if(Xe==="verify"){let ce=/\bFAIL\b|test.*fail|error|broken|missing|incorrect/i.test(I.slice(0,500));if(ce&&dr<1){dr++;let G={role:"user",content:`[PHASE: RE-IMPLEMENTATION] Verification found issues:
|
|
1182
1182
|
${I.slice(0,400)}
|
|
1183
1183
|
|
|
1184
|
-
Fix the identified issues. This is the final attempt.`};Xe="implement",kn=ml("implement",ao),H.push(G),R.push(G),Ve=0,sn=hs("implement"),W(`${$.yellow} \u21B3 Verify \u2192 implement loop-back #${dr} (issues found)${$.reset}`);continue}W(`${$.green} \u2713 Verification phase complete${
|
|
1184
|
+
Fix the identified issues. This is the final attempt.`};Xe="implement",kn=ml("implement",ao),H.push(G),R.push(G),Ve=0,sn=hs("implement"),W(`${$.yellow} \u21B3 Verify \u2192 implement loop-back #${dr} (issues found)${$.reset}`);continue}W(`${$.green} \u2713 Verification phase complete${ce?" (loop-back exhausted)":" (PASS)"}${$.reset}`)}}if(fr()&&_&&x===0)if(Yi++,Yi>2)W(`${$.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${$.reset}`);else{let I={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.).
|
|
1185
1185
|
|
|
1186
|
-
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(I),R.push(I),W(`${$.yellow} \u26A0 Plan rejected (${Yi}/2): no files read \u2014 forcing investigation${$.reset}`);continue}if(fr()&&_){let I=(rn||Et||"").trim();
|
|
1187
|
-
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${F.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 te=process.stdin.isRaw,
|
|
1188
|
-
`),
|
|
1186
|
+
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(I),R.push(I),W(`${$.yellow} \u26A0 Plan rejected (${Yi}/2): no files read \u2014 forcing investigation${$.reset}`);continue}if(fr()&&_){let I=(rn||Et||"").trim();tk(I),Ik(I);let F=nk(I);if(F.length>0){let ce=H.find(Y=>Y.role==="user"),G=typeof ce?.content=="string"?ce.content.slice(0,120):"Task";sk(G,F);let we=F.length===1?"step":"steps",U=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:Y,startExecution:z,setPlanMode:ee}=Vt();process.stdout.write(`
|
|
1187
|
+
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${F.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 te=process.stdin.isRaw,ue=await new Promise(_e=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",le=>{try{process.stdin.setRawMode(te||!1)}catch{}let He=le.toString().toLowerCase()[0]||"\r";_e(He)})});if(process.stdout.write(`
|
|
1188
|
+
`),ue==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(ue==="e")console.log(`${$.yellow}Type /plan edit to open in editor, or give feedback.${$.reset}`);else if(Y()){z(),ee(!1),yl(),console.log(`${$.green}${$.bold}Approved!${$.reset} Executing ${F.length} ${we}...`);let _e=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1189
1189
|
|
|
1190
1190
|
Implement the following plan step by step. All tools are now available.
|
|
1191
1191
|
|
|
1192
1192
|
${I}`;H.push({role:"user",content:_e}),R.push({role:"user",content:_e}),U=!0}}else console.log(`
|
|
1193
|
-
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${F.length} ${we} extracted).${$.reset} Type ${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ${$.reset}${$.cyan}/plan edit${$.reset}${$.dim} to review.${$.reset}`);if(U){u&&(u.stop(),u=null),Ve--;continue}}else{let
|
|
1193
|
+
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${F.length} ${we} extracted).${$.reset} Type ${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ${$.reset}${$.cyan}/plan edit${$.reset}${$.dim} to review.${$.reset}`);if(U){u&&(u.stop(),u=null),Ve--;continue}}else{let ce=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:G,startExecution:we,setPlanMode:U}=Vt();process.stdout.write(`
|
|
1194
1194
|
${$.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,z=await new Promise(ee=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",te=>{try{process.stdin.setRawMode(Y||!1)}catch{}ee(te.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
|
|
1195
1195
|
`),z==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(G()){we(),U(!1),yl(),console.log(`${$.green}${$.bold}Approved!${$.reset} Executing...`);let te=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1196
1196
|
|
|
1197
1197
|
Implement the following plan step by step. All tools are now available.
|
|
1198
1198
|
|
|
1199
|
-
${getPlanContent()||on.content}`;H.push({role:"user",content:te}),R.push({role:"user",content:te}),
|
|
1200
|
-
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.dim}Type ${$.reset}${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ask follow-up questions to refine.${$.reset}`);if(
|
|
1201
|
-
${G}`),H.push({role:"user",content:I},{role:"assistant",content:G}))}catch{}Ze(H),yh(H);return}x++,oa++,x>=1&&(Ne=!1);for(let _ of gn){let b=_.function.name;E.set(b,(E.get(b)||0)+1)}if(x>=30&&!Ah){Ah=!0,W(`${$.yellow} \u26A0 Tool budget warning: ${x} tool calls used \u2014 nudging model to wrap up${$.reset}`);let _={role:"user",content:"[SYSTEM] \u26A0 You have used "+x+" 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(_),R.push(_)}let Se=await Promise.all(gn.map(_=>Ik(_)));{let _=Zt(R,pt()),b=_.percentage,re=Se.some(G=>G.canExecute&&G.fnName==="read_file"&&!G.args?.line_end),I=Se.filter(G=>G.canExecute&&G.fnName==="read_file"&&G.args?.path&&gs(Er,G.args.path)>=1&&!G.args?.line_start).map(G=>G.args.path.split("/").slice(-2).join("/")),F=I.length>0;if(b>=70&&re&&xa<70||b>=85&&xa<85||F){xa=b;let G=b>=85?"URGENT":"WARNING",we;F?(G="WARNING",we=`Full-file read of ${I.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):re?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 U={role:"user",content:`[SYSTEM ${G}] Context ${Math.round(b)}% used (${_.used}/${_.limit} tokens). ${we}`};if(H.push(U),R.push(U),b>=85){let Y=F?` (re-read of: ${I.join(", ")})`:"";W(`${$.yellow} \u26A0 Context ${Math.round(b)}% used \u2014 agent warned to use targeted reads${Y}${$.reset}`)}}}let Ra=new Map;for(let _ of Se){if(!_.canExecute||_.fnName!=="read_file")continue;let b=_.args?.path;if(!b)continue;let re=gs(Er,b),I=Ra.get(b)||0,F=re+I,ae=_.args?.line_start!=null,G=ys.get(b)||0,we=G>0,U=2;if(F>=ho){let Y=b.split("/").slice(-2).join("/"),z=(vs.get(b)||0)+1;if(vs.set(b,z),z===1)W(`${$.red} \u2716 Blocked: "${Y}" read ${F}\xD7 \u2014 hard cap (${ho}) reached${$.reset}`);else if(z===2){W(`${$.red} \u2716 Escalated block: "${Y}" \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let ee={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 (${ho}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};H.push(ee),R.push(ee)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already read ${F}\xD7 (hard cap: ${ho}). 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(F>=1&&ae)if(we&&G<=U){let Y=b.split("/").slice(-2).join("/");console.log(`${$.cyan} \u21A9 Targeted re-read: "${Y}" (line_start=${_.args.line_start}) \u2014 edit recovery #${G}${$.reset}`),ys.set(b,G-1)}else if(we&&G>U){let Y=b.split("/").slice(-2).join("/");W(`${$.red} \u2716 Edit recovery blocked: "${Y}" \u2014 ${U} 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 (${U} 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,ee=Dn.get(b)||[],te=!1;for(let[le,_e]of ee){let ce=Math.max(Y,le),He=Math.min(z,_e);if(He>ce){let lt=He-ce,Kt=z-Y||1,Tt=_e-le||1,$n=lt/Tt>=.7&</Kt<.7;if(!(z-Y<=g$)&&(lt/Kt>=.7||lt/Tt>=.7)){let Rs=b.split("/").slice(-2).join("/"),ku=`${b}:${Y}-${z}`,Cs=(na.get(ku)||0)+1;if(na.set(ku,Cs),W($n?`${$.red} \u2716 Blocked superread: "${Rs}" lines ${Y}-${z} subsumes already-read ${le}-${_e} \u2014 use line_start=${_e+1} to skip known content (block #${Cs})${$.reset}`:`${$.red} \u2716 Blocked duplicate read: "${Rs}" lines ${Y}-${z} (\u226570% overlap with lines ${le}-${_e} already in context, block #${Cs})${$.reset}`),Cs>=2){W(`${$.red} \u2716 Escalated range-block: "${Rs}" lines ${Y}-${z} \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let Su={role:"user",content:$n?`[SYSTEM] Read blocked ${Cs}\xD7 for read_file("${b}", lines ${Y}-${z}). Lines ${le}-${_e} were already read. Use line_start=${_e+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Cs}\xD7 for read_file("${b}", lines ${Y}-${z}). Lines ${le}-${_e} were already read and will NOT change. Use grep_search to find specific content instead.`};H.push(Su),R.push(Su)}_.canExecute=!1,_.errorResult={role:"tool",content:$n?`BLOCKED: read_file("${b}", lines ${Y}-${z}) re-reads lines ${le}-${_e} already in context. Use line_start=${_e+1} to read only the new content beyond line ${_e}.`:`BLOCKED: read_file("${b}", lines ${Y}-${z}) is a duplicate \u2014 lines ${le}-${_e} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:_.callId},te=!0;break}}}if(!te){let le=ee.length,_e=2;if(le>=3){let He=b.split("/").slice(-2).join("/");W(`${$.red} \u2716 Blocked file-scroll: "${He}" \u2014 ${le} sections already read. Use grep to find specific content.${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 you have already read ${le} 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 le>=_e&&(_._scrollWarn={sectionCount:le+1,path:b})}}else if(F>=1){let Y=b.split("/").slice(-2).join("/"),z=(vs.get(b)||0)+1;if(vs.set(b,z),z===1)W(`${$.red} \u2716 Blocked unbounded re-read: "${Y}" \u2014 already in context. Use line_start/line_end for specific sections.${$.reset}`);else if(z===2){W(`${$.red} \u2716 Escalated block: "${Y}" \u2014 model ignored unbounded re-read block, injecting system warning${$.reset}`);let ee={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(ee),R.push(ee)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already in context (read ${F}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:_.callId}}_.canExecute&&Ra.set(b,(Ra.get(b)||0)+1)}if(jn>=3)for(let _ of Se)_.canExecute&&(_.fnName!=="read_file"&&_.fnName!=="edit_file"||(W(`${$.red} \u2716 Blocked ${_.fnName} \u2014 ${jn} consecutive file-not-found errors, must search first${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${jn} 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 Se){if(!_.canExecute||_.fnName!=="bash")continue;let b=(_.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(b)&&!/npm|yarn|pnpm|make|git/.test(b)){W(`${$.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)&&(W(`${$.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 Se)_.canExecute&&(_.fnName!=="ssh_exec"&&_.fnName!=="bash"||/\bsed\s+-n\b/.test(_.args?.command||"")&&(W(`${$.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 Se){if(!_.canExecute||_.fnName!=="write_file")continue;let b=_.args?.path,re=_.args?.content||"";if(b)try{let I=require("fs"),F=require("path").resolve(process.cwd(),b);if(I.existsSync(F)){let ae=I.statSync(F).size,G=Buffer.byteLength(re,"utf8"),we=ae>0?G/ae:1;if(we<.6&&ae>200){let U=b.split("/").slice(-2).join("/");console.log(`${$.red} \u2716 write_file shrink guard: "${U}" 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 ${G} 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 bu=new Map;for(let _ of Se){if(!_.canExecute||_.fnName!=="grep")continue;let b=_.args?.path;if(!b)continue;let re=bu.get(b)||0,I=gs(fu,b)+re;if(I>=pu){let F=b.split("/").slice(-2).join("/");W(`${$.red} \u2716 Blocked grep: "${F}" grepped ${I}\xD7 with different patterns \u2014 flood threshold exceeded${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: grep("${b}") denied \u2014 ${I} patterns already tried. Use existing results or read the file instead.`,tool_call_id:_.callId}}_.canExecute&&bu.set(b,re+1)}let x$=5,_u=new Map;for(let _ of Se){if(!_.canExecute||_.fnName!=="ssh_exec")continue;let re=(_.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),I=_u.get(re)||0,F=gs(tt,re)+I;F>=x$&&(W(`${$.yellow} \u26A0 Blocked ssh_exec: same command run ${F}\xD7 \u2014 result already in context${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${F} 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&&_u.set(re,I+1)}if(Mt){let _=Se.filter(I=>I.canExecute&&I.fnName==="ssh_exec"),b=Se.some(I=>I.canExecute&&I.fnName!=="ssh_exec"),re=k&&j<3;if(_.length>0&&!b&&re&&Xi<1)Mt=!1,Xi++,Ut=Math.max(0,go-2),W(`${$.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Xi}/1)]${$.reset}`);else for(let I of _)I.canExecute=!1,I.errorResult={role:"tool",content:ot?`BLOCKED: ssh_exec denied \u2014 SSH paused (${go}+ calls). Root cause is known (${kt}). Edit the file now. You can still use bash("ssh user@host 'cmd'") for a single targeted lookup if essential.`:`BLOCKED: ssh_exec denied \u2014 SSH temporarily paused (${go}+ 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:I.callId}}if(k&&j<3&&!Mt){for(let _ of Se)if(_.canExecute&&["bash","read_file","find_files"].includes(_.fnName)){j++;{let b=pt(),{messages:re}=dn(R,b);R=re}W(`${$.yellow} \u26A0 Jarvis-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(!Te&&Qt&&Bt&&en>=1){let _=["read_file","grep","search_files","glob","list_directory","find_files"];for(let b of Se)b.canExecute&&_.includes(b.fnName)&&(W(`${$.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(ws>=0){let _=Se.filter(b=>b.canExecute).length;if(_>0&&(ws-=_,ws<0))if(!Vi&&A.size>Ji){Vi=!0,ws=5,W(`${$.green} \u2713 Post-wipe progress detected (${A.size-Ji} 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),R.push(b)}else{W(`${$.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${$.reset}`);for(let re of Se)re.canExecute&&(re.canExecute=!1,re.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:re.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),R.push(b)}}let v$=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 Se){if(!_.canExecute||v$.has(_.fnName))continue;let b=JSON.stringify(_.args||{}),re=`${_.fnName}|${b}`,I=gs(sa,re);I>=2?(W(`${$.red} \u2716 Blocked duplicate: ${_.fnName}(${b.substring(0,80)}) \u2014 called ${I+1}\xD7 with identical args${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${_.fnName}() with these exact arguments has already been called ${I}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:_.callId}):I===1&&W(`${$.yellow} \u26A0 Duplicate tool call: ${_.fnName}(${b.substring(0,80)}) \u2014 2nd call with identical args${$.reset}`),$s(sa,re)}let $o=u?{skipSpinner:!0,skipSummaries:!0}:{},k$=Se.some(_=>_.fnName==="ask_user"),xu=!$o.skipSummaries&&!Ne,Or=null;xu&&!k$?(Ne=!0,$o.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(Bi(Se,x,!1,"blink")),Or=!0):mn||process.stdout.write(Bi(Se,x,!1)+`
|
|
1202
|
-
`)):xu&&(Ne=!0,$o.skipSpinner=!0),u&&u._paused&&u.resume();let Nr=null;if(Or&&process.stdout.isTTY&&Se.some(b=>b.canExecute&&(b.fnName==="bash"||b.fnName==="ssh_exec"))){let b=Date.now();Nr=setInterval(()=>{let re=Math.round((Date.now()-b)/1e3);re>=3&&process.stdout.write(`\r\x1B[2K${Bi(Se,x,!1,"blink")} ${$.dim}[${re}s]${$.reset}`)},1e3)}let{results:an,summaries:
|
|
1203
|
-
`)),!$o.skipSummaries){let _=
|
|
1204
|
-
`)[0],F=!I.startsWith("ERROR")&&!I.startsWith("CANCELLED")&&!I.startsWith("Command failed")&&!I.startsWith("EXIT");if(!F&&(b.fnName==="edit_file"||b.fnName==="patch_file")&&b.args?.path&&I.includes("old_text not found")){let U=ys.get(b.args.path)||0;ys.set(b.args.path,U+1)}if(!F&&(b.fnName==="read_file"||b.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(I)){if(jn++,jn>=2){W(`${$.yellow} \u26A0 File-not-found streak: ${jn} consecutive misses \u2014 forcing search${$.reset}`);let U={role:"user",content:`[SYSTEM] ${jn} 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(U),R.push(U)}}else F&&(b.fnName==="read_file"||b.fnName==="edit_file"||b.fnName==="search_files"||b.fnName==="glob_files")&&(jn=0);if(F&&b.fnName==="write_file"&&b.args?.path){let U=b.args.path.split("/").pop(),Y=b.args.path.includes("/tests/")||b.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(U)&&!Y){W(`${$.yellow} \u26A0 Temp file: "${U}" \u2014 delete with bash rm when done to keep the workspace clean${$.reset}`);let ee={role:"user",content:`[HINT] "${b.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${b.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};H.push(ee),R.push(ee)}}if(F&&["write_file","edit_file","patch_file"].includes(b.fnName)&&b.args&&b.args.path){ys.delete(b.args.path),A.add(b.args.path);let U=$s(se,b.args.path),Y=b.args.path.split("/").slice(-2).join("/");if(U===
|
|
1205
|
-
`).map(ee=>ee.trim()).find(ee=>ee.length>0&&!ee.startsWith("**")&&(ee.startsWith("EXIT")||/^[\w./-]+:\s/.test(ee)||ee.startsWith("bash:")||ee.startsWith("sh:")))??"";if(z){if(z===Zi?bs++:(Zi=z,bs=1),bs===3&&!Mt){W(`${$.yellow} \u26A0 SSH repeated-error: "${z.slice(0,60)}" returned ${bs}\xD7 \u2014 nudging to change approach${$.reset}`);let ee={role:"user",content:`[SYSTEM WARNING] The last ${bs} SSH commands all failed with the same error: "${z}". 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(ee),R.push(ee)}}else Zi="",bs=0}if(Ut>=
|
|
1206
|
-
`).map(ee=>ee.trim()).find(ee=>ee.length>0&&(ee.startsWith("EXIT")||/^[\w./-]+:\s/.test(ee)||ee.startsWith("bash:")||ee.startsWith("sh:")))??"";if(z){if(z===Qi?_s++:(Qi=z,_s=1),_s===3){W(`${$.yellow} \u26A0 Bash repeated-error: "${z.slice(0,60)}" returned ${_s}\xD7 \u2014 nudging to change approach${$.reset}`);let ee={role:"user",content:`[SYSTEM WARNING] The last ${_s} bash commands all failed with the same error: "${z}". 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(ee),R.push(ee)}}else Qi="",_s=0}if(b.fnName==="bash"&&b.canExecute&&!pl&&b.args?.command){let U=an[_]?.content??"";if(/git\s+commit\b/.test(b.args.command)&&!U.startsWith("EXIT")&&!U.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(U)||U.includes("files changed")||U.includes("file changed")||U.includes("insertions(+)")||U.includes("create mode"))){pl=!0,or=0,W(`${$.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${$.reset}`);let ee={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(ee),R.push(ee)}}if(pl&&b.fnName==="bash"&&b.args?.command&&/git\s+(status|diff|log|show)\b/.test(b.args.command)&&(or++,or>2)){W(`${$.yellow} \u26A0 Post-commit git verification blocked (call ${or})${$.reset}`);let Y={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(or-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),R.push(Y)}if(F&&b.fnName==="grep"&&b.args&&b.args.pattern){let U=`${b.args.pattern}|${b.args.path||""}`,Y=$s(ba,U);if(Y===_a){W(`${$.yellow} \u26A0 Loop warning: grep pattern "${b.args.pattern.slice(0,40)}" run ${Y}\xD7 \u2014 possible search loop${$.reset}`);let z={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${Y}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};H.push(z),R.push(z)}else if(Y>=a$){W(`${$.red} \u2716 Loop abort: grep pattern run ${Y}\xD7 \u2014 aborting runaway search loop${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}if(b.args.path){let z=$s(fu,b.args.path),ee=gs(Er,b.args.path)>=1;if(z===(ee?1:c$)){let le=b.args.path.split("/").slice(-2).join("/");W(`${$.yellow} \u26A0 Loop warning: "${le}" grepped ${z}\xD7 with different patterns \u2014 context flood risk${$.reset}`);let _e={role:"user",content:ee?`[SYSTEM NOTE] "${b.args.path}" was already fully read \u2014 its content is in context. Grepping it again is redundant; use the context you already have.`:`[SYSTEM NOTE] "${b.args.path}" grepped ${z}\xD7 \u2014 use the search results already in context instead of searching again.`};H.push(_e),R.push(_e)}}}if(F&&(b.fnName==="glob"||b.fnName==="glob_files"||b.fnName==="search_files")&&b.args){let U=b.args.pattern||b.args.query||b.args.path||"",Y=$s(l$,U);if(Y===u$){W(`${$.yellow} \u26A0 Loop warning: glob pattern "${U.slice(0,40)}" run ${Y}\xD7 \u2014 possible search loop${$.reset}`);let ee={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${Y}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};H.push(ee),R.push(ee)}else if(Y>=d$){W(`${$.red} \u2716 Loop abort: glob pattern run ${Y}\xD7 \u2014 aborting runaway search loop${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}let z=U.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(ee=>ee.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(ee));for(let ee of z){let te=ee.toLowerCase();mr.has(te)||mr.set(te,new Set);let le=mr.get(te);if(le.add(U),le.size===p$){W(`${$.red} \u2716 Glob core-term block: ${le.size} different patterns all searching for "${te}" \u2014 search loop${$.reset}`);let _e={role:"user",content:`[SYSTEM WARNING] You have searched for "${te}" using ${le.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(_e),R.push(_e)}else if(le.size===f$){W(`${$.yellow} \u26A0 Glob core-term warning: ${le.size} different patterns searching for "${te}"${$.reset}`);let _e={role:"user",content:`[SYSTEM WARNING] ${le.size} different glob patterns all target "${te}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};H.push(_e),R.push(_e)}}}let ae=(b.args?.command||b.args?.cmd||b.args?.script||"").toLowerCase(),G=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(ae)||/\/(health|status|ping|ready|alive)\b/.test(ae);if(F&&(b.fnName==="bash"||b.fnName==="ssh_exec")&&G&&re.includes('"valid":true')){{let Y=pt();if(Zt(R,Y).percentage>=60){let{messages:ee,tokensRemoved:te}=dn(R,Y);te>0&&(R=ee,console.log(`${$.dim} [pre-stop-compress \u2014 ~${te} tokens freed before STOP injection, now ${Math.round(Zt(R,Y).percentage)}%]${$.reset}`))}}let U={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(U),R.push(U),console.log(`${$.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${$.reset}`)}if(re.startsWith("BLOCKED:")){if(Kn++,Kn>=mu){W(`${$.red} \u2716 Loop abort: ${Kn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}}else Kn=0;if(F)Hn=0,ka=!0;else if(Hn++,Hn===$$){W(`${$.yellow} \u26A0 Loop warning: ${Hn} consecutive tool errors \u2014 possible stuck loop${$.reset}`);let U={role:"user",content:`[SYSTEM WARNING] ${Hn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};H.push(U),R.push(U)}else if(Hn>=y$){W(`${$.red} \u2716 Loop abort: ${Hn} consecutive errors \u2014 aborting stuck loop${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}if(F&&b.fnName==="read_file"&&b.args&&b.args.path){T.add(b.args.path);let U=$s(Er,b.args.path);if(b.args.line_start!=null){let te=b.args.line_start||1,le=b.args.line_end||te+350;Dn.has(b.args.path)||Dn.set(b.args.path,[]),Dn.get(b.args.path).push([te,le])}if(b._scrollWarn){let{sectionCount:te,path:le}=b._scrollWarn,_e={role:"user",content:`[SYSTEM WARNING] "${le}" \u2014 you have now read ${te} 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(_e),R.push(_e),W(`${$.yellow} \u26A0 Scroll warning: "${le.split("/").slice(-2).join("/")}" \u2014 ${te} sections read \u2014 use grep instead${$.reset}`)}let Y=b.args.path.split("/").slice(-2).join("/"),z=!b.args?.line_start&&!b.args?.line_end,ee=Te&&Xe==="plan";if(!ee&&z&&U===m$){{let le=pt();if(Zt(R,le).percentage>=60){let{messages:ce}=dn(R,le);R=ce}}W(`${$.yellow} \u26A0 Loop warning: "${Y}" read unbounded ${U}\xD7 \u2014 use line_start/line_end${$.reset}`);let te={role:"user",content:`[SYSTEM WARNING] "${b.args.path}" read ${U}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};H.push(te),R.push(te)}else if(!ee&&z&&U>=h$){W(`${$.red} \u2716 Loop abort: "${Y}" read unbounded ${U}\xD7 \u2014 aborting runaway read loop${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}}if(b.fnName==="spawn_agents"){let U=(re.match(/\bStatus: done\b/g)||[]).length;if((re.match(/\bStatus: truncated\b/g)||[]).length>0&&U===0){if(Gn++,Gn===w$){W(`${$.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${Gn}\xD7 in a row${$.reset}`);let z={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${Gn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};H.push(z),R.push(z)}else if(Gn>=b$){console.log(`${$.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Gn}\xD7 \u2014 aborting stuck swarm${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}}else U>0&&(Gn=0)}}for(let _ of an)H.push(_),R.push(_);if(!ot)for(let _=0;_<an.length;_++){if(!Se[_]||Se[_].fnName!=="ssh_exec")continue;let b=an[_];if(!b||typeof b.content!="string")continue;let re=fl(b.content);if(re){ot=!0,kt=re.slice(0,120),fn=0,Qt=!1,vn=0,W(`${$.yellow} \u26A1 Root cause detected: ${kt} \u2014 fix phase (read budget: 3)${$.reset}`);let I={role:"user",content:`[SYSTEM] Root cause identified: ${kt}. Read only the file that needs fixing, then edit it. Do not read other files.`};H.push(I),R.push(I);break}}for(let _=0;_<an.length;_++){let b=Se[_];if(!b)continue;let re=typeof an[_]?.content=="string"?an[_].content:"";if(b.fnName==="create_task"){let I=re.match(/Task #(\d+) created/),F=typeof b.args?.subject=="string"?b.args.subject:"";I&&F&&hr.set(I[1],F)}else if((b.fnName==="write_file"||b.fnName==="edit_file")&&!re.startsWith("BLOCKED:")&&re.trim().length>0){let F=(typeof b.args?.path=="string"?b.args.path:typeof b.args?.file_path=="string"?b.args.file_path:"").split("/").pop().toLowerCase(),ae=F.split(/[._\-/]/).filter(G=>G.length>2);for(let[G,we]of hr){if(gr.has(G))continue;let U=we.toLowerCase().split(/\W+/).filter(z=>z.length>3);ae.filter(z=>U.some(ee=>ee.includes(z)||z.includes(ee))).length>=1&&(gr.add(G),W(`${$.green} \u2714 Auto-matched task #${G} to ${F}: ${we.slice(0,60)}${$.reset}`))}}}{let _=pt();if(Zt(R,_).percentage>=78){let{messages:re,tokensRemoved:I}=dn(R,_);I>0&&(R=re,console.log(`${$.dim} [auto-compressed \u2014 ~${I} tokens freed, now ${Math.round(Zt(R,_).percentage)}%]${$.reset}`))}}let vu=Bk();if(vu){let _={role:"user",content:`[User note mid-run]: ${vu}`};H.push(_),R.push(_),console.log(`${$.cyan} \u270E Context added${$.reset}`)}}if(Ve>=sn){if(u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L),Ze(H),yh(H),Te&&Xe==="plan"){let Es=[...H].reverse().find(ct=>ct.role==="assistant"),Et=typeof Es?.content=="string"?Es.content:"",Ts=rr("implement",Et);if(Ts){H.push(Ts),R=[{role:"system",content:await kl()},...H],sn=hs("implement"),W(`${$.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${$.reset}`);continue e}}else if(Te&&Xe==="verify"){W(`${$.yellow} \u26A0 Verify budget exhausted \u2014 completing session${$.reset}`);break e}let{getActiveProviderName:Ae}=je();if(Ae()==="ollama"&&va<gu){if(A.size===0&&!ka){console.log(`${$.yellow} \u26A0 Max iterations reached with no progress. Stopping.${$.reset}`);break e}va++,sn=20,console.log(`${$.dim} \u2500\u2500 auto-extending (+20 turns, ext ${va}/${gu}) \u2500\u2500${$.reset}`);continue e}if(console.log(`
|
|
1207
|
-
${$.yellow}\u26A0 Max iterations reached.${$.reset}`),await Nh(" Continue for 20 more turns?")){sn=20;continue e}console.log(`${$.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${$.reset}`)}break e}}qh.exports={processInput:
|
|
1199
|
+
${getPlanContent()||on.content}`;H.push({role:"user",content:te}),R.push({role:"user",content:te}),ce=!0}}else console.log(`
|
|
1200
|
+
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.dim}Type ${$.reset}${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ask follow-up questions to refine.${$.reset}`);if(ce){u&&(u.stop(),u=null),Ve--;continue}}}if(u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L),Bt&&A.size>=3){let I=[...A].map(U=>U.split("/").pop()).slice(0,8).join(", "),F=[...A].some(U=>U.endsWith("package.json")),ce=[...A].some(U=>U.endsWith("requirements.txt")),G=[...A].some(U=>U.endsWith("package-lock.json")||U.endsWith("yarn.lock")||U.endsWith("pnpm-lock.yaml")),we=F&&!G?"npm install not yet run":ce?"pip install not yet run":null;ur=`[Previous session created ${A.size} files: ${I}`+(we?` \u2014 ${we}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Bt&&!_l&&x>0){let I=[...A].some(te=>te.endsWith("package.json")),F=[...A].some(te=>te.endsWith("requirements.txt")||te.endsWith("Pipfile")||te.endsWith("pyproject.toml")),ce=[...A].some(te=>te.endsWith("package-lock.json")||te.endsWith("yarn.lock")||te.endsWith("pnpm-lock.yaml")),G=H.flatMap(te=>{let ue=Array.isArray(te.tool_calls)?te.tool_calls:[],_e=Array.isArray(te.content)?te.content.filter(le=>le?.type==="tool_use"):[];return[...ue,..._e]}).filter(te=>{let ue=te.function?.name||te.name||"";return ue==="bash"||ue==="Bash"}).map(te=>{try{let ue=te.function?.arguments??te.input??{};return(typeof ue=="string"?JSON.parse(ue):ue)?.command||""}catch{return""}}),we=G.some(te=>/pip\s+install|python\s+-m\s+venv/.test(te)),U=G.some(te=>/npm\s+install/.test(te)),z=[...A].some(te=>/\/App\.(js|ts|jsx|tsx)$/.test(te))&&!I&&!U;if(F&&!we||I&&!ce&&!U||z){_l=!0;let te=[];F&&!we&&te.push("python -m venv venv && source venv/bin/activate && pip install -r requirements.txt"),z?te.push("create package.json for the React frontend (with react, react-dom, react-scripts dependencies), then run npm install"):I&&!ce&&!U&&te.push("npm install");let ue=`[FRAMEWORK \u2014 post-creation check] You wrote dependency files but never ran the installer. Run now: ${te.join(" && ")}. Verify it succeeds, fix any errors, then write a closing summary.`;W(`${$.dim} [post-creation] bootstrapping environment (${te.join(", ")})${$.reset}`),H.push({role:"user",content:ue}),R.push({role:"user",content:ue});continue}}if(x>0&&!n._isSummaryTurn&&Hv(rn))try{W(`${$.dim} [post-turn] terse ending \u2014 requesting diagnosis/summary${$.reset}`);let I=A.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.",F=[...R,{role:"user",content:I}],G=((await $h(F,[],{}))?.content||"").trim();G&&(console.log(`
|
|
1201
|
+
${G}`),H.push({role:"user",content:I},{role:"assistant",content:G}))}catch{}Ze(H),yh(H);return}x++,oa++,x>=1&&(Ne=!1);for(let _ of gn){let b=_.function.name;E.set(b,(E.get(b)||0)+1)}if(x>=30&&!Ah){Ah=!0,W(`${$.yellow} \u26A0 Tool budget warning: ${x} tool calls used \u2014 nudging model to wrap up${$.reset}`);let _={role:"user",content:"[SYSTEM] \u26A0 You have used "+x+" 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(_),R.push(_)}let Se=await Promise.all(gn.map(_=>jk(_)));{let _=Zt(R,pt()),b=_.percentage,re=Se.some(G=>G.canExecute&&G.fnName==="read_file"&&!G.args?.line_end),I=Se.filter(G=>G.canExecute&&G.fnName==="read_file"&&G.args?.path&&gs(Er,G.args.path)>=1&&!G.args?.line_start).map(G=>G.args.path.split("/").slice(-2).join("/")),F=I.length>0;if(b>=70&&re&&xa<70||b>=85&&xa<85||F){xa=b;let G=b>=85?"URGENT":"WARNING",we;F?(G="WARNING",we=`Full-file read of ${I.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):re?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 U={role:"user",content:`[SYSTEM ${G}] Context ${Math.round(b)}% used (${_.used}/${_.limit} tokens). ${we}`};if(H.push(U),R.push(U),b>=85){let Y=F?` (re-read of: ${I.join(", ")})`:"";W(`${$.yellow} \u26A0 Context ${Math.round(b)}% used \u2014 agent warned to use targeted reads${Y}${$.reset}`)}}}let Ra=new Map;for(let _ of Se){if(!_.canExecute||_.fnName!=="read_file")continue;let b=_.args?.path;if(!b)continue;let re=gs(Er,b),I=Ra.get(b)||0,F=re+I,ce=_.args?.line_start!=null,G=ys.get(b)||0,we=G>0,U=2;if(F>=ho){let Y=b.split("/").slice(-2).join("/"),z=(vs.get(b)||0)+1;if(vs.set(b,z),z===1)W(`${$.red} \u2716 Blocked: "${Y}" read ${F}\xD7 \u2014 hard cap (${ho}) reached${$.reset}`);else if(z===2){W(`${$.red} \u2716 Escalated block: "${Y}" \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let ee={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 (${ho}\xD7). Do NOT attempt to read it again. Use grep_search to find specific content, or proceed with what you already know.`};H.push(ee),R.push(ee)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already read ${F}\xD7 (hard cap: ${ho}). 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(F>=1&&ce)if(we&&G<=U){let Y=b.split("/").slice(-2).join("/");console.log(`${$.cyan} \u21A9 Targeted re-read: "${Y}" (line_start=${_.args.line_start}) \u2014 edit recovery #${G}${$.reset}`),ys.set(b,G-1)}else if(we&&G>U){let Y=b.split("/").slice(-2).join("/");W(`${$.red} \u2716 Edit recovery blocked: "${Y}" \u2014 ${U} 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 (${U} 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,ee=Dn.get(b)||[],te=!1;for(let[ue,_e]of ee){let le=Math.max(Y,ue),He=Math.min(z,_e);if(He>le){let lt=He-le,Kt=z-Y||1,Tt=_e-ue||1,$n=lt/Tt>=.7&</Kt<.7;if(!(z-Y<=$$)&&(lt/Kt>=.7||lt/Tt>=.7)){let Rs=b.split("/").slice(-2).join("/"),ku=`${b}:${Y}-${z}`,Cs=(na.get(ku)||0)+1;if(na.set(ku,Cs),W($n?`${$.red} \u2716 Blocked superread: "${Rs}" lines ${Y}-${z} subsumes already-read ${ue}-${_e} \u2014 use line_start=${_e+1} to skip known content (block #${Cs})${$.reset}`:`${$.red} \u2716 Blocked duplicate read: "${Rs}" lines ${Y}-${z} (\u226570% overlap with lines ${ue}-${_e} already in context, block #${Cs})${$.reset}`),Cs>=2){W(`${$.red} \u2716 Escalated range-block: "${Rs}" lines ${Y}-${z} \u2014 model ignored BLOCKED, injecting system warning${$.reset}`);let Su={role:"user",content:$n?`[SYSTEM] Read blocked ${Cs}\xD7 for read_file("${b}", lines ${Y}-${z}). Lines ${ue}-${_e} were already read. Use line_start=${_e+1} to read only new content, or use grep_search for specific lines.`:`[SYSTEM] Read blocked ${Cs}\xD7 for read_file("${b}", lines ${Y}-${z}). Lines ${ue}-${_e} were already read and will NOT change. Use grep_search to find specific content instead.`};H.push(Su),R.push(Su)}_.canExecute=!1,_.errorResult={role:"tool",content:$n?`BLOCKED: read_file("${b}", lines ${Y}-${z}) re-reads lines ${ue}-${_e} already in context. Use line_start=${_e+1} to read only the new content beyond line ${_e}.`:`BLOCKED: read_file("${b}", lines ${Y}-${z}) is a duplicate \u2014 lines ${ue}-${_e} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:_.callId},te=!0;break}}}if(!te){let ue=ee.length,_e=2;if(ue>=3){let He=b.split("/").slice(-2).join("/");W(`${$.red} \u2716 Blocked file-scroll: "${He}" \u2014 ${ue} sections already read. Use grep to find specific content.${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 you have already read ${ue} 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 ue>=_e&&(_._scrollWarn={sectionCount:ue+1,path:b})}}else if(F>=1){let Y=b.split("/").slice(-2).join("/"),z=(vs.get(b)||0)+1;if(vs.set(b,z),z===1)W(`${$.red} \u2716 Blocked unbounded re-read: "${Y}" \u2014 already in context. Use line_start/line_end for specific sections.${$.reset}`);else if(z===2){W(`${$.red} \u2716 Escalated block: "${Y}" \u2014 model ignored unbounded re-read block, injecting system warning${$.reset}`);let ee={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(ee),R.push(ee)}_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: read_file("${b}") denied \u2014 file already in context (read ${F}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:_.callId}}_.canExecute&&Ra.set(b,(Ra.get(b)||0)+1)}if(jn>=3)for(let _ of Se)_.canExecute&&(_.fnName!=="read_file"&&_.fnName!=="edit_file"||(W(`${$.red} \u2716 Blocked ${_.fnName} \u2014 ${jn} consecutive file-not-found errors, must search first${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${jn} 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 Se){if(!_.canExecute||_.fnName!=="bash")continue;let b=(_.args?.command||"").trim();if(/^\s*ls(\s+-[a-zA-Z]+)*(\s+\S+)?\s*$/.test(b)&&!/npm|yarn|pnpm|make|git/.test(b)){W(`${$.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)&&(W(`${$.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 Se)_.canExecute&&(_.fnName!=="ssh_exec"&&_.fnName!=="bash"||/\bsed\s+-n\b/.test(_.args?.command||"")&&(W(`${$.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 Se){if(!_.canExecute||_.fnName!=="write_file")continue;let b=_.args?.path,re=_.args?.content||"";if(b)try{let I=require("fs"),F=require("path").resolve(process.cwd(),b);if(I.existsSync(F)){let ce=I.statSync(F).size,G=Buffer.byteLength(re,"utf8"),we=ce>0?G/ce:1;if(we<.6&&ce>200){let U=b.split("/").slice(-2).join("/");console.log(`${$.red} \u2716 write_file shrink guard: "${U}" 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 (${ce} \u2192 ${G} 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 bu=new Map;for(let _ of Se){if(!_.canExecute||_.fnName!=="grep")continue;let b=_.args?.path;if(!b)continue;let re=bu.get(b)||0,I=gs(fu,b)+re;if(I>=pu){let F=b.split("/").slice(-2).join("/");W(`${$.red} \u2716 Blocked grep: "${F}" grepped ${I}\xD7 with different patterns \u2014 flood threshold exceeded${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: grep("${b}") denied \u2014 ${I} patterns already tried. Use existing results or read the file instead.`,tool_call_id:_.callId}}_.canExecute&&bu.set(b,re+1)}let v$=5,_u=new Map;for(let _ of Se){if(!_.canExecute||_.fnName!=="ssh_exec")continue;let re=(_.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),I=_u.get(re)||0,F=gs(et,re)+I;F>=v$&&(W(`${$.yellow} \u26A0 Blocked ssh_exec: same command run ${F}\xD7 \u2014 result already in context${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 this command has already run ${F} 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&&_u.set(re,I+1)}if(Mt){let _=Se.filter(I=>I.canExecute&&I.fnName==="ssh_exec"),b=Se.some(I=>I.canExecute&&I.fnName!=="ssh_exec"),re=k&&j<3;if(_.length>0&&!b&&re&&Xi<1)Mt=!1,Xi++,Ut=Math.max(0,go-2),W(`${$.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Xi}/1)]${$.reset}`);else for(let I of _)I.canExecute=!1,I.errorResult={role:"tool",content:st?`BLOCKED: ssh_exec denied \u2014 SSH paused (${go}+ calls). Root cause is known (${kt}). Edit the file now. You can still use bash("ssh user@host 'cmd'") for a single targeted lookup if essential.`:`BLOCKED: ssh_exec denied \u2014 SSH temporarily paused (${go}+ 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:I.callId}}if(k&&j<3&&!Mt){for(let _ of Se)if(_.canExecute&&["bash","read_file","find_files"].includes(_.fnName)){j++;{let b=pt(),{messages:re}=dn(R,b);R=re}W(`${$.yellow} \u26A0 Jarvis-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(!Te&&Qt&&Bt&&en>=1){let _=["read_file","grep","search_files","glob","list_directory","find_files"];for(let b of Se)b.canExecute&&_.includes(b.fnName)&&(W(`${$.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(ws>=0){let _=Se.filter(b=>b.canExecute).length;if(_>0&&(ws-=_,ws<0))if(!Vi&&A.size>Ji){Vi=!0,ws=5,W(`${$.green} \u2713 Post-wipe progress detected (${A.size-Ji} 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),R.push(b)}else{W(`${$.red} \u2716 Post-wipe tool budget exhausted \u2014 blocking all tool calls${$.reset}`);for(let re of Se)re.canExecute&&(re.canExecute=!1,re.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:re.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),R.push(b)}}let k$=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 Se){if(!_.canExecute||k$.has(_.fnName))continue;let b=JSON.stringify(_.args||{}),re=`${_.fnName}|${b}`,I=gs(sa,re);I>=2?(W(`${$.red} \u2716 Blocked duplicate: ${_.fnName}(${b.substring(0,80)}) \u2014 called ${I+1}\xD7 with identical args${$.reset}`),_.canExecute=!1,_.errorResult={role:"tool",content:`BLOCKED: ${_.fnName}() with these exact arguments has already been called ${I}\xD7 \u2014 the result is already in your context. Use the existing output instead of repeating the same call.`,tool_call_id:_.callId}):I===1&&W(`${$.yellow} \u26A0 Duplicate tool call: ${_.fnName}(${b.substring(0,80)}) \u2014 2nd call with identical args${$.reset}`),$s(sa,re)}let $o=u?{skipSpinner:!0,skipSummaries:!0}:{},S$=Se.some(_=>_.fnName==="ask_user"),xu=!$o.skipSummaries&&!Ne,Or=null;xu&&!S$?(Ne=!0,$o.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(Bi(Se,x,!1,"blink")),Or=!0):mn||process.stdout.write(Bi(Se,x,!1)+`
|
|
1202
|
+
`)):xu&&(Ne=!0,$o.skipSpinner=!0),u&&u._paused&&u.resume();let Nr=null;if(Or&&process.stdout.isTTY&&Se.some(b=>b.canExecute&&(b.fnName==="bash"||b.fnName==="ssh_exec"))){let b=Date.now();Nr=setInterval(()=>{let re=Math.round((Date.now()-b)/1e3);re>=3&&process.stdout.write(`\r\x1B[2K${Bi(Se,x,!1,"blink")} ${$.dim}[${re}s]${$.reset}`)},1e3)}let{results:an,summaries:E$}=await Uk(Se,!0,{...$o,skipSummaries:!0});if(Nr&&(clearInterval(Nr),Nr=null),Or&&(Or=null,process.stdout.write(`\r\x1B[2K${Bi(Se,x,!1)}
|
|
1203
|
+
`)),!$o.skipSummaries){let _=E$.filter((I,F)=>!(Se[F]&&Se[F].fnName==="ask_user"));for(let I of _)console.log(I);console.log("");let b=Se.filter(I=>I&&I.fnName!=="ask_user").map(I=>I.fnName),re=ae.record(0,b,T,A);re&&wk(re)}for(let _ of Se){if(_.canExecute||!_.errorResult)continue;let b=typeof _.errorResult.content=="string"?_.errorResult.content:"";if((b.startsWith("BLOCKED:")||b.startsWith("PLAN MODE:"))&&(Kn++,Kn>=mu)){W(`${$.red} \u2716 Loop abort: ${Kn} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}}for(let _=0;_<Se.length;_++){let b=Se[_];if(!b.canExecute)continue;let re=an[_].content,I=re.split(`
|
|
1204
|
+
`)[0],F=!I.startsWith("ERROR")&&!I.startsWith("CANCELLED")&&!I.startsWith("Command failed")&&!I.startsWith("EXIT");if(!F&&(b.fnName==="edit_file"||b.fnName==="patch_file")&&b.args?.path&&I.includes("old_text not found")){let U=ys.get(b.args.path)||0;ys.set(b.args.path,U+1)}if(!F&&(b.fnName==="read_file"||b.fnName==="edit_file")&&/file not found|does not exist|ENOENT/i.test(I)){if(jn++,jn>=2){W(`${$.yellow} \u26A0 File-not-found streak: ${jn} consecutive misses \u2014 forcing search${$.reset}`);let U={role:"user",content:`[SYSTEM] ${jn} 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(U),R.push(U)}}else F&&(b.fnName==="read_file"||b.fnName==="edit_file"||b.fnName==="search_files"||b.fnName==="glob_files")&&(jn=0);if(F&&b.fnName==="write_file"&&b.args?.path){let U=b.args.path.split("/").pop(),Y=b.args.path.includes("/tests/")||b.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(U)&&!Y){W(`${$.yellow} \u26A0 Temp file: "${U}" \u2014 delete with bash rm when done to keep the workspace clean${$.reset}`);let ee={role:"user",content:`[HINT] "${b.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${b.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};H.push(ee),R.push(ee)}}if(F&&["write_file","edit_file","patch_file"].includes(b.fnName)&&b.args&&b.args.path){ys.delete(b.args.path),A.add(b.args.path);let U=$s(se,b.args.path),Y=b.args.path.split("/").slice(-2).join("/");if(U===Ce){W(`${$.yellow} \u26A0 Loop warning: "${Y}" edited ${U}\xD7 \u2014 possible edit loop${$.reset}`);let z={role:"user",content:`[SYSTEM WARNING] "${b.args.path}" edited ${U}\xD7. One more edit max, then move on.`};H.push(z),R.push(z)}else if(U>=at){W(`${$.red} \u2716 Loop abort: "${Y}" edited ${U}\xD7 \u2014 aborting to prevent runaway loop${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}}if(F&&b.canExecute&&Te&&(qn=0),F&&b.canExecute&&!(Te&&Xe==="plan")){let U=["read_file","grep","search_files","glob","list_directory","ssh_exec","find_files"];["write_file","edit_file","patch_file"].includes(b.fnName)?(fn=0,Qt=!1,vn=0,en++):U.includes(b.fnName)&&(fn++,Qt&&vn++);let z=o.postEditCap,ee=Te&&Xe==="implement"?Math.min(hu,6):hu,te=st?3:Bt?en>0?2:4:en>0?z:ee,ue=3;if(!Te&&Qt&&(st||Bt&&en>=1||vn>=ue)&&U.includes(b.fnName)){let le=st?`root cause already identified (${kt})`:vn>=ue?`${fn} consecutive reads without an edit`:`${en} file edit(s) already made`;W(`${$.red} \u2716 Blocked read-only tool: cap fired, ${le}${$.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:st?`BLOCKED: root cause already identified (${kt}). Use edit_file to fix the issue \u2014 do not read more files.`:Bt?"BLOCKED: files already written \u2014 continue with write_file or edit_file to finish the remaining tasks. Do not read more files.":vn>=ue?`BLOCKED: You have read ${fn} 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: ${en} file edit(s) already made and post-edit investigation cap reached. The fix is in place. Do not read more files \u2014 proceed with the task.`,tool_call_id:b.callId}}else if(fn>=te&&!Qt){if(Qt=!0,W(`${$.yellow} \u26A0 Investigation cap: ${fn} read-only calls without an edit \u2014 forcing implementation${$.reset}`),Te&&Xe==="plan"){let lt=[...R].reverse().find($n=>$n.role==="assistant"),Kt=typeof lt?.content=="string"?lt.content:"",Tt=rr("implement",Kt);Tt&&(H.push(Tt),R.push(Tt),Ve=0,sn=hs("implement"))}let le;st?le=`[SYSTEM] Root cause was already identified (${kt}). Edit the file now \u2014 do not read more files.`:Mt?le="[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.":le="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let He={role:"user",content:le};H.push(He),R.push(He)}}if((b.fnName==="bash"||b.fnName==="ssh_exec")&&b.args&&b.args.command){let U=b.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),Y=$s(et,U);if(Y===Tn){W(`${$.yellow} \u26A0 Loop warning: same bash command run ${Y}\xD7 \u2014 possible debug loop${$.reset}`);let z={role:"user",content:`[SYSTEM WARNING] Same bash command ${Y}\xD7. Debug loop detected \u2014 try a different approach.`};H.push(z),R.push(z)}else if(Y>=ba){W(`${$.red} \u2716 Loop abort: same bash command run ${Y}\xD7 \u2014 aborting runaway debug loop${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}}if(b.fnName==="ssh_exec"){Ut++;{let z=(an[_]?.content??"").split(`
|
|
1205
|
+
`).map(ee=>ee.trim()).find(ee=>ee.length>0&&!ee.startsWith("**")&&(ee.startsWith("EXIT")||/^[\w./-]+:\s/.test(ee)||ee.startsWith("bash:")||ee.startsWith("sh:")))??"";if(z){if(z===Zi?bs++:(Zi=z,bs=1),bs===3&&!Mt){W(`${$.yellow} \u26A0 SSH repeated-error: "${z.slice(0,60)}" returned ${bs}\xD7 \u2014 nudging to change approach${$.reset}`);let ee={role:"user",content:`[SYSTEM WARNING] The last ${bs} SSH commands all failed with the same error: "${z}". 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(ee),R.push(ee)}}else Zi="",bs=0}if(Ut>=x$){W(`${$.red} \u2716 SSH storm abort: ${Ut} consecutive ssh_exec calls \u2014 aborting${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}else if(Ut===go){{let z=pt(),{messages:ee}=dn(R,z);R=ee}Mt=!0,Hi++,W(`${$.yellow} \u26A0 SSH storm warning (#${Hi}): ${Ut} consecutive ssh_exec calls \u2014 blocking further SSH${$.reset}`);let Y={role:"user",content:st?`[SYSTEM WARNING] ${Ut} consecutive SSH calls. Root cause identified (${kt}). Read the file that needs fixing, then edit it.`:`[SYSTEM WARNING] ${Ut} 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),R.push(Y)}}else b.canExecute&&(Ut=0);if(b.fnName==="bash"&&b.canExecute){let z=(an[_]?.content??"").split(`
|
|
1206
|
+
`).map(ee=>ee.trim()).find(ee=>ee.length>0&&(ee.startsWith("EXIT")||/^[\w./-]+:\s/.test(ee)||ee.startsWith("bash:")||ee.startsWith("sh:")))??"";if(z){if(z===Qi?_s++:(Qi=z,_s=1),_s===3){W(`${$.yellow} \u26A0 Bash repeated-error: "${z.slice(0,60)}" returned ${_s}\xD7 \u2014 nudging to change approach${$.reset}`);let ee={role:"user",content:`[SYSTEM WARNING] The last ${_s} bash commands all failed with the same error: "${z}". 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(ee),R.push(ee)}}else Qi="",_s=0}if(b.fnName==="bash"&&b.canExecute&&!pl&&b.args?.command){let U=an[_]?.content??"";if(/git\s+commit\b/.test(b.args.command)&&!U.startsWith("EXIT")&&!U.startsWith("ERROR")&&(/\[\S+\s+[a-f0-9]+\]/.test(U)||U.includes("files changed")||U.includes("file changed")||U.includes("insertions(+)")||U.includes("create mode"))){pl=!0,or=0,W(`${$.green} \u2713 Git commit detected \u2014 post-commit verification cap active (max 2 git status/diff/log)${$.reset}`);let ee={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(ee),R.push(ee)}}if(pl&&b.fnName==="bash"&&b.args?.command&&/git\s+(status|diff|log|show)\b/.test(b.args.command)&&(or++,or>2)){W(`${$.yellow} \u26A0 Post-commit git verification blocked (call ${or})${$.reset}`);let Y={role:"user",content:"[SYSTEM] \u26A0 STOP: You already ran "+(or-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),R.push(Y)}if(F&&b.fnName==="grep"&&b.args&&b.args.pattern){let U=`${b.args.pattern}|${b.args.path||""}`,Y=$s(_a,U);if(Y===a$){W(`${$.yellow} \u26A0 Loop warning: grep pattern "${b.args.pattern.slice(0,40)}" run ${Y}\xD7 \u2014 possible search loop${$.reset}`);let z={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${Y}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};H.push(z),R.push(z)}else if(Y>=c$){W(`${$.red} \u2716 Loop abort: grep pattern run ${Y}\xD7 \u2014 aborting runaway search loop${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}if(b.args.path){let z=$s(fu,b.args.path),ee=gs(Er,b.args.path)>=1;if(z===(ee?1:l$)){let ue=b.args.path.split("/").slice(-2).join("/");W(`${$.yellow} \u26A0 Loop warning: "${ue}" grepped ${z}\xD7 with different patterns \u2014 context flood risk${$.reset}`);let _e={role:"user",content:ee?`[SYSTEM NOTE] "${b.args.path}" was already fully read \u2014 its content is in context. Grepping it again is redundant; use the context you already have.`:`[SYSTEM NOTE] "${b.args.path}" grepped ${z}\xD7 \u2014 use the search results already in context instead of searching again.`};H.push(_e),R.push(_e)}}}if(F&&(b.fnName==="glob"||b.fnName==="glob_files"||b.fnName==="search_files")&&b.args){let U=b.args.pattern||b.args.query||b.args.path||"",Y=$s(u$,U);if(Y===d$){W(`${$.yellow} \u26A0 Loop warning: glob pattern "${U.slice(0,40)}" run ${Y}\xD7 \u2014 possible search loop${$.reset}`);let ee={role:"user",content:`[SYSTEM WARNING] Same glob/search pattern ${Y}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};H.push(ee),R.push(ee)}else if(Y>=f$){W(`${$.red} \u2716 Loop abort: glob pattern run ${Y}\xD7 \u2014 aborting runaway search loop${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}let z=U.replace(/\*+/g," ").replace(/[{}()\[\],.\/\\]/g," ").split(/\s+/).filter(ee=>ee.length>=4&&!/^\.(js|ts|py|json|md|yaml|yml|txt|css|html|sh)$/.test(ee));for(let ee of z){let te=ee.toLowerCase();mr.has(te)||mr.set(te,new Set);let ue=mr.get(te);if(ue.add(U),ue.size===m$){W(`${$.red} \u2716 Glob core-term block: ${ue.size} different patterns all searching for "${te}" \u2014 search loop${$.reset}`);let _e={role:"user",content:`[SYSTEM WARNING] You have searched for "${te}" using ${ue.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(_e),R.push(_e)}else if(ue.size===p$){W(`${$.yellow} \u26A0 Glob core-term warning: ${ue.size} different patterns searching for "${te}"${$.reset}`);let _e={role:"user",content:`[SYSTEM WARNING] ${ue.size} different glob patterns all target "${te}". If previous searches returned no results, the file probably does not exist \u2014 stop searching and proceed with available information.`};H.push(_e),R.push(_e)}}}let ce=(b.args?.command||b.args?.cmd||b.args?.script||"").toLowerCase(),G=/\b(health|healthcheck|health-check|status|check|ping|validate|alive|ready)\b/.test(ce)||/\/(health|status|ping|ready|alive)\b/.test(ce);if(F&&(b.fnName==="bash"||b.fnName==="ssh_exec")&&G&&re.includes('"valid":true')){{let Y=pt();if(Zt(R,Y).percentage>=60){let{messages:ee,tokensRemoved:te}=dn(R,Y);te>0&&(R=ee,console.log(`${$.dim} [pre-stop-compress \u2014 ~${te} tokens freed before STOP injection, now ${Math.round(Zt(R,Y).percentage)}%]${$.reset}`))}}let U={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(U),R.push(U),console.log(`${$.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${$.reset}`)}if(re.startsWith("BLOCKED:")){if(Kn++,Kn>=mu){W(`${$.red} \u2716 Loop abort: ${Kn} consecutive blocked calls \u2014 model not heeding BLOCKED messages${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}}else Kn=0;if(F)Hn=0,ka=!0;else if(Hn++,Hn===y$){W(`${$.yellow} \u26A0 Loop warning: ${Hn} consecutive tool errors \u2014 possible stuck loop${$.reset}`);let U={role:"user",content:`[SYSTEM WARNING] ${Hn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};H.push(U),R.push(U)}else if(Hn>=w$){W(`${$.red} \u2716 Loop abort: ${Hn} consecutive errors \u2014 aborting stuck loop${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}if(F&&b.fnName==="read_file"&&b.args&&b.args.path){T.add(b.args.path);let U=$s(Er,b.args.path);if(b.args.line_start!=null){let te=b.args.line_start||1,ue=b.args.line_end||te+350;Dn.has(b.args.path)||Dn.set(b.args.path,[]),Dn.get(b.args.path).push([te,ue])}if(b._scrollWarn){let{sectionCount:te,path:ue}=b._scrollWarn,_e={role:"user",content:`[SYSTEM WARNING] "${ue}" \u2014 you have now read ${te} 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(_e),R.push(_e),W(`${$.yellow} \u26A0 Scroll warning: "${ue.split("/").slice(-2).join("/")}" \u2014 ${te} sections read \u2014 use grep instead${$.reset}`)}let Y=b.args.path.split("/").slice(-2).join("/"),z=!b.args?.line_start&&!b.args?.line_end,ee=Te&&Xe==="plan";if(!ee&&z&&U===h$){{let ue=pt();if(Zt(R,ue).percentage>=60){let{messages:le}=dn(R,ue);R=le}}W(`${$.yellow} \u26A0 Loop warning: "${Y}" read unbounded ${U}\xD7 \u2014 use line_start/line_end${$.reset}`);let te={role:"user",content:`[SYSTEM WARNING] "${b.args.path}" read ${U}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};H.push(te),R.push(te)}else if(!ee&&z&&U>=g$){W(`${$.red} \u2716 Loop abort: "${Y}" read unbounded ${U}\xD7 \u2014 aborting runaway read loop${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}}if(b.fnName==="spawn_agents"){let U=(re.match(/\bStatus: done\b/g)||[]).length;if((re.match(/\bStatus: truncated\b/g)||[]).length>0&&U===0){if(Gn++,Gn===b$){W(`${$.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${Gn}\xD7 in a row${$.reset}`);let z={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${Gn}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};H.push(z),R.push(z)}else if(Gn>=_$){console.log(`${$.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${Gn}\xD7 \u2014 aborting stuck swarm${$.reset}`),u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L,{suppressHint:!0}),Ze(H);return}}else U>0&&(Gn=0)}}for(let _ of an)H.push(_),R.push(_);if(!st)for(let _=0;_<an.length;_++){if(!Se[_]||Se[_].fnName!=="ssh_exec")continue;let b=an[_];if(!b||typeof b.content!="string")continue;let re=fl(b.content);if(re){st=!0,kt=re.slice(0,120),fn=0,Qt=!1,vn=0,W(`${$.yellow} \u26A1 Root cause detected: ${kt} \u2014 fix phase (read budget: 3)${$.reset}`);let I={role:"user",content:`[SYSTEM] Root cause identified: ${kt}. Read only the file that needs fixing, then edit it. Do not read other files.`};H.push(I),R.push(I);break}}for(let _=0;_<an.length;_++){let b=Se[_];if(!b)continue;let re=typeof an[_]?.content=="string"?an[_].content:"";if(b.fnName==="create_task"){let I=re.match(/Task #(\d+) created/),F=typeof b.args?.subject=="string"?b.args.subject:"";I&&F&&hr.set(I[1],F)}else if((b.fnName==="write_file"||b.fnName==="edit_file")&&!re.startsWith("BLOCKED:")&&re.trim().length>0){let F=(typeof b.args?.path=="string"?b.args.path:typeof b.args?.file_path=="string"?b.args.file_path:"").split("/").pop().toLowerCase(),ce=F.split(/[._\-/]/).filter(G=>G.length>2);for(let[G,we]of hr){if(gr.has(G))continue;let U=we.toLowerCase().split(/\W+/).filter(z=>z.length>3);ce.filter(z=>U.some(ee=>ee.includes(z)||z.includes(ee))).length>=1&&(gr.add(G),W(`${$.green} \u2714 Auto-matched task #${G} to ${F}: ${we.slice(0,60)}${$.reset}`))}}}{let _=pt();if(Zt(R,_).percentage>=78){let{messages:re,tokensRemoved:I}=dn(R,_);I>0&&(R=re,console.log(`${$.dim} [auto-compressed \u2014 ~${I} tokens freed, now ${Math.round(Zt(R,_).percentage)}%]${$.reset}`))}}let vu=Wk();if(vu){let _={role:"user",content:`[User note mid-run]: ${vu}`};H.push(_),R.push(_),console.log(`${$.cyan} \u270E Context added${$.reset}`)}}if(Ve>=sn){if(u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L),Ze(H),yh(H),Te&&Xe==="plan"){let Es=[...H].reverse().find(ct=>ct.role==="assistant"),Et=typeof Es?.content=="string"?Es.content:"",Ts=rr("implement",Et);if(Ts){H.push(Ts),R=[{role:"system",content:await kl()},...H],sn=hs("implement"),W(`${$.yellow} \u26A0 Plan budget exhausted \u2014 auto-transitioning to implement${$.reset}`);continue e}}else if(Te&&Xe==="verify"){W(`${$.yellow} \u26A0 Verify budget exhausted \u2014 completing session${$.reset}`);break e}let{getActiveProviderName:Ae}=je();if(Ae()==="ollama"&&va<gu){if(A.size===0&&!ka){console.log(`${$.yellow} \u26A0 Max iterations reached with no progress. Stopping.${$.reset}`);break e}va++,sn=20,console.log(`${$.dim} \u2500\u2500 auto-extending (+20 turns, ext ${va}/${gu}) \u2500\u2500${$.reset}`);continue e}if(console.log(`
|
|
1207
|
+
${$.yellow}\u26A0 Max iterations reached.${$.reset}`),await Nh(" Continue for 20 more turns?")){sn=20;continue e}console.log(`${$.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${$.reset}`)}break e}}qh.exports={processInput:eS,clearConversation:Gk,getConversationLength:zk,getConversationMessages:Xk,setConversationMessages:Jk,setAbortSignalGetter:kk,setMaxIterations:vk,invalidateSystemPromptCache:yl,clearToolFilterCache:Nk,getCachedFilteredTools:Lh,buildSystemPrompt:kl,getProjectContextHash:Ih,buildUserContent:Ph,detectAndTruncateLoop:hl,injectMidRunNote:Bk,resetSessionTracking:Dh}});var je=Q((NR,Hh)=>{var{OllamaProvider:tS}=Qu(),{OpenAIProvider:nS}=sd(),{AnthropicProvider:sS}=ad(),{GeminiProvider:oS}=dd(),{LocalProvider:rS}=md(),{checkBudget:iS}=qs(),Ml={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"}},Ol=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Uh={};for(let[t,e]of Object.entries(Ml))for(let n of Object.values(e))Uh[n]=t;function Nl(t,e){let n=Uh[t];return n&&Ml[n][e]||t}var ot={},St=null,Je=null,$r=[];function Wt(){if(Object.keys(ot).length>0)return;co("ollama",new tS),co("openai",new nS),co("anthropic",new sS),co("gemini",new oS),co("local",new rS);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;ot[t]?(St=t,Je=e||ot[t].defaultModel):(St="ollama",Je="kimi-k2.5");let n=process.env.FALLBACK_CHAIN;n&&($r=n.split(",").map(o=>o.trim()).filter(Boolean))}function co(t,e){ot[t]=e}function aS(t){return Wt(),ot[t]||null}function Pl(){return Wt(),ot[St]||null}function cS(){return Wt(),St}function lS(){return Wt(),Je}function uS(){Wt();let t=Pl();if(!t)return{id:Je,name:Je,provider:St};let e=t.getModel(Je);return e?{...e,provider:St}:{id:Je,name:Je,provider:St}}function Bh(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(ot[n]||["ollama","openai","anthropic","gemini","local"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function dS(t){Wt();let{provider:e,model:n}=Bh(t);if(e){let s=ot[e];return s&&(s.getModel(n)||e==="local"||e==="ollama")?(St=e,Je=n,ra(),!0):!1}let o=Pl();if(o&&o.getModel(n))return Je=n,ra(),!0;for(let[s,r]of Object.entries(ot))if(r.getModel(n))return St=s,Je=n,ra(),!0;return!1}function ra(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=ve();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Ct();t()}catch{}}function fS(){Wt();let t=new Set;for(let e of Object.values(ot))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function pS(){return Wt(),Object.entries(ot).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===St&&n.id===Je}))}))}function mS(){Wt();let t=[];for(let[e,n]of Object.entries(ot)){let o=n.isConfigured();for(let s of Object.values(n.getModels()))t.push({spec:`${e}:${s.id}`,name:s.name,provider:e,configured:o})}return t}function hS(t){$r=Array.isArray(t)?t:[]}function gS(){return[...$r]}function Fh(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 Wh(t){let e=[St,...$r.filter(r=>r!==St)],n,o=0,s=0;for(let r=0;r<e.length;r++){let i=e[r],c=ot[i];if(!c||!c.isConfigured())continue;s++;let l=iS(i);if(!l.allowed){o++,n=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?Nl(Je,i):Je;return u&&d!==Je&&process.stderr.write(` [fallback: ${i}:${d}]
|
|
1208
1208
|
`),await t(c,i,d)}catch(u){if(n=u,!Fh(u)||r>=e.length-1)throw u;if(i==="ollama"&&Ol.length>0){let d=isFallback?Nl(Je,i):Je;for(let f of Ol)if(f!==d)try{return process.stderr.write(` [ollama fallback: ${f}]
|
|
1209
|
-
`),await t(c,i,f)}catch(p){if(n=p,!Fh(p))throw p}}continue}}throw o>0&&o===s?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):s===0?new Error("No configured provider available"):n||new Error("No configured provider available")}async function
|
|
1209
|
+
`),await t(c,i,f)}catch(p){if(n=p,!Fh(p))throw p}}continue}}throw o>0&&o===s?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):s===0?new Error("No configured provider available"):n||new Error("No configured provider available")}async function $S(t,e,n={}){return Wt(),Wh((o,s,r)=>o.stream(t,e,{model:r,signal:n.signal,...n}))}async function yS(t,e,n={}){if(Wt(),n.provider){let o=ot[n.provider];if(!o||!o.isConfigured())throw new Error(`Provider '${n.provider}' is not available`);let s={model:n.model||Je,...n};try{return await o.chat(t,e,s)}catch(r){if(typeof o.stream=="function")try{return await o.stream(t,e,{...s,onToken:()=>{}})}catch{}throw r}}return Wh(async(o,s,r)=>{try{return await o.chat(t,e,{model:r,...n})}catch(i){if(typeof o.stream=="function")try{return await o.stream(t,e,{model:r,...n,onToken:()=>{}})}catch{}throw i}})}function wS(){Wt();let t=[];for(let[e,n]of Object.entries(ot))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function bS(){for(let t of Object.keys(ot))delete ot[t];St=null,Je=null,$r=[]}Hh.exports={registerProvider:co,getProvider:aS,getActiveProvider:Pl,getActiveProviderName:cS,getActiveModelId:lS,getActiveModel:uS,setActiveModel:dS,getModelNames:fS,parseModelSpec:Bh,listProviders:pS,listAllModels:mS,callStream:$S,callChat:yS,getConfiguredProviders:wS,setFallbackChain:hS,getFallbackChain:gS,resolveModelForProvider:Nl,MODEL_EQUIVALENTS:Ml,OLLAMA_FALLBACK_MODELS:Ol,_reset:bS}});var Il=Q((MR,Kh)=>{"use strict";var Sn=require("fs"),ia=require("path"),_S=require("readline"),Ee="\x1B[0m",aa="\x1B[1m",mt="\x1B[2m",ca="\x1B[33m",Ll="\x1B[36m",yr="\x1B[32m";function xS(t){return(e,n="")=>new Promise(o=>{let s=n?` ${mt}[${n}]${Ee}`:"";t.question(` ${Ll}${e}${s}${Ee}: `,r=>o(r.trim()||n))})}function wr(t,e){return new Promise(n=>{e&&e.pause(),process.stdout.write(` ${Ll}${t}${Ee}: `);let o=process.stdin,s=o.isRaw,r="";o.setRawMode(!0),o.resume(),o.setEncoding("utf8");let i=c=>{c==="\r"||c===`
|
|
1210
1210
|
`?(o.setRawMode(s||!1),o.removeListener("data",i),process.stdout.write(`
|
|
1211
1211
|
`),e&&e.resume(),n(r)):c===""?(process.stdout.write(`
|
|
1212
|
-
`),process.exit(0)):c==="\x7F"?r.length>0&&(r=r.slice(0,-1),process.stdout.write("\b \b")):(r+=c,process.stdout.write("*"))};o.on("data",i)})}async function
|
|
1212
|
+
`),process.exit(0)):c==="\x7F"?r.length>0&&(r=r.slice(0,-1),process.stdout.write("\b \b")):(r+=c,process.stdout.write("*"))};o.on("data",i)})}async function vS({rl:t=null,force:e=!1}={}){if(!e){let p=Sn.existsSync(ia.join(process.cwd(),".env"))||Sn.existsSync(ia.join(__dirname,"..",".env")),h=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||h||m)return}let n=!t,o=t||_S.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),s=xS(o),r=!e;console.log(),console.log(r?`${ca}${aa} \u2726 Welcome to nex-code! No configuration found.${Ee}`:`${Ll}${aa} \u2726 nex-code \u2014 Provider & API Key Setup${Ee}`),console.log(`${mt} \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${Ee}`),r&&console.log(` Let's set you up in 60 seconds.
|
|
1213
1213
|
`),console.log(` ${aa}Which AI provider do you want to use?${Ee}
|
|
1214
1214
|
`),console.log(` ${yr}1)${Ee} ${aa}Ollama Cloud${Ee} ${mt}recommended \u2014 devstral-2:123b, no API key needed${Ee}`),console.log(` ${mt} (also works with a local Ollama server)${Ee}`),console.log(` ${mt}2) Anthropic Claude (claude-sonnet-4-6 etc.)${Ee}`),console.log(` ${mt}3) OpenAI GPT-4o, GPT-4.1 etc.${Ee}`),console.log(` ${mt}4) Gemini Google Gemini 2.x${Ee}`),console.log(` ${mt}5) Skip / Cancel${Ee}`),console.log();let i=await s("Enter number","1"),c=[];if(i==="5"){n&&o.close(),console.log(`
|
|
1215
1215
|
${mt} Cancelled \u2014 no changes made.${Ee}
|
|
@@ -1231,16 +1231,16 @@ ${ca} No key entered \u2014 cancelled.${Ee}
|
|
|
1231
1231
|
`)),console.log(`
|
|
1232
1232
|
${yr} \u2713 Saved to ${u}${Ee}`),c.some(m=>m.includes("API_KEY"))&&console.log(`${mt} (key stored locally \u2014 never committed)${Ee}`)}if(process.env.DEFAULT_PROVIDER)try{let{setActiveModel:p}=je(),h=process.env.DEFAULT_MODEL?`${process.env.DEFAULT_PROVIDER}:${process.env.DEFAULT_MODEL}`:process.env.DEFAULT_PROVIDER;p(h),console.log(`${yr} \u2713 Switched to ${h} for this session${Ee}`)}catch{}console.log(`
|
|
1233
1233
|
${yr} \u2713 Setup complete!${Ee}
|
|
1234
|
-
`)}Kh.exports={runSetupWizard:
|
|
1235
|
-
`))}function Gh(t,e){if(!
|
|
1234
|
+
`)}Kh.exports={runSetupWizard:vS}});var Xh=Q((PR,zh)=>{"use strict";var la=require("fs"),{T:tn,isDark:kS}=Yn(),Pt="\x1B[0m",SS=!kS,ES=process.env.FOOTER_DEBUG==="1"||process.env.FOOTER_DEBUG==="2",TS=process.env.FOOTER_DEBUG==="2",lo=null;function Fn(...t){ES&&(lo||(lo=la.openSync("/tmp/footer-debug.log","w")),la.writeSync(lo,t.join(" ")+`
|
|
1235
|
+
`))}function Gh(t,e){if(!TS||typeof e!="string")return;lo||(lo=la.openSync("/tmp/footer-debug.log","w"));let n=e.replace(/\x1b\[([^a-zA-Z]*)([a-zA-Z])/g,(o,s,r)=>`<ESC[${s}${r}>`).replace(/\x1b([^[])/g,(o,s)=>`<ESC${s}>`).replace(/\r/g,"<CR>").replace(/\n/g,`<LF>
|
|
1236
1236
|
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,o=>`<${o.charCodeAt(0).toString(16).padStart(2,"0")}>`);la.writeSync(lo,`${t}: ${n}
|
|
1237
|
-
`)}function Yh(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var jl=class{constructor(){this._active=!1,this._rl=null,this._origWrite=null,this._origPrompt=null,this._origSetPr=null,this._origRefreshLine=null,this._origLog=null,this._origError=null,this._origStderrWrite=null,this._drawing=!1,this._offResize=null,this._cursorOnInputRow=!1,this._inRefreshLine=!1,this._lastOutputRow=1,this._prevTermRows=0,this._prevTermCols=0,this._consistencyTimer=null,this._dirty=!1,this._statusModel="",this._statusBranch="",this._statusProject="",this._statusMode=""}setStatusInfo({model:e,branch:n,project:o,mode:s}={}){e!==void 0&&(this._statusModel=e),n!==void 0&&(this._statusBranch=n),o!==void 0&&(this._statusProject=o),s!==void 0&&(this._statusMode=s),this._active&&this.drawFooter()}get _rows(){return process.stdout.rows||24}get _cols(){return process.stdout.columns||80}get _scrollEnd(){return this._rows-2}get _rowStatus(){return this._rows-1}get _rowInput(){return this._rows}_goto(e,n=1){return`\x1B[${e};${n}H`}_statusLine(){let e=this._cols,n=this._statusModel,o=this._statusBranch,s=this._statusProject,r=this._statusMode;if(!n)return tn.footer_sep+"\u2500".repeat(e)+Pt;let i=` ${tn.footer_divider}\xB7${Pt} `,c=[];n&&c.push(`${tn.footer_model}${n}${Pt}`),o&&c.push(`${tn.footer_branch}${o}${Pt}`),s&&c.push(`${tn.footer_project}${s}${Pt}`);let l=c.join(i),u=[n,o,s].filter(Boolean).join(" \xB7 ").length,d="\u2500 ";if(r){let h=r.length,m=Math.max(0,e-d.length-u-1-1-h-3),g="\u2500".repeat(m);return`${tn.footer_sep}${d}${Pt}${l}${tn.footer_sep} ${g} ${Pt}${tn.footer_mode}${r}${Pt}${tn.footer_sep} \u2500\u2500${Pt}`}let f=Math.max(0,e-d.length-u-2),p="\u2500".repeat(f);return`${tn.footer_sep}${d}${Pt}${l}${tn.footer_sep} ${p}${Pt}`}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(
|
|
1237
|
+
`)}function Yh(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var jl=class{constructor(){this._active=!1,this._rl=null,this._origWrite=null,this._origPrompt=null,this._origSetPr=null,this._origRefreshLine=null,this._origLog=null,this._origError=null,this._origStderrWrite=null,this._drawing=!1,this._offResize=null,this._cursorOnInputRow=!1,this._inRefreshLine=!1,this._lastOutputRow=1,this._prevTermRows=0,this._prevTermCols=0,this._consistencyTimer=null,this._dirty=!1,this._statusModel="",this._statusBranch="",this._statusProject="",this._statusMode=""}setStatusInfo({model:e,branch:n,project:o,mode:s}={}){e!==void 0&&(this._statusModel=e),n!==void 0&&(this._statusBranch=n),o!==void 0&&(this._statusProject=o),s!==void 0&&(this._statusMode=s),this._active&&this.drawFooter()}get _rows(){return process.stdout.rows||24}get _cols(){return process.stdout.columns||80}get _scrollEnd(){return this._rows-2}get _rowStatus(){return this._rows-1}get _rowInput(){return this._rows}_goto(e,n=1){return`\x1B[${e};${n}H`}_statusLine(){let e=this._cols,n=this._statusModel,o=this._statusBranch,s=this._statusProject,r=this._statusMode;if(!n)return tn.footer_sep+"\u2500".repeat(e)+Pt;let i=` ${tn.footer_divider}\xB7${Pt} `,c=[];n&&c.push(`${tn.footer_model}${n}${Pt}`),o&&c.push(`${tn.footer_branch}${o}${Pt}`),s&&c.push(`${tn.footer_project}${s}${Pt}`);let l=c.join(i),u=[n,o,s].filter(Boolean).join(" \xB7 ").length,d="\u2500 ";if(r){let h=r.length,m=Math.max(0,e-d.length-u-1-1-h-3),g="\u2500".repeat(m);return`${tn.footer_sep}${d}${Pt}${l}${tn.footer_sep} ${g} ${Pt}${tn.footer_mode}${r}${Pt}${tn.footer_sep} \u2500\u2500${Pt}`}let f=Math.max(0,e-d.length-u-2),p="\u2500".repeat(f);return`${tn.footer_sep}${d}${Pt}${l}${tn.footer_sep} ${p}${Pt}`}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(SS)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 Gh("RAW",e),this._origWrite?this._origWrite(e):process.stdout.write(e)}_relayout(e){if(!this._origWrite)return;let n=this._origWrite,o=this._rows,s=this._cols,r=Math.max(1,o-2);Fn("RELAYOUT:",e,"rows="+o,"cols="+s,"scrollEnd="+r,"cursorOnInput="+this._cursorOnInputRow),this._prevTermRows=o,this._prevTermCols=s;let i=Math.min(this._lastOutputRow+1,r+1),c="";for(let l=i;l<=o;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,o=process.stdout.write.bind(process.stdout);this._origWrite=o,process.stdout.write=function(m,...g){if(Gh("PATCH",m),!n._active||typeof m!="string")return o(m,...g);if(n._inRefreshLine){let C=m.replace(/\n/g,"");return C?o(C,...g):!0}if(n._cursorOnInputRow){if(m.length<=4&&!m.includes(`
|
|
1238
1238
|
`)&&!m.includes("\r")&&!/[\x00-\x1f\x7f]/.test(m))return Fn("STDOUT: char intercept:",JSON.stringify(m)),n._origRefreshLine&&n._doRefreshLine(),!0;Fn("STDOUT: non-echo on input row, anchoring to workspace, data="+JSON.stringify(m).slice(0,100)),n._cursorOnInputRow=!1,o(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd)))}let y=n._cols||80,w=0,v=m.split(`
|
|
1239
1239
|
`);for(let C=0;C<v.length;C++){let S=Yh(v[C]);S>0&&(w+=Math.floor((S-1)/y))}let M=v.length-1;return M+w>0&&(n._lastOutputRow=Math.min(n._lastOutputRow+M+w,n._scrollEnd)),o(m,...g)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(m,...g){if(!n._active)return n._origStderrWrite(m,...g);if(typeof m=="string"&&m.includes("\r")){let w=Math.min(n._lastOutputRow+1,n._scrollEnd);if(n._cursorOnInputRow){n._origWrite("\x1B7"),n._origWrite(n._goto(w));let v=n._origStderrWrite(m,...g);return n._origWrite("\x1B8"),v}n._origWrite(n._goto(w))}let y=n._origStderrWrite(m,...g);return typeof m=="string"&&m.includes(`
|
|
1240
|
-
`)&&!/\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 s(...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(),o(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(),o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}console.log=s,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(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);Fn("PROMPT: goto rowInput="+n._rowInput),e.prevRows=0,o(n._goto(n._rowInput)+Pt+"\x1B[2K"),n._cursorOnInputRow=!0,n._origPrompt(m)};let i=e.question.bind(e);e.question=function(m,g){if(!n._active)return i(m,g);o(n._goto(n._rowInput)+"\x1B[2K"),e.prevRows=0,n._cursorOnInputRow=!0,i(m,y=>{o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!1,n.drawFooter(),g(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,o(n._goto(n._rowInput)+Pt+"\x1B[2K");let m=n._cols,g=e._prompt||"",y=Yh(g),w=m-y-1;n._inRefreshLine=!0;try{if(e.line.length<=w){Fn("REFRESH: short line, len="+e.line.length),u();return}Fn("REFRESH: long line, len="+e.line.length+", max="+w);let v=e.line,M=e.cursor,C=Math.max(1,w-1),S=Math.max(0,M-C),O=(S>0?"\xAB":"")+v.slice(S,S+C+(S>0?0:1));e.line=O,e.cursor=O.length,u(),e.line=v,e.cursor=M}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&&(Fn("LINE: leaving input row"),n._cursorOnInputRow=!1,o(n._goto(n._rowInput)+"\x1B[2K"),o(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n.drawFooter())});let d=null,f=null,p=()=>{d=null,n._relayout("resize"),f&&clearTimeout(f),f=setTimeout(()=>{f=null,n._relayout("resize-cleanup")},300)},h=()=>{n._dirty=!0,d&&clearTimeout(d),d=setTimeout(p,80)};process.stdout.on("resize",h),this._offResize=()=>{process.stdout.off("resize",h),d&&(clearTimeout(d),d=null),f&&(clearTimeout(f),f=null)},this._consistencyTimer=setInterval(()=>{if(!n._active)return;let m=n._rows,g=n._cols;(n._dirty||m!==n._prevTermRows||g!==n._prevTermCols)&&(Fn("CONSISTENCY: dirty="+n._dirty+" rows="+m+"/"+n._prevTermRows+" cols="+g+"/"+n._prevTermCols),n._relayout("consistency"))},800)}deactivate(){if(this._active){if(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._consistencyTimer&&(clearInterval(this._consistencyTimer),this._consistencyTimer=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine)){let e=Object.getOwnPropertySymbols(Object.getPrototypeOf(this._rl)).find(n=>n.toString()==="Symbol(_refreshLine)");e&&delete this._rl[e],delete this._rl._refreshLine,this._origRefreshLine=null}this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null}}};zh.exports={StickyFooter:jl}});var Zh=Q((
|
|
1240
|
+
`)&&!/\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 s(...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(),o(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(),o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}console.log=s,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(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);Fn("PROMPT: goto rowInput="+n._rowInput),e.prevRows=0,o(n._goto(n._rowInput)+Pt+"\x1B[2K"),n._cursorOnInputRow=!0,n._origPrompt(m)};let i=e.question.bind(e);e.question=function(m,g){if(!n._active)return i(m,g);o(n._goto(n._rowInput)+"\x1B[2K"),e.prevRows=0,n._cursorOnInputRow=!0,i(m,y=>{o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!1,n.drawFooter(),g(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,o(n._goto(n._rowInput)+Pt+"\x1B[2K");let m=n._cols,g=e._prompt||"",y=Yh(g),w=m-y-1;n._inRefreshLine=!0;try{if(e.line.length<=w){Fn("REFRESH: short line, len="+e.line.length),u();return}Fn("REFRESH: long line, len="+e.line.length+", max="+w);let v=e.line,M=e.cursor,C=Math.max(1,w-1),S=Math.max(0,M-C),O=(S>0?"\xAB":"")+v.slice(S,S+C+(S>0?0:1));e.line=O,e.cursor=O.length,u(),e.line=v,e.cursor=M}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&&(Fn("LINE: leaving input row"),n._cursorOnInputRow=!1,o(n._goto(n._rowInput)+"\x1B[2K"),o(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n.drawFooter())});let d=null,f=null,p=()=>{d=null,n._relayout("resize"),f&&clearTimeout(f),f=setTimeout(()=>{f=null,n._relayout("resize-cleanup")},300)},h=()=>{n._dirty=!0,d&&clearTimeout(d),d=setTimeout(p,80)};process.stdout.on("resize",h),this._offResize=()=>{process.stdout.off("resize",h),d&&(clearTimeout(d),d=null),f&&(clearTimeout(f),f=null)},this._consistencyTimer=setInterval(()=>{if(!n._active)return;let m=n._rows,g=n._cols;(n._dirty||m!==n._prevTermRows||g!==n._prevTermCols)&&(Fn("CONSISTENCY: dirty="+n._dirty+" rows="+m+"/"+n._prevTermRows+" cols="+g+"/"+n._prevTermCols),n._relayout("consistency"))},800)}deactivate(){if(this._active){if(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._consistencyTimer&&(clearInterval(this._consistencyTimer),this._consistencyTimer=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine)){let e=Object.getOwnPropertySymbols(Object.getPrototypeOf(this._rl)).find(n=>n.toString()==="Symbol(_refreshLine)");e&&delete this._rl[e],delete this._rl._refreshLine,this._origRefreshLine=null}this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null}}};zh.exports={StickyFooter:jl}});var Zh=Q((LR,Vh)=>{var{C:We}=Fe(),{listProviders:RS,getActiveProviderName:CS,getActiveModelId:AS,setActiveModel:OS}=je();function Jh(t,e,n={}){let{title:o="Select",hint:s="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=n;return new Promise(r=>{let i=e.map((w,v)=>w.isHeader?-1:v).filter(w=>w>=0);if(i.length===0){r(null);return}let c=e.findIndex(w=>w.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 w=i[l];return w<d?d=w:w>=d+u&&(d=w-u+1),{start:d,end:Math.min(e.length,d+u)}}let p=0;function h(){if(p>0){process.stdout.write(`\x1B[${p}A`);for(let S=0;S<p;S++)process.stdout.write(`\x1B[2K
|
|
1241
1241
|
`);process.stdout.write(`\x1B[${p}A`)}let w=[];w.push(` ${We.bold}${We.cyan}${o}${We.reset}`),w.push(` ${We.dim}${s}${We.reset}`),w.push("");let{start:v,end:M}=f();v>0&&w.push(` ${We.dim}\u2191 more${We.reset}`);for(let S=v;S<M;S++){let O=e[S];if(O.isHeader){w.push(` ${We.bold}${We.dim}${O.label}${We.reset}`);continue}let D=i[l]===S,K=D?`${We.cyan}> `:" ",V=O.isCurrent?` ${We.yellow}<current>${We.reset}`:"";D?w.push(`${K}${We.bold}${O.label}${We.reset}${V}`):w.push(`${K}${We.dim}${O.label}${We.reset}${V}`)}M<e.length&&w.push(` ${We.dim}\u2193 more${We.reset}`);let C=w.join(`
|
|
1242
1242
|
`);process.stdout.write(C+`
|
|
1243
|
-
`),p=w.length}t.pause();let m=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&m!==void 0&&process.stdin.setRawMode(m),t.resume()}function y(w,v){if(v){if(v.name==="up"||v.ctrl&&v.name==="p"){l>0&&(l--,h());return}if(v.name==="down"||v.ctrl&&v.name==="n"){l<i.length-1&&(l++,h());return}if(v.name==="return"){let M=e[i[l]];g(),r(M?M.value:null);return}if(v.name==="escape"||v.ctrl&&v.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",y),h()})}async function
|
|
1243
|
+
`),p=w.length}t.pause();let m=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&m!==void 0&&process.stdin.setRawMode(m),t.resume()}function y(w,v){if(v){if(v.name==="up"||v.ctrl&&v.name==="p"){l>0&&(l--,h());return}if(v.name==="down"||v.ctrl&&v.name==="n"){l<i.length-1&&(l++,h());return}if(v.name==="return"){let M=e[i[l]];g(),r(M?M.value:null);return}if(v.name==="escape"||v.ctrl&&v.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",y),h()})}async function NS(t){let e=RS(),n=CS(),o=AS(),s=[];for(let i of e)if(i.models.length!==0){s.push({label:i.provider,value:null,isHeader:!0});for(let c of i.models){let l=i.provider===n&&c.id===o;s.push({label:` ${c.name} (${i.provider}:${c.id})`,value:`${i.provider}:${c.id}`,isCurrent:l})}}let r=await Jh(t,s,{title:"Select Model"});return r?(OS(r),console.log(`${We.green}Switched to ${r}${We.reset}`),!0):(console.log(`${We.dim}Cancelled${We.reset}`),!1)}Vh.exports={pickFromList:Jh,showModelPicker:NS}});var ql=Q((jR,ig)=>{var Qh=require("fs"),MS=require("path"),{atomicWrite:PS,withFileLockSync:LS}=An(),{callChat:eg}=je(),{remember:IS,listMemories:IR,recall:jS}=un(),Dl=4,DS=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
1244
1244
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
1245
1245
|
|
|
1246
1246
|
Return ONLY valid JSON in this exact format:
|
|
@@ -1268,13 +1268,13 @@ Rules:
|
|
|
1268
1268
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
1269
1269
|
- Return ONLY the JSON, no markdown, no explanation`;function tg(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(`
|
|
1270
1270
|
|
|
1271
|
-
`)}async function ng(t){if(t.filter(s=>s.role==="user").length<Dl)return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=tg(t);if(!n.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let o=[{role:"system",content:
|
|
1271
|
+
`)}async function ng(t){if(t.filter(s=>s.role==="user").length<Dl)return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=tg(t);if(!n.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let o=[{role:"system",content:DS},{role:"user",content:`Conversation to analyze:
|
|
1272
1272
|
|
|
1273
|
-
${n}`}];try{let i=((await eg(o,[],{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(s){return{memories:[],nex_additions:[],summary:null,error:s.message}}}function sg(t){let e=[];for(let{key:n,value:o}of t||[]){if(!n||!o||typeof n!="string"||typeof o!="string")continue;let s=n.trim().replace(/\s+/g,"-").substring(0,60),r=o.trim().substring(0,200);if(!s||!r)continue;let i=
|
|
1273
|
+
${n}`}];try{let i=((await eg(o,[],{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(s){return{memories:[],nex_additions:[],summary:null,error:s.message}}}function sg(t){let e=[];for(let{key:n,value:o}of t||[]){if(!n||!o||typeof n!="string"||typeof o!="string")continue;let s=n.trim().replace(/\s+/g,"-").substring(0,60),r=o.trim().substring(0,200);if(!s||!r)continue;let i=jS(s);i!==r&&(IS(s,r),e.push({key:s,value:r,action:i?"updated":"added"}))}return e}function og(t){if(!t||t.length===0)return[];let e=MS.join(process.cwd(),"NEX.md");return LS(e,()=>{let n="";try{Qh.existsSync(e)&&(n=Qh.readFileSync(e,"utf-8"))}catch{}let o=[],s=n;for(let r of t){if(!r||typeof r!="string")continue;let i=r.trim();if(!i)continue;let c=i.substring(0,35).toLowerCase();n.toLowerCase().includes(c)||(o.push(i),s=s?s.endsWith(`
|
|
1274
1274
|
`)?s+i:s+`
|
|
1275
1275
|
`+i:i)}return o.length>0&&(s.endsWith(`
|
|
1276
1276
|
`)||(s+=`
|
|
1277
|
-
`),
|
|
1277
|
+
`),PS(e,s)),o})}async function qS(t){let e=await ng(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let n=sg(e.memories),o=og(e.nex_additions);return{applied:n,nexAdded:o,summary:e.summary}}var FS=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
1278
1278
|
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
1279
1279
|
|
|
1280
1280
|
Return ONLY valid JSON in this exact format:
|
|
@@ -1308,20 +1308,20 @@ Rules:
|
|
|
1308
1308
|
---
|
|
1309
1309
|
- Maximum 3 documents per session. Quality over quantity.
|
|
1310
1310
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
1311
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function rg(t){if(t.filter(s=>s.role==="user").length<Dl)return{documents:[],skip_reason:"Session too short"};let n=tg(t);if(!n.trim())return{documents:[],skip_reason:"No usable content"};let o=[{role:"system",content:
|
|
1311
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function rg(t){if(t.filter(s=>s.role==="user").length<Dl)return{documents:[],skip_reason:"Session too short"};let n=tg(t);if(!n.trim())return{documents:[],skip_reason:"No usable content"};let o=[{role:"system",content:FS},{role:"user",content:`Conversation to analyze:
|
|
1312
1312
|
|
|
1313
|
-
${n}`}];try{let i=((await eg(o,[],{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(s){return{documents:[],error:s.message}}}async function
|
|
1313
|
+
${n}`}];try{let i=((await eg(o,[],{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(s){return{documents:[],error:s.message}}}async function US(t){let e=await rg(t);if(e.error)return{written:[],skipped:[],error:e.error};if(!e.documents||e.documents.length===0)return{written:[],skipped:[],skip_reason:e.skip_reason};let{writeDocument:n,readDocument:o}=Do(),s=[],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=o(c);if(l.content){let d=`
|
|
1314
1314
|
|
|
1315
1315
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
1316
1316
|
|
|
1317
|
-
${i.content}`;n(c,l.content+d),s.push({name:c,reason:i.reason||"",action:"updated"})}else n(c,i.content),s.push({name:c,reason:i.reason||"",action:"created"})}return{written:s,skipped:r}}ig.exports={learnFromSession:
|
|
1317
|
+
${i.content}`;n(c,l.content+d),s.push({name:c,reason:i.reason||"",action:"updated"})}else n(c,i.content),s.push({name:c,reason:i.reason||"",action:"created"})}return{written:s,skipped:r}}ig.exports={learnFromSession:qS,learnBrainFromSession:US,reflectOnSession:ng,reflectBrain:rg,applyMemories:sg,applyNexAdditions:og,LEARN_MIN_MESSAGES:Dl}});var Un=Q((DR,ag)=>{var{C:Pe}=Fe();function BS(t){return t.tree&&t.tree.branches?t.tree:{branches:{main:{messages:t.messages||[],parentBranch:null,forkIndex:0}},activeBranch:"main"}}function WS(t){let e=t.branches[t.activeBranch];return e?e.messages:[]}function HS(t,e){let n=t.branches[t.activeBranch];n&&(n.messages=e)}function KS(t,e,n){let o=t.activeBranch,s=t.branches[o].messages;if(e<0||e>=s.length)throw new Error(`Fork index ${e} out of range (0-${s.length-1})`);return n||(n=`branch-${Object.keys(t.branches).filter(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:s.slice(0,e+1),parentBranch:o,forkIndex:e},t.activeBranch=n,{tree:t,branchName:n}}function GS(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 YS(t,e){let n=t.branches[t.activeBranch];if(!n)throw new Error("No active branch");if(e<0||e>=n.messages.length)throw new Error(`Index ${e} out of range (0-${n.messages.length-1})`);let o=n.messages.length-(e+1);return n.messages=n.messages.slice(0,e+1),{tree:t,truncated:o}}function zS(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 XS(t){let e=[];e.push(`${Pe.bold}${Pe.cyan}Session Tree${Pe.reset}
|
|
1318
1318
|
`);let n=Object.keys(t.branches);for(let o of n){let s=t.branches[o],r=o===t.activeBranch,i=r?`${Pe.green}* `:" ",c=r?`${Pe.green}${Pe.bold}${o}${Pe.reset}`:`${Pe.cyan}${o}${Pe.reset}`,l=s.messages.length,u=s.parentBranch?` ${Pe.dim}(forked from ${s.parentBranch}@${s.forkIndex})${Pe.reset}`:"";e.push(`${i}${c} \u2014 ${l} messages${u}`);let f=s.messages.filter(p=>p.role==="user").slice(-2);for(let p of f){let h=typeof p.content=="string"?p.content.substring(0,60):"[multimodal]";e.push(` ${Pe.dim}> ${h}${h.length>=60?"...":""}${Pe.reset}`)}}return e.join(`
|
|
1319
|
-
`)}function
|
|
1319
|
+
`)}function JS(t,e=20){let n=t.branches[t.activeBranch];if(!n)return"No active branch.";let o=n.messages,s=[];s.push(`${Pe.bold}${Pe.cyan}Timeline: ${t.activeBranch}${Pe.reset} (${o.length} messages)
|
|
1320
1320
|
`);let r=Math.max(0,o.length-e);for(let i=r;i<o.length;i++){let c=o[i],l=c.role,u=l==="user"?Pe.green:l==="assistant"?Pe.cyan:l==="system"?Pe.yellow:Pe.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(h=>h.type==="text"||h.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?` ${Pe.dim}[${c.tool_calls.length} tool calls]${Pe.reset}`:"";s.push(` ${Pe.dim}${String(i).padStart(3)}${Pe.reset} ${u}${l.padEnd(9)}${Pe.reset} ${d}${f}`)}return r>0&&s.splice(1,0,` ${Pe.dim}... ${r} earlier messages not shown${Pe.reset}`),s.join(`
|
|
1321
|
-
`)}ag.exports={initTree:
|
|
1321
|
+
`)}ag.exports={initTree:BS,getActiveMessages:WS,setActiveMessages:HS,createBranch:KS,switchBranch:GS,gotoMessage:YS,deleteBranch:zS,renderTree:XS,renderTimeline:JS}});var pg=Q((qR,fg)=>{var{spawn:VS}=require("child_process"),cg=require("path"),lg=require("fs"),ZS=require("os"),Bn=new Map;function ug(t){return typeof t!="string"?t:t.replace(/\$\{([^}]+)\}/g,(e,n)=>process.env[n]!==void 0?process.env[n]:"")}function dg(t){let e=t||process.env.NEX_MCP_CONFIG||null,n=e?[e]:[cg.join(process.cwd(),".nex","mcp.json"),cg.join(ZS.homedir(),".nex","mcp.json")];for(let o of n)if(lg.existsSync(o))try{return JSON.parse(lg.readFileSync(o,"utf-8"))}catch{}return{servers:{}}}function ua(t,e,n={},o=1e4){return new Promise((s,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:n})+`
|
|
1322
1322
|
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},o);function d(p){l+=p.toString();let h=l.split(`
|
|
1323
|
-
`);for(let m of h)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):s(g.result);return}}catch{}l=h[h.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
|
|
1324
|
-
`):JSON.stringify(s)}function
|
|
1323
|
+
`);for(let m of h)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):s(g.result);return}}catch{}l=h[h.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 QS(t){let n=dg(t).servers||{},o=[];for(let[s,r]of Object.entries(n)){if(Bn.has(s)){let d=Bn.get(s);o.push({name:s,tools:d.tools.length});continue}let i={};for(let[d,f]of Object.entries(r.env||{}))i[d]=ug(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=VS(r.command,r.args||[],{stdio:["pipe","pipe","pipe"],env:{...l,...i}})}catch(d){console.warn(`[mcp-client] Failed to spawn '${s}': ${d.message}`),o.push({name:s,tools:0,error:d.message});continue}try{await ua(u,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.4.8"}});let d=await ua(u,"tools/list",{}),f=d&&d.tools||[];Bn.set(s,{name:s,proc:u,tools:f,config:r}),o.push({name:s,tools:f.length})}catch(d){console.warn(`[mcp-client] Server '${s}' failed to initialize: ${d.message}`);try{u.kill()}catch{}o.push({name:s,tools:0,error:d.message})}}return o}async function eE(t,e,n={}){let o=Bn.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await ua(o.proc,"tools/call",{name:e,arguments:n});return s&&Array.isArray(s.content)?s.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
1324
|
+
`):JSON.stringify(s)}function tE(){let t=[];for(let[e,n]of Bn)for(let o of n.tools)t.push({type:"function",function:{name:`mcp_${e}_${o.name}`,description:`[MCP:${e}] ${o.description||""}`,parameters:o.inputSchema||{type:"object",properties:{}}}});return t}function nE(){for(let[t,e]of Bn){try{e.proc.kill()}catch{}Bn.delete(t)}}function sE(){let t=[];for(let[e,n]of Bn)t.push({name:e,connected:!0,toolCount:n.tools.length});return t}fg.exports={loadMcpServers:QS,callMcpTool:eE,getMcpTools:tE,shutdownMcpServers:nE,listMcpServers:sE,_interpolateEnv:ug,_readConfig:dg,_sendRequest:ua}});var $g=Q((UR,gg)=>{var yt=require("fs"),fo=require("path"),FR=require("os"),oE=require("readline"),{C:oe}=Fe(),mg=".nex",Fl=null;function rE(t){Fl=t}function wt(t,e=""){let n=e?` ${oe.dim}[${e}]${oe.reset}`:"",o=` ${oe.cyan}${t}${n}${oe.reset}: `;return new Promise(s=>{let r=i=>{let c=i.trim()||e;s(c)};if(Fl)Fl.question(o,r);else{let i=oE.createInterface({input:process.stdin,output:process.stdout});i.question(o,c=>{i.close(),r(c)})}})}function uo(t,e=!0){return wt(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(o=>o.toLowerCase()!=="n"&&o.toLowerCase()!=="no")}async function Ul(t,e,n){let o=e.map((c,l)=>`${oe.dim}${l+1})${oe.reset} ${c}`).join(" ");console.log(` ${oe.cyan}${t}${oe.reset}`),console.log(` ${o}`);let s=n?e.indexOf(n)+1:1,r=await wt("Enter number",String(s)),i=parseInt(r,10)-1;return e[Math.max(0,Math.min(i,e.length-1))]}async function iE(){let t=fo.join(process.cwd(),mg),e=fo.join(t,"servers.json"),n={};if(yt.existsSync(e))try{n=JSON.parse(yt.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
1325
1325
|
${oe.bold}${oe.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${oe.reset}`),console.log(`${oe.bold}${oe.cyan}\u2551 nex-code Server Setup Wizard \u2551${oe.reset}`),console.log(`${oe.bold}${oe.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${oe.reset}
|
|
1326
1326
|
`);let o=Object.keys(n);if(o.length>0&&(console.log(`${oe.dim}Existing profiles: ${o.join(", ")}${oe.reset}`),!await uo("Add or update a server profile?",!0))){console.log(`${oe.dim}No changes made.${oe.reset}
|
|
1327
1327
|
`);return}let s={...n},r=!0;for(;r;){console.log(`
|
|
@@ -1343,7 +1343,7 @@ ${oe.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${oe.reset}`);l
|
|
|
1343
1343
|
Add another deploy config?`,!1)}yt.existsSync(n)||yt.mkdirSync(n,{recursive:!0}),yt.writeFileSync(o,JSON.stringify(c,null,2)+`
|
|
1344
1344
|
`,"utf-8"),console.log(`
|
|
1345
1345
|
${oe.green}\u2713 Saved .nex/deploy.json (${Object.keys(c).length} config${Object.keys(c).length!==1?"s":""})${oe.reset}`),console.log(`${oe.dim}Use: deploy prod (or with explicit params)${oe.reset}
|
|
1346
|
-
`)}gg.exports={runServerWizard:
|
|
1346
|
+
`)}gg.exports={runServerWizard:iE,runDeployWizard:hg,setWizardRL:rE}});var po=Q((BR,bg)=>{"use strict";var pa=require("os"),br=require("path"),rt=require("fs"),aE=require("axios"),cE=require("https"),da=br.join(pa.homedir(),".nex-code","known-models.json"),lE="https://ollama.com/api/tags",uE=60,dE={"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 Bl(){try{if(rt.existsSync(da))return JSON.parse(rt.readFileSync(da,"utf-8"))}catch{}return{benchmarked:[],lastChecked:null}}function fE(t){let e=br.dirname(da);rt.existsSync(e)||rt.mkdirSync(e,{recursive:!0}),rt.writeFileSync(da,JSON.stringify(t,null,2))}function pE(t){let e=Bl(),n=new Set(e.benchmarked);for(let o of t)n.add(o);e.benchmarked=[...n],e.lastChecked=new Date().toISOString(),fE(e)}async function yg(){let t=process.env.OLLAMA_API_KEY;if(!t)throw new Error("OLLAMA_API_KEY not set");let e=new cE.Agent({keepAlive:!0});return((await aE.get(lE,{headers:{Authorization:`Bearer ${t}`},timeout:15e3,httpsAgent:e})).data?.models||[]).map(o=>(o.name||o.model||"").replace(/:latest$/,"")).filter(Boolean)}async function mE(){let t=await yg(),e=Bl(),n=new Set(e.benchmarked),o=t.filter(s=>!n.has(s));return{allCloud:t,newModels:o,store:e}}var Wl="<!-- nex-benchmark-start -->",fa="<!-- nex-benchmark-end -->",hE={"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 gE(t){return t?t>=25e4?"256K":t>=19e4?"200K":t>=128e3?"131K":t>=64e3?"64K":`${Math.round(t/1024)}K`:"?"}function wg(t,e){let n=["\u{1F947}","\u{1F948}","\u{1F949}"],o=(e||new Date().toISOString()).split("T")[0],s=t.filter(r=>r.score>=uE).map((r,i)=>{let c=n[i]||"\u2014",l=gE(dE[r.model]),u=hE[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(`
|
|
1347
1347
|
`);return`${Wl}
|
|
1348
1348
|
<!-- Updated: ${o} \u2014 run \`/benchmark --discover\` after new Ollama Cloud releases -->
|
|
1349
1349
|
|
|
@@ -1353,20 +1353,20 @@ ${s}
|
|
|
1353
1353
|
|
|
1354
1354
|
> Rankings are nex-code-specific: tool name accuracy, argument validity, schema compliance.
|
|
1355
1355
|
> Toolathon (Minimax SOTA) measures different task types \u2014 run \`/benchmark --discover\` after model releases.
|
|
1356
|
-
${fa}`}function
|
|
1356
|
+
${fa}`}function $E(t,e){if(!rt.existsSync(e))return!1;let n=rt.readFileSync(e,"utf-8"),o=n.indexOf(Wl),s=n.indexOf(fa);if(o===-1||s===-1)return!1;let r=n.slice(0,o),i=n.slice(s+fa.length),c=wg(t);return rt.writeFileSync(e,r+c+i),!0}function yE(t){let e=br.join(pa.homedir(),".nex-code","models.env");if(!rt.existsSync(e)||t.length===0)return{updated:!1,reason:"models.env not found or empty summary"};let n=t[0],o=rt.readFileSync(e,"utf-8"),r=o.match(/^DEFAULT_MODEL=(\S+)/m)?.[1];if(r===n.model)return{updated:!1,reason:"winner unchanged"};let i=t.find(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 o=o.replace(/^DEFAULT_MODEL=\S+/m,`DEFAULT_MODEL=${n.model}`).replace(/^# Last reviewed:.*$/m,`# Last reviewed: ${c} (after /benchmark, ${n.model} wins nex-code tasks)`),rt.writeFileSync(e,o),{updated:!0,previousModel:r,newModel:n.model}}function wE(t){let{saveRoutingConfig:e}=In(),n=br.join(pa.homedir(),".nex-code","models.env"),o=[],s=Object.entries(t).filter(([,c])=>c.score>0);if(s.length===0)return{saved:!1,envUpdated:!1,changes:[]};let r={};for(let[c,l]of s)r[c]=l.model,o.push(`${c}: ${l.model} (${l.score}/100)`);e(r);let i=!1;if(rt.existsSync(n)){let c=rt.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,h])=>`${h}=${t[p].model} # ${p} score: ${t[p].score}/100`).join(`
|
|
1357
1357
|
`),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),h=c.indexOf(f);h!==-1&&(c=c.slice(0,p)+`${d}
|
|
1358
1358
|
${u}
|
|
1359
1359
|
${f}`+c.slice(h+f.length))}else c+=`
|
|
1360
1360
|
${d}
|
|
1361
1361
|
${u}
|
|
1362
1362
|
${f}
|
|
1363
|
-
`;
|
|
1363
|
+
`;rt.writeFileSync(n,c),i=!0}return{saved:!0,envUpdated:i,changes:o}}var bE=/thinking|reasoning|instruct|planner|orchestrat/i;function _E(t){return bE.test(t)}function xE(t){if(!t||t.length===0)return{updated:!1};let e=br.join(pa.homedir(),".nex-code","models.env");if(!rt.existsSync(e))return{updated:!1};let n=rt.readFileSync(e,"utf-8"),o=n.match(/^NEX_ORCHESTRATOR_MODEL=(.+)$/m),s=o?o[1].trim():null,i=[...t].sort((d,f)=>f.overall-d.overall)[0],c=s?t.find(d=>d.model===s):null,l=c?c.overall:0;if(i.model===s)return{updated:!1};if(l>0&&i.overall<l*1.05)return{updated:!1};let u=`NEX_ORCHESTRATOR_MODEL=${i.model}`;return o?n=n.replace(/^NEX_ORCHESTRATOR_MODEL=.+$/m,u):n+=`
|
|
1364
1364
|
${u}
|
|
1365
|
-
`,it.writeFileSync(e,n),{updated:!0,previousModel:s,newModel:i.model}}bg.exports={findNewModels:pE,fetchCloudModels:yg,loadKnownModels:Bl,markBenchmarked:fE,updateReadme:gE,updateModelsEnv:$E,updateRoutingConfig:yE,generateBenchmarkBlock:wg,checkOrchestratorCandidate:bE,updateOrchestratorModel:_E,SENTINEL_START:Wl,SENTINEL_END:fa}});var Wn=Q((BR,Ag)=>{"use strict";var{C:J}=Fe(),xE=je(),{TOOL_DEFINITIONS:_g}=Gt(),{saveRoutingConfig:vE}=In(),Gl=[{id:"read-package",category:"file-ops",prompt:"Read the file package.json and show me its contents.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"write-file",category:"file-ops",prompt:'Create a file at /tmp/nex-bench-test.txt with the content "benchmark run".',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&typeof t.content=="string"},{id:"edit-file",category:"file-ops",prompt:'In the file src/config.js, replace the string "debug: false" with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.old_string!==void 0&&t.new_string!==void 0||t.path&&Array.isArray(t.patches)&&t.patches.length>0)},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".js")},{id:"search-constant",category:"search",prompt:'Search for the string "DEFAULT_MODEL" across all files in the project.',expectedTool:["search_files","grep"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("DEFAULT_MODEL")},{id:"grep-function-def",category:"search",prompt:'Find where the function "callStream" is defined in the codebase.',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:t=>JSON.stringify(t).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git")},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git status")},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let n=e?.function?.parameters||{},o=n.required||[],s=Object.keys(n.properties||{});return o.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>s.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"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}],xg=[{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)}],ga=[...Gl,...xg],Hl=["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 kE(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return Hl;let o=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(o)||o.length===0?Hl:o.filter(s=>typeof s.score=="number"&&s.score>=60).sort((s,r)=>r.score-s.score).slice(0,12).map(s=>s.model)}catch{return Hl}}var Yl=kE(),SE=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],vg=(()=>{let t=Yl.slice(0,3);return t.length>=3?t:SE})(),EE=7,ma={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},TE="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 Kl(t,e){let n={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},o=[{role:"system",content:TE},{role:"user",content:t.prompt}],s=Date.now();try{let r=await xE.callChat(o,_g,{provider:"ollama",model:e,temperature:0,timeout:9e4});n.latencyMs=Date.now()-s;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=_g.find(p=>p.function?.name===l);if(n.validArgs=!!t.validateArgs(u,f),f){let p=f.function?.parameters||{},h=p.required||[],m=Object.keys(p.properties||{});n.schemaCompliant=h.every(g=>u[g]!==void 0)&&Object.keys(u).every(g=>m.includes(g))}}}}catch(r){n.latencyMs=Date.now()-s,n.error=r.message.slice(0,120)}return n}function mo(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 kg={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 zl(t){return Object.entries(t).map(([e,n])=>{let o=n.map(mo),s=o.reduce((c,l)=>c+l,0)/o.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=>kg[d.category]===c);if(l.length===0)continue;let u=l.map(mo).reduce((d,f)=>d+f,0)/l.length;i[c]=Math.round(u*10)/10}return{model:e,score:Math.round(s*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 Sg(t){let e={};for(let c of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let l=t.filter(g=>g.categoryScores[c]!==void 0&&g.score>=65).sort((g,y)=>y.categoryScores[c]-g.categoryScores[c]);if(l.length===0)continue;let d=(l[0]?.results||[]).filter(g=>kg[g.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(g=>f.categoryScores[c]-g.categoryScores[c]<=5).sort((g,y)=>g.avgLatency-y.avgLatency)[0];e[c]={model:m.model,score:m.categoryScores[c],avgLatency:m.avgLatency}}return e}function Eg(t,e){let n=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,o=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],s=o.reduce((u,d)=>u+d.width+1,0)+1,r="\u2500".repeat(s);console.log(`
|
|
1365
|
+
`,rt.writeFileSync(e,n),{updated:!0,previousModel:s,newModel:i.model}}bg.exports={findNewModels:mE,fetchCloudModels:yg,loadKnownModels:Bl,markBenchmarked:pE,updateReadme:$E,updateModelsEnv:yE,updateRoutingConfig:wE,generateBenchmarkBlock:wg,checkOrchestratorCandidate:_E,updateOrchestratorModel:xE,SENTINEL_START:Wl,SENTINEL_END:fa}});var Wn=Q((WR,Ag)=>{"use strict";var{C:J}=Fe(),vE=je(),{TOOL_DEFINITIONS:_g}=Gt(),{saveRoutingConfig:kE}=In(),Gl=[{id:"read-package",category:"file-ops",prompt:"Read the file package.json and show me its contents.",expectedTool:"read_file",validateArgs:t=>typeof t.path=="string"&&t.path.includes("package.json")},{id:"write-file",category:"file-ops",prompt:'Create a file at /tmp/nex-bench-test.txt with the content "benchmark run".',expectedTool:"write_file",validateArgs:t=>typeof t.path=="string"&&typeof t.content=="string"},{id:"edit-file",category:"file-ops",prompt:'In the file src/config.js, replace the string "debug: false" with "debug: true".',expectedTool:["edit_file","patch_file"],validateArgs:t=>!!(t.path&&t.old_string!==void 0&&t.new_string!==void 0||t.path&&Array.isArray(t.patches)&&t.patches.length>0)},{id:"list-directory",category:"file-ops",prompt:"Show me all files and folders in the cli/ directory.",expectedTool:["list_directory","glob"],validateArgs:t=>!!(typeof t.path=="string"&&t.path.includes("cli")||typeof t.pattern=="string"&&t.pattern.includes("cli"))},{id:"glob-js-files",category:"file-ops",prompt:"Find all JavaScript files (*.js) recursively in the cli/ directory.",expectedTool:"glob",validateArgs:t=>typeof t.pattern=="string"&&t.pattern.includes(".js")},{id:"search-constant",category:"search",prompt:'Search for the string "DEFAULT_MODEL" across all files in the project.',expectedTool:["search_files","grep"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("DEFAULT_MODEL")},{id:"grep-function-def",category:"search",prompt:'Find where the function "callStream" is defined in the codebase.',expectedTool:["grep","search_files"],validateArgs:t=>(t.pattern||t.query||t.regex||"").includes("callStream")},{id:"search-todos",category:"search",prompt:"Find all TODO comments in the source code.",expectedTool:["grep","search_files","bash"],validateArgs:t=>JSON.stringify(t).toUpperCase().includes("TODO")},{id:"git-branch",category:"shell",prompt:"What git branch am I currently on?",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git")},{id:"git-status",category:"shell",prompt:"Show me the current git status of the repository.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("git status")},{id:"npm-install",category:"shell",prompt:"Run npm install to install project dependencies.",expectedTool:"bash",validateArgs:t=>typeof t.command=="string"&&t.command.includes("npm")},{id:"schema-strict",category:"schema",prompt:"Read the file README.md",expectedTool:"read_file",validateArgs:(t,e)=>{let n=e?.function?.parameters||{},o=n.required||[],s=Object.keys(n.properties||{});return o.every(r=>t[r]!==void 0)&&Object.keys(t).every(r=>s.includes(r))}},{id:"multi-step-version",category:"multi-step",prompt:"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}],xg=[{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)}],ga=[...Gl,...xg],Hl=["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 SE(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return Hl;let o=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(o)||o.length===0?Hl:o.filter(s=>typeof s.score=="number"&&s.score>=60).sort((s,r)=>r.score-s.score).slice(0,12).map(s=>s.model)}catch{return Hl}}var Yl=SE(),EE=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],vg=(()=>{let t=Yl.slice(0,3);return t.length>=3?t:EE})(),TE=7,ma={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},RE="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 Kl(t,e){let n={taskId:t.id,category:t.category,model:e,producedToolCall:!1,correctTool:!1,validArgs:!1,schemaCompliant:!1,toolCalled:null,error:null,latencyMs:0},o=[{role:"system",content:RE},{role:"user",content:t.prompt}],s=Date.now();try{let r=await vE.callChat(o,_g,{provider:"ollama",model:e,temperature:0,timeout:9e4});n.latencyMs=Date.now()-s;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=_g.find(p=>p.function?.name===l);if(n.validArgs=!!t.validateArgs(u,f),f){let p=f.function?.parameters||{},h=p.required||[],m=Object.keys(p.properties||{});n.schemaCompliant=h.every(g=>u[g]!==void 0)&&Object.keys(u).every(g=>m.includes(g))}}}}catch(r){n.latencyMs=Date.now()-s,n.error=r.message.slice(0,120)}return n}function mo(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 kg={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 zl(t){return Object.entries(t).map(([e,n])=>{let o=n.map(mo),s=o.reduce((c,l)=>c+l,0)/o.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=>kg[d.category]===c);if(l.length===0)continue;let u=l.map(mo).reduce((d,f)=>d+f,0)/l.length;i[c]=Math.round(u*10)/10}return{model:e,score:Math.round(s*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 Sg(t){let e={};for(let c of["coding","frontend","sysadmin","data","agentic","plan","verify"]){let l=t.filter(g=>g.categoryScores[c]!==void 0&&g.score>=65).sort((g,y)=>y.categoryScores[c]-g.categoryScores[c]);if(l.length===0)continue;let d=(l[0]?.results||[]).filter(g=>kg[g.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(g=>f.categoryScores[c]-g.categoryScores[c]<=5).sort((g,y)=>g.avgLatency-y.avgLatency)[0];e[c]={model:m.model,score:m.categoryScores[c],avgLatency:m.avgLatency}}return e}function Eg(t,e){let n=`nex-code Model Benchmark (${e} tasks \xB7 ollama cloud)`,o=[{label:"#",width:3},{label:"Model",width:26},{label:"Score",width:7},{label:"Tool\u2713",width:7},{label:"Name\u2713",width:7},{label:"Args\u2713",width:7},{label:"Schema\u2713",width:8},{label:"Latency",width:8},{label:"Err",width:4}],s=o.reduce((u,d)=>u+d.width+1,0)+1,r="\u2500".repeat(s);console.log(`
|
|
1366
1366
|
${J.bold}${n}${J.reset}`),console.log(r);let i=o.map(u=>u.label.padEnd(u.width)).join(" ");if(console.log(`${J.dim}${i}${J.reset}`),console.log(r),t.forEach((u,d)=>{let f=String(d+1).padEnd(o[0].width),p=u.model.slice(0,o[1].width).padEnd(o[1].width),h=String(u.score).padEnd(o[2].width),m=`${u.toolCallRate}%`.padEnd(o[3].width),g=`${u.correctRate}%`.padEnd(o[4].width),y=`${u.validArgsRate}%`.padEnd(o[5].width),w=`${u.schemaRate}%`.padEnd(o[6].width),v=`${(u.avgLatency/1e3).toFixed(1)}s`.padEnd(o[7].width),M=u.errorCount>0?`${J.red}${u.errorCount}${J.reset}`:`${J.dim}0${J.reset}`,C=u.score>=80?J.green:u.score>=60?J.yellow:J.red,S=d===0?`${J.yellow}${f}${J.reset}`:`${J.dim}${f}${J.reset}`;console.log(`${S} ${C}${p}${J.reset} ${J.bold}${C}${h}${J.reset} ${m} ${g} ${y} ${w} ${J.dim}${v}${J.reset} ${M}`)}),console.log(r),t.length>0){let u=t[0];if(console.log(`
|
|
1367
1367
|
${J.bold}${J.green}Winner: ${u.model}${J.reset} score ${u.score}/100`),t.length>1){let d=(u.score-t[1].score).toFixed(1);console.log(`${J.dim}+${d} pts over ${t[1].model}${J.reset}`)}}let c=["coding","frontend","sysadmin","data","agentic"];if(t.some(u=>Object.keys(u.categoryScores).length>1)){console.log(`
|
|
1368
|
-
${J.bold}Best model per task type:${J.reset}`);for(let u of c){let d=t.filter(m=>m.categoryScores[u]!==void 0).sort((m,g)=>g.categoryScores[u]-m.categoryScores[u]);if(d.length===0)continue;let f=d[0],p=f.categoryScores[u],h=p>=80?J.green:p>=60?J.yellow:J.red;console.log(` ${J.dim}${u.padEnd(10)}${J.reset} ${h}${f.model}${J.reset} ${J.dim}${p}/100${J.reset}`)}}console.log()}function Tg(t){if(!(!t||t.length<2))try{let e=Sg(t),{loadRoutingConfig:n}=In(),o=n(),s={...o},r=[],i=new Set(["plan","verify"]);for(let[c,{model:l,score:u}]of Object.entries(e)){let d=i.has(c),f=d?o.phases&&o.phases[c]:o[c];f&&f!==l&&!t.find(h=>h.model===f)||(d?(s.phases||(s.phases={}),s.phases[c]!==l&&(s.phases[c]=l,r.push(`phase:${c}\u2192${l}`))):s[c]!==l&&(s[c]=l,r.push(`${c}\u2192${l}`)))}r.length>0&&(
|
|
1369
|
-
${J.dim} Routing updated: ${r.join(", ")}${J.reset}`))}catch{}}async function
|
|
1368
|
+
${J.bold}Best model per task type:${J.reset}`);for(let u of c){let d=t.filter(m=>m.categoryScores[u]!==void 0).sort((m,g)=>g.categoryScores[u]-m.categoryScores[u]);if(d.length===0)continue;let f=d[0],p=f.categoryScores[u],h=p>=80?J.green:p>=60?J.yellow:J.red;console.log(` ${J.dim}${u.padEnd(10)}${J.reset} ${h}${f.model}${J.reset} ${J.dim}${p}/100${J.reset}`)}}console.log()}function Tg(t){if(!(!t||t.length<2))try{let e=Sg(t),{loadRoutingConfig:n}=In(),o=n(),s={...o},r=[],i=new Set(["plan","verify"]);for(let[c,{model:l,score:u}]of Object.entries(e)){let d=i.has(c),f=d?o.phases&&o.phases[c]:o[c];f&&f!==l&&!t.find(h=>h.model===f)||(d?(s.phases||(s.phases={}),s.phases[c]!==l&&(s.phases[c]=l,r.push(`phase:${c}\u2192${l}`))):s[c]!==l&&(s[c]=l,r.push(`${c}\u2192${l}`)))}r.length>0&&(kE(s),console.log(`
|
|
1369
|
+
${J.dim} Routing updated: ${r.join(", ")}${J.reset}`))}catch{}}async function CE({models:t,quick:e=!1,onProgress:n,parallelModels:o=1}={}){let s=e?Gl.slice(0,TE):ga,r=t?.length>0?t:e?vg:Yl,i={};for(let l of r)i[l]=[];if(o<=1)for(let l of r)for(let u of s){n?.({model:l,task:u.id,done:!1});let d=await Kl(u,l);i[l].push(d),n?.({model:l,task:u.id,done:!0,score:mo(d),error:d.error})}else{let l=Math.min(o,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 s){n?.({model:f,task:p.id,done:!1});let h=await Kl(p,f);i[f].push(h),n?.({model:f,task:p.id,done:!0,score:mo(h),error:h.error})}}});await Promise.all(d)}let c=zl(i);return Eg(c,s.length),Tg(c),c}async function AE({newModels:t,existingRanking:e=[],onProgress:n}={}){if(!t||t.length===0)return e;let o={};for(let i of t){o[i]=[];for(let c of ga){n?.({model:i,task:c.id,done:!1});let l=await Kl(c,i);o[i].push(l),n?.({model:i,task:c.id,done:!0,score:mo(l),error:l.error})}}let r=[...zl(o)];for(let i of e)r.find(c=>c.model===i.model)||r.push(i);return r.sort((i,c)=>c.score-i.score),Eg(r,ga.length),Tg(r),r}var ha=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function Rg(t){let e=require("fs"),o=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(o))return console.log(`${J.yellow}No scenarios configured.${J.reset} Create ${J.dim}.nex/benchmark-config.json${J.reset} to define your benchmark scenarios.
|
|
1370
1370
|
Example:
|
|
1371
1371
|
{
|
|
1372
1372
|
"scenarios": [
|
|
@@ -1381,26 +1381,26 @@ ${J.dim} Routing updated: ${r.join(", ")}${J.reset}`))}catch{}}async function R
|
|
|
1381
1381
|
}
|
|
1382
1382
|
`),ha;try{let s=JSON.parse(e.readFileSync(o,"utf-8"));return!Array.isArray(s.scenarios)||s.scenarios.length===0?(console.log(`${J.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${J.reset}
|
|
1383
1383
|
`),ha):s.scenarios}catch(s){return console.log(`${J.yellow}Failed to parse benchmark-config.json: ${s.message}${J.reset}
|
|
1384
|
-
`),ha}}function Cg(t,e){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=Li(),r=n(t),i=r.score,c=[],l=s(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=o(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
|
|
1384
|
+
`),ha}}function Cg(t,e){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=Li(),r=n(t),i=r.score,c=[],l=s(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=o(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 OE(t,e={}){let{spawn:n}=require("child_process"),o=require("fs"),s=require("path"),r=require("os"),i=s.join(r.tmpdir(),`nex-bench-${t.id}-${Date.now()}.txt`);o.writeFileSync(i,t.prompt,"utf-8");let c=s.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,h=!1,m=setTimeout(()=>{h=!0;try{f.kill("SIGTERM")}catch{}},p);f.on("close",g=>{clearTimeout(m);try{o.unlinkSync(i)}catch{}let y=s.join(l,".nex","sessions","_autosave.json"),w=[];if(o.existsSync(y))try{w=JSON.parse(o.readFileSync(y,"utf-8")).messages||[]}catch{}d({messages:w,exitCode:g||0,timedOut:h})}),f.stdout.resume(),f.stderr.resume()})}function NE(t,e,n){let o=t.length>0?Math.round(t.reduce((l,u)=>l+u.score,0)/t.length*10)/10:0,s=o>=9?"A":o>=8?"B":o>=7?"C":o>=6?"D":"F",r=57,i="\u2500".repeat(r);console.log(`
|
|
1385
1385
|
\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: ${o}/10 (${s}) \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
|
|
1386
|
-
`)}function
|
|
1386
|
+
`)}function ME(t=10){let e=require("fs"),o=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(o)){console.log(`${J.yellow}No score history yet. Run a session first.${J.reset}
|
|
1387
1387
|
`);return}let s=[];try{s=JSON.parse(e.readFileSync(o,"utf-8"))}catch{s=[]}if(!Array.isArray(s)||s.length===0){console.log(`${J.yellow}Score history is empty.${J.reset}
|
|
1388
1388
|
`);return}let r=s.slice(-t);console.log(`
|
|
1389
|
-
${J.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${J.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?`${J.yellow}\u26A0 ${i.issues.slice(0,2).map(m=>m.substring(0,30)).join(", ")}${J.reset}`:`${J.green}\u2713${J.reset}`,h=i.score>=8?J.green:i.score>=6?J.yellow:J.red;console.log(` ${J.dim}${c}${J.reset} ${J.dim}v${l}${J.reset} ${J.dim}${u}${J.reset} ${h}${d} ${f}${J.reset} ${p}`)}console.log()}async function
|
|
1389
|
+
${J.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${J.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?`${J.yellow}\u26A0 ${i.issues.slice(0,2).map(m=>m.substring(0,30)).join(", ")}${J.reset}`:`${J.green}\u2713${J.reset}`,h=i.score>=8?J.green:i.score>=6?J.yellow:J.red;console.log(` ${J.dim}${c}${J.reset} ${J.dim}v${l}${J.reset} ${J.dim}${u}${J.reset} ${h}${d} ${f}${J.reset} ${p}`)}console.log()}async function PE({dryRun:t=!1,model:e,cwd:n,onProgress:o}={}){let s=As(),r=Rg(n);if(t){console.log(`
|
|
1390
1390
|
${J.bold}Jarvis Benchmark \u2014 Scenarios (dry-run):${J.reset}
|
|
1391
1391
|
`);for(let l of r)console.log(` ${J.cyan}${l.id.padEnd(20)}${J.reset} ${J.dim}${l.name}${J.reset} maxTurns=${l.maxTurns}`),console.log(` ${J.dim}${l.prompt.substring(0,80)}${J.reset}`);return console.log(),[]}let i=(()=>{if(e)return typeof e=="object"?e.id||"unknown":e;try{let{getActiveModel:l}=Fs(),u=l?l():null;return u?typeof u=="object"?u.id||"unknown":u:"unknown"}catch{return"unknown"}})(),c=[];for(let l of r){o?.({id:l.id,name:l.name,done:!1}),console.log(`
|
|
1392
|
-
${J.dim}Running scenario: ${l.name}...${J.reset}`);let{messages:u,timedOut:d}=await
|
|
1392
|
+
${J.dim}Running scenario: ${l.name}...${J.reset}`);let{messages:u,timedOut:d}=await OE(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=Cg(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),o?.({id:l.id,name:l.name,done:!0,score:f.score,grade:f.grade});try{let{appendScoreHistory:h}=Li();h(f.score,{version:s.version,model:i,sessionName:`bench:${l.id}`,issues:f.issues})}catch{}}return NE(c,s.version,i),c}Ag.exports={runBenchmark:CE,runDiscoverBenchmark:AE,buildSummary:zl,buildCategoryWinners:Sg,TASKS:Gl,PHASE_TASKS:xg,ALL_TASKS:ga,scoreResult:mo,DEFAULT_MODELS:Yl,QUICK_MODELS:vg,runJarvisBenchmark:PE,showScoreTrend:ME,loadScenarios:Rg,DEFAULT_SCENARIOS:ha,scoreJarvisScenario:Cg}});var qg=Q((HR,Dg)=>{"use strict";var LE=require("os"),Mg=require("path"),Xl=require("fs"),{callWithRetry:Og}=xi(),{parseModelSpec:IE}=je(),{extractJSON:Ng,DECOMPOSE_PROMPT:jE,SYNTHESIZE_PROMPT:DE}=sr(),{C:Lt}=Fe(),$a=Mg.join(LE.homedir(),".nex-code","orchestrator-bench.json"),Pg=[{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 Lg(t,e){if(!Array.isArray(t))return 0;let n=0;n+=1.5;let o=Math.abs(t.length-e.expectedSubTasks);o===0?n+=3:o===1&&(n+=1.5),t.every(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 Ig(t,e){if(!t||typeof t!="object")return 0;let n=0;n+=1.5,t.summary&&t.summary.length>10&&(n+=2),t.commitMessage&&t.commitMessage.length>5&&(n+=2);let o=Array.isArray(t.conflicts)?t.conflicts:[];return e.expectedConflicts===0&&o.length===0||e.expectedConflicts>0&&o.length>0?n+=2.5:e.expectedConflicts>0&&o.length===0&&(n+=0),Array.isArray(t.filesChanged)&&t.filesChanged.length>0&&(n+=2),Math.min(10,Math.round(n*10)/10)}async function jg(t,e){let n={};if(e){let s=IE(e);s.provider&&(n.provider=s.provider),s.model&&(n.model=s.model)}let o=Date.now();try{if(t.type==="decompose"){let s=jE.replace("{maxSubTasks}",String(t.maxSubTasks)).replace("{prompt}",t.prompt),r=await Og([{role:"system",content:s},{role:"user",content:t.prompt}],[],n),i=Ng(r.content||""),c=Date.now()-o;return{score:Lg(i,t),latencyMs:c}}if(t.type==="synthesize"){let s=t.subResults.map((d,f)=>{let p=d.status==="done"?"SUCCESS":"FAILED";return`--- Agent ${f+1} [${p}] ---
|
|
1393
1393
|
Task: ${d.task}
|
|
1394
1394
|
Result: ${d.result}
|
|
1395
1395
|
Tools: ${d.toolsUsed.join(", ")}`}).join(`
|
|
1396
1396
|
|
|
1397
|
-
`),r=
|
|
1397
|
+
`),r=DE.replace("{prompt}",t.prompt).replace("{results}",s),i=await Og([{role:"system",content:r},{role:"user",content:"Synthesize the sub-agent results above."}],[],n),c=Ng(i.content||""),l=Date.now()-o;return{score:Ig(c,t),latencyMs:l}}return{score:0,latencyMs:0,error:`Unknown scenario type: ${t.type}`}}catch(s){return{score:0,latencyMs:Date.now()-o,error:s.message}}}async function qE(t={}){let e=t.models||["kimi-k2.5","qwen3.5:397b","minimax-m2.7:cloud"],n=t.onProgress||(()=>{}),o=[];for(let r of e){let i={model:r,scores:[],latencies:[]},c=[],l=[];for(let h of Pg){n({model:r,scenario:h.id,done:!1});let m=await jg(h,r);i.scores.push(m.score),i.latencies.push(m.latencyMs),h.type==="decompose"&&c.push(m.score),h.type==="synthesize"&&l.push(m.score),n({model:r,scenario:h.id,done:!0,score:m.score,error:m.error})}let u=c.length>0?c.reduce((h,m)=>h+m,0)/c.length:0,d=l.length>0?l.reduce((h,m)=>h+m,0)/l.length:0,f=i.latencies.reduce((h,m)=>h+m,0)/i.latencies.length,p=u*.6+d*.4;o.push({model:r,decompose:Math.round(u*10)/10,synthesize:Math.round(d*10)/10,avgLatency:Math.round(f),overall:Math.round(p*10)/10})}o.sort((r,i)=>i.overall-r.overall);let s=Mg.dirname($a);return Xl.existsSync(s)||Xl.mkdirSync(s,{recursive:!0}),Xl.writeFileSync($a,JSON.stringify({date:new Date().toISOString().slice(0,10),results:o},null,2)),o}function FE(t){console.log(`
|
|
1398
1398
|
${Lt.bold}${Lt.cyan}Orchestrator Model Benchmark${Lt.reset}
|
|
1399
1399
|
`);let e=` ${"Model".padEnd(25)} ${"Decompose".padEnd(10)} ${"Synthesize".padEnd(11)} ${"Speed".padEnd(8)} ${"Score".padEnd(8)}`;console.log(`${Lt.dim}${e}${Lt.reset}`),console.log(` ${Lt.dim}${"\u2500".repeat(65)}${Lt.reset}`);for(let n of t){let o=t.indexOf(n)===0?"\u{1F947}":t.indexOf(n)===1?"\u{1F948}":t.indexOf(n)===2?"\u{1F949}":" ",s=`${(n.avgLatency/1e3).toFixed(1)}s`;console.log(`${o} ${n.model.padEnd(25)} ${(n.decompose+"/10").padEnd(10)} ${(n.synthesize+"/10").padEnd(11)} ${s.padEnd(8)} ${Lt.bold}${n.overall}/10${Lt.reset}`)}t.length>0&&(console.log(`
|
|
1400
1400
|
${Lt.green}Best orchestrator: ${t[0].model} (${t[0].overall}/10)${Lt.reset}`),console.log(` ${Lt.dim}Saved to ${$a}${Lt.reset}
|
|
1401
|
-
`))}Dg.exports={runOrchestratorBenchmark:
|
|
1401
|
+
`))}Dg.exports={runOrchestratorBenchmark:qE,ORCHESTRATOR_SCENARIOS:Pg,scoreDecompose:Lg,scoreSynthesize:Ig,runScenario:jg,printResults:FE,RESULTS_PATH:$a}});var Bg=Q((KR,Ug)=>{var UE=require("axios"),_r=require("fs"),Fg=require("path"),BE="nex-code",Jl=Fg.join(process.cwd(),".nex"),Vl=Fg.join(Jl,"last-version-check");_r.existsSync(Jl)||_r.mkdirSync(Jl,{recursive:!0});async function WE(){try{let t=KE(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};GE(e);let n=HE(),s=(await UE.get(`https://registry.npmjs.org/${BE}/latest`,{timeout:5e3})).data.version,r=YE(s,n);return{hasNewVersion:r,latestVersion:r?s:void 0,currentVersion:r?n:void 0}}catch{return{hasNewVersion:!1}}}function HE(){return As().version}function KE(){try{if(_r.existsSync(Vl)){let t=_r.readFileSync(Vl,"utf8");return parseInt(t,10)}}catch{}return null}function GE(t){try{_r.writeFileSync(Vl,t.toString())}catch{}}function YE(t,e){try{let n=t.split(".").map(Number),o=e.split(".").map(Number);return n[0]>o[0]?!0:n[0]<o[0]?!1:n[1]>o[1]?!0:n[1]<o[1]?!1:n[2]>o[2]}catch{return!1}}Ug.exports={checkForNewVersion:WE}});var iu=Q((YR,Qg)=>{var zE=require("readline"),it=require("fs"),tt=require("path"),{C:a,banner:XE,cleanupTerminal:Wg}=Fe(),{isDark:JE}=Yn(),{listProviders:eu,getActiveProviderName:ks,listAllModels:GR,setFallbackChain:VE,getFallbackChain:ZE,getProvider:QE}=je(),{flushAutoSave:Hg}=Jt(),{getActiveModel:En,setActiveModel:tu}=Fs(),{printContext:Kg}=Mi(),{loadAllSkills:eT,getSkillCommands:wa,handleSkillCommand:tT}=Mn(),{setReadlineInterface:nT,setAutoConfirm:sT,getAutoConfirm:Zl,setAllowAlwaysHandler:oT}=ft(),{StickyFooter:rT}=Xh(),Ht=process.cwd(),Le=null,nn=null;function Gg(){return nn?.signal??null}var Sr=[{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 Jarvis 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 Yg(){let t=wa(),e=[...Sr,...t],n=Math.max(...e.map(o=>o.cmd.length));console.log("");for(let{cmd:o,desc:s}of Sr)console.log(` ${a.cyan}${o.padEnd(n+2)}${a.reset}${a.dim}${s}${a.reset}`);for(let{cmd:o,desc:s}of t)console.log(` ${a.cyan}${o.padEnd(n+2)}${a.reset}${a.dim}${s} ${a.yellow}[skill]${a.reset}`);console.log(`
|
|
1402
1402
|
${a.dim}Type /help for detailed usage${a.reset}
|
|
1403
|
-
`)}function zg(t){try{let e,n;t.endsWith("/")||t.endsWith(
|
|
1403
|
+
`)}function zg(t){try{let e,n;t.endsWith("/")||t.endsWith(tt.sep)?(e=t,n=""):(e=tt.dirname(t),n=tt.basename(t)),e.startsWith("~")&&(e=tt.join(require("os").homedir(),e.slice(1)));let o=tt.isAbsolute(e)?e:tt.resolve(Ht,e);if(!it.existsSync(o)||!it.statSync(o).isDirectory())return[];let s=it.readdirSync(o,{withFileTypes:!0}),r=[];for(let i of s){if(i.name.startsWith(".")||i.name==="node_modules"||n&&!i.name.startsWith(n))continue;let c=t.endsWith("/")||t.endsWith(tt.sep)?t:tt.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?i.name:c+i.name;r.push(i.isDirectory()?l+"/":l)}return r}catch{return[]}}function Xg(t){if(t.startsWith("/")){let o=[...Sr,...wa()],s=o.map(r=>r.cmd).filter(r=>r.startsWith(t));return[s.length?s:o.map(r=>r.cmd),t]}let e=t.split(/\s+/),n=e[e.length-1]||"";return n&&(n.includes("/")||n.startsWith("./")||n.startsWith("../")||n.startsWith("~"))?[zg(n),n]:[[],t]}function Jg(){console.log(`
|
|
1404
1404
|
${a.bold}${a.cyan}Commands:${a.reset}
|
|
1405
1405
|
${a.cyan}/help${a.reset} ${a.dim}Show this help${a.reset}
|
|
1406
1406
|
${a.cyan}/model [spec]${a.reset} ${a.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${a.reset}
|
|
@@ -1474,7 +1474,7 @@ ${a.bold}${a.cyan}Undo / Redo:${a.reset}
|
|
|
1474
1474
|
|
|
1475
1475
|
${a.cyan}/exit${a.reset} ${a.dim}Quit${a.reset}
|
|
1476
1476
|
`)}function Vg(t){let n=Math.round(t/100*30),o=30-n;return` ${t>80?a.red:t>50?a.yellow:a.green}${"\u2588".repeat(n)}${a.dim}${"\u2591".repeat(o)}${a.reset} ${t}%`}function Ql(){let t=eu(),e=ks(),n=En();console.log(`
|
|
1477
|
-
${a.bold}${a.cyan}Providers:${a.reset}`);for(let o of t){let s=o.provider===e,r=o.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,i=s?` ${a.cyan}(active)${a.reset}`:"";console.log(` ${r} ${a.bold}${o.provider}${a.reset}${i}`);for(let c of o.models){let l=c.id===n.id&&s?` ${a.yellow}\u25C4${a.reset}`:"";console.log(` ${a.dim}${c.id}${a.reset} \u2014 ${c.name}${l}`)}}console.log()}async function kr(t,e){let[n,...o]=t.split(/\s+/);switch(n){case"/help":return Jg(),!0;case"/model":{let s=o.join(" ").trim();if(!s){if(e){let{showModelPicker:r}=Zh();await r(e)}else{let r=En(),i=ks();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(s==="list")return Ql(),!0;if(tu(s)){let r=En(),i=ks();console.log(`${a.green}Switched to ${i}:${r.id} (${r.name})${a.reset}`)}else console.log(`${a.red}Unknown model: ${s}${a.reset}`),console.log(`${a.gray}Use /providers to see available models${a.reset}`);return!0}case"/providers":return Ql(),!0;case"/fallback":{let s=o.join(" ").trim();if(!s){let i=
|
|
1477
|
+
${a.bold}${a.cyan}Providers:${a.reset}`);for(let o of t){let s=o.provider===e,r=o.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,i=s?` ${a.cyan}(active)${a.reset}`:"";console.log(` ${r} ${a.bold}${o.provider}${a.reset}${i}`);for(let c of o.models){let l=c.id===n.id&&s?` ${a.yellow}\u25C4${a.reset}`:"";console.log(` ${a.dim}${c.id}${a.reset} \u2014 ${c.name}${l}`)}}console.log()}async function kr(t,e){let[n,...o]=t.split(/\s+/);switch(n){case"/help":return Jg(),!0;case"/model":{let s=o.join(" ").trim();if(!s){if(e){let{showModelPicker:r}=Zh();await r(e)}else{let r=En(),i=ks();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(s==="list")return Ql(),!0;if(tu(s)){let r=En(),i=ks();console.log(`${a.green}Switched to ${i}:${r.id} (${r.name})${a.reset}`)}else console.log(`${a.red}Unknown model: ${s}${a.reset}`),console.log(`${a.gray}Use /providers to see available models${a.reset}`);return!0}case"/providers":return Ql(),!0;case"/fallback":{let s=o.join(" ").trim();if(!s){let i=ZE();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=s.split(",").map(i=>i.trim()).filter(Boolean);return VE(r),console.log(`${a.green}Fallback chain: ${r.join(" \u2192 ")}${a.reset}`),!0}case"/tokens":{let{getConversationMessages:s}=ve(),{getUsage:r}=Ct(),{TOOL_DEFINITIONS:i}=Gt(),c=s(),l=r(c,i),u=En(),d=ks();console.log(`
|
|
1478
1478
|
${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=Vg(l.percentage);return console.log(` ${f}`),console.log(`
|
|
1479
1479
|
${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:s,resetCosts:r}=qs();return o.join(" ").trim()==="reset"?(r(),console.log(`${a.green}Cost tracking reset${a.reset}`),!0):(console.log(`
|
|
1480
1480
|
${s()}
|
|
@@ -1486,7 +1486,7 @@ ${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let y of m){let w=r(y.pr
|
|
|
1486
1486
|
`):p=String(f.content),r(c.slice(0,l));let{resetSessionTracking:h}=ve();h();let m=d||"current model";return console.log(`${a.cyan}Retrying with ${m}...${a.reset}`),await i(p),!0}case"/context":return await Kg(Ht),!0;case"/tree":{let{generateFileTree:s}=Mi(),r=parseInt(o.join(" ").trim(),10),i=!isNaN(r)&&r>0?Math.min(r,8):3,c=s(Ht,{maxDepth:i,maxFiles:300});return console.log(`
|
|
1487
1487
|
${a.bold}${a.cyan}Project tree${a.reset}${a.dim} (depth ${i})${a.reset}
|
|
1488
1488
|
`),console.log(`${a.dim}${c}${a.reset}
|
|
1489
|
-
`),!0}case"/autoconfirm":{let s=!Zl();return
|
|
1489
|
+
`),!0}case"/autoconfirm":{let s=!Zl();return sT(s),console.log(`${a.green}Auto-confirm: ${s?"ON":"OFF"}${a.reset}`),s&&console.log(`${a.yellow} \u26A0 File changes will be applied without confirmation${a.reset}`),xr(),!0}case"/save":{let{saveSession:s}=Jt(),{getConversationMessages:r}=ve(),i=o.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=En(),u=ks();return s(i,c,{model:l.id,provider:u}),console.log(`${a.green}Session saved: ${i} (${c.length} messages)${a.reset}`),!0}case"/load":{let{loadSession:s}=Jt(),{setConversationMessages:r}=ve(),i=o.join(" ").trim();if(!i)return console.log(`${a.red}Usage: /load <name>${a.reset}`),!0;let c=s(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:s}=Jt(),r=s();if(r.length===0)return console.log(`${a.dim}No saved sessions${a.reset}`),!0;console.log(`
|
|
1490
1490
|
${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:s}=Jt(),{setConversationMessages:r}=ve(),i=s();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:s,renderTree:r}=Un(),{getConversationMessages:i}=ve(),c=i();return c.length===0?(console.log(`${a.yellow}No conversation yet${a.reset}`),!0):(Le||(Le=s({messages:c})),console.log(r(Le)),console.log(),!0)}case"/timeline":{let{initTree:s,renderTimeline:r}=Un(),{getConversationMessages:i}=ve(),c=i();if(c.length===0)return console.log(`${a.yellow}No conversation yet${a.reset}`),!0;Le||(Le=s({messages:c})),Un().setActiveMessages(Le,c);let u=parseInt(o[0],10)||20;return console.log(r(Le,u)),console.log(),!0}case"/goto":{let s=Un(),{getConversationMessages:r,setConversationMessages:i}=ve(),c=r();if(c.length===0)return console.log(`${a.yellow}No conversation yet${a.reset}`),!0;let l=parseInt(o[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;Le||(Le=s.initTree({messages:c})),s.setActiveMessages(Le,c);try{let{truncated:u}=s.gotoMessage(Le,l),d=s.getActiveMessages(Le);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 s=Un(),{getConversationMessages:r,setConversationMessages:i}=ve(),c=r();if(c.length===0)return console.log(`${a.yellow}No conversation yet${a.reset}`),!0;Le||(Le=s.initTree({messages:c})),s.setActiveMessages(Le,c);let l=o[0]?parseInt(o[0],10):c.length-1,u=o[1]||void 0;if(isNaN(l))return console.log(`${a.red}Usage: /fork [message-index] [branch-name]${a.reset}`),!0;try{let{branchName:d}=s.createBranch(Le,l,u),f=s.getActiveMessages(Le);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 s=Un(),{getConversationMessages:r,setConversationMessages:i}=ve();if(!Le){let l=r();Le=s.initTree({messages:l})}s.setActiveMessages(Le,r());let c=o.join(" ").trim();if(!c)return console.log(`${a.red}Usage: /switch-branch <name>${a.reset}`),console.log(`${a.dim}Available: ${Object.keys(Le.branches).join(", ")}${a.reset}`),!0;try{s.switchBranch(Le,c);let l=s.getActiveMessages(Le);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 s=Un();if(!Le){let{getConversationMessages:i}=ve();Le=s.initTree({messages:i()})}let r=o.join(" ").trim();if(!r)return console.log(`${a.red}Usage: /delete-branch <name>${a.reset}`),!0;try{s.deleteBranch(Le,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:s}=un(),r=o.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),s(c,l),console.log(`${a.green}Remembered: ${c}${a.reset}`),!0}case"/forget":{let{forget:s}=un(),r=o.join(" ").trim();return r?(s(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:s}=un(),r=s();if(r.length===0)return console.log(`${a.dim}No memories saved${a.reset}`),!0;console.log(`
|
|
1491
1491
|
${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:s,readDocument:r,writeDocument:i,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=Do(),p=o[0],h=o.slice(1).join(" ").trim();switch(p){case"add":{if(!h)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=h.indexOf(" ");if(m<0){i(h,`# ${h}
|
|
1492
1492
|
|
|
@@ -1613,66 +1613,66 @@ ${a.dim}No deploy configs. Run /init to create .nex/deploy.json${a.reset}
|
|
|
1613
1613
|
`),!0;console.log(`
|
|
1614
1614
|
${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}`,h=[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}${h}`)}return console.log(`
|
|
1615
1615
|
${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}
|
|
1616
|
-
`),!0}case"/init":{let{runServerWizard:s,runDeployWizard:r,setWizardRL:i}=$g();return i(e),o[0]==="deploy"?await r():await s(),!0}case"/setup":{let{runSetupWizard:s}=Il();return await s({rl:e,force:!0}),!0}case"/benchmark":{try{let y=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(
|
|
1617
|
-
`)}}catch{}if(o.includes("--history")){let y=require("os"),w=
|
|
1616
|
+
`),!0}case"/init":{let{runServerWizard:s,runDeployWizard:r,setWizardRL:i}=$g();return i(e),o[0]==="deploy"?await r():await s(),!0}case"/setup":{let{runSetupWizard:s}=Il();return await s({rl:e,force:!0}),!0}case"/benchmark":{try{let y=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(it.existsSync(y)){let w=(Date.now()-it.statSync(y).mtimeMs)/864e5;w>30&&console.log(`${a.dim} \u2139 Benchmark results are ${Math.floor(w)} days old \u2014 run /benchmark --all to refresh${a.reset}
|
|
1617
|
+
`)}}catch{}if(o.includes("--history")){let y=require("os"),w=tt.join(y.homedir(),"Coding","nex-code-benchmarks","results");if(!it.existsSync(w)){console.log(`${a.yellow}No nightly results at ${w}${a.reset}`),console.log(`${a.dim}Use /benchmark (no flags) to run a live model comparison.${a.reset}`);break}let v=it.readdirSync(w).filter(C=>C.endsWith(".json")).sort().slice(-7);if(v.length===0){console.log(`${a.yellow}No result files found${a.reset}`);break}console.log(`
|
|
1618
1618
|
${a.bold}${a.cyan}OpenClaw Nightly Results (${v.length}-day trend)${a.reset}
|
|
1619
|
-
`),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 M=[];for(let C of v)try{let S=JSON.parse(
|
|
1619
|
+
`),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 M=[];for(let C of v)try{let S=JSON.parse(it.readFileSync(tt.join(w,C),"utf-8")),O=C.replace(".json",""),D=S.tasks?.length||S.total||0,K=S.tasks?.filter(R=>R.passed||R.score>=.7)?.length||S.passed||0,V=S.score??S.overall_score??(D>0?Math.round(K/D*100):"N/A"),X=S.model||S.config?.model||"unknown";M.push({date:O,model:X,total:D,passed:K,score:V});let B=typeof V=="number"?V>=80?a.green:V>=60?a.yellow:a.red:a.dim;console.log(` ${O.padEnd(12)} ${X.substring(0,24).padEnd(25)} ${B}${String(V).padEnd(8)}${a.reset} ${K}/${D}`)}catch{}if(M.length>=2){let C=M[0].score,S=M[M.length-1].score;if(typeof C=="number"&&typeof S=="number"){let O=S-C,D=O>0?`${a.green}\u25B2 +${O}`:O<0?`${a.red}\u25BC ${O}`:`${a.dim}\u2192 stable`;console.log(`
|
|
1620
1620
|
${a.bold}Trend:${a.reset} ${D}${a.reset} over ${M.length} days`)}}console.log();break}if(o.includes("--all")){let{fetchCloudModels:y,markBenchmarked:w,updateReadme:v,updateModelsEnv:M,updateRoutingConfig:C}=po(),{runBenchmark:S,buildCategoryWinners:O}=Wn(),D=new Set(["nemotron-3-super:cloud"]),K=o.find(E=>E.startsWith("--parallel=")),V=K?Math.max(1,parseInt(K.replace("--parallel=",""),10)||3):3;console.log(`
|
|
1621
1621
|
${a.bold}Fetching all available Ollama Cloud models...${a.reset}`);let X;try{X=await y()}catch(E){console.log(`${a.red}Failed to fetch model list: ${E.message}${a.reset}`);break}let B=X.filter(E=>!D.has(E)),R=X.filter(E=>D.has(E)),ye=56,be=Math.ceil(ye*B.length*4/V/60);console.log(`${a.cyan}${B.length} models found${a.reset}`+(R.length>0?` ${a.dim}(${R.length} blacklisted: ${R.join(", ")})${a.reset}`:"")),console.log(`${a.dim}Models: ${B.join(", ")}${a.reset}`),console.log(`${a.dim}${ye} tasks \xB7 ${V} parallel \xB7 ~${be}min estimated${a.reset}
|
|
1622
|
-
`);let
|
|
1623
|
-
${a.cyan}${E.padEnd(30)}${a.reset} `));return}let se=
|
|
1624
|
-
`);let xe=require("os"),
|
|
1622
|
+
`);let pe=new Map,me=await S({models:B,quick:!1,parallelModels:V,onProgress:({model:E,task:A,done:T,score:L,error:ae})=>{if(!T){pe.has(E)||(pe.set(E,""),process.stdout.write(`
|
|
1623
|
+
${a.cyan}${E.padEnd(30)}${a.reset} `));return}let se=ae?`${a.red}\u2717${a.reset}`:L>=80?`${a.green}\xB7${a.reset}`:L>=40?`${a.yellow}\xB7${a.reset}`:`${a.red}\xB7${a.reset}`;process.stdout.write(se)}});process.stdout.write(`
|
|
1624
|
+
`);let xe=require("os"),he=require("path").join(xe.homedir(),".nex-code","benchmark-results.json");try{require("fs").writeFileSync(he,JSON.stringify(me,null,2))}catch{}w(B);let ge=O(me),Re=C(ge),k=require("path").join(process.cwd(),"README.md"),j=v(me,k),x=M(me);if(j&&console.log(`
|
|
1625
1625
|
${a.green}README.md benchmark table updated${a.reset}`),x.updated&&console.log(`${a.green}DEFAULT_MODEL: ${x.previousModel} \u2192 ${x.newModel}${a.reset}`),Re.changes.length>0){console.log(`${a.green}Routing updated:${a.reset}`);for(let E of Re.changes)console.log(` ${a.dim}${E}${a.reset}`)}return console.log(),!0}if(o.includes("--discover")){let{findNewModels:y,markBenchmarked:w,updateReadme:v,updateModelsEnv:M}=po(),{runDiscoverBenchmark:C,buildSummary:S}=Wn();console.log(`
|
|
1626
1626
|
${a.bold}Checking Ollama Cloud for new models...${a.reset}`);let O;try{O=await y()}catch(k){console.log(`${a.red}Discovery failed: ${k.message}${a.reset}`);break}let{newModels:D,allCloud:K}=O;if(console.log(`${a.dim}${K.length} models available on cloud${a.reset}`),D.length===0){console.log(`${a.green}No new models since last benchmark run.${a.reset}
|
|
1627
1627
|
`);break}console.log(`${a.cyan}New models to benchmark (${D.length}):${a.reset} ${D.join(", ")}
|
|
1628
|
-
`);let V=require("os"),X=
|
|
1628
|
+
`);let V=require("os"),X=tt.join(V.homedir(),".nex-code","benchmark-results.json"),B=[];try{it.existsSync(X)&&(B=JSON.parse(it.readFileSync(X,"utf-8")))}catch{}let R="",ye=await C({newModels:D,existingRanking:B,onProgress:({model:k,task:j,done:x,score:E,error:A})=>{if(!x){k!==R&&(R&&process.stdout.write(`
|
|
1629
1629
|
`),R=k,process.stdout.write(`${a.cyan}${k}${a.reset} `));return}let T=A?`${a.red}\u2717${a.reset}`:E>=80?`${a.green}\xB7${a.reset}`:E>=40?`${a.yellow}\xB7${a.reset}`:`${a.red}\xB7${a.reset}`;process.stdout.write(T)}});R&&process.stdout.write(`
|
|
1630
|
-
`);try{
|
|
1630
|
+
`);try{it.writeFileSync(X,JSON.stringify(ye,null,2))}catch{}w(K);let be=tt.join(process.cwd(),"README.md"),pe=v(ye,be),me=M(ye),{buildCategoryWinners:xe}=Wn(),{updateRoutingConfig:he}=po(),ge=xe(ye),Re=he(ge);if(pe&&console.log(`${a.green}README.md benchmark table updated${a.reset}`),me.updated?console.log(`${a.green}DEFAULT_MODEL: ${me.previousModel} \u2192 ${me.newModel}${a.reset}`):me.reason&&console.log(`${a.dim}models.env unchanged: ${me.reason}${a.reset}`),Re.changes.length>0){console.log(`${a.green}Routing updated:${a.reset}`);for(let k of Re.changes)console.log(` ${a.dim}${k}${a.reset}`)}return console.log(),!0}let{runBenchmark:s,DEFAULT_MODELS:r,QUICK_MODELS:i}=Wn(),c=o.includes("--quick"),l=o.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(`
|
|
1631
1631
|
${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}
|
|
1632
1632
|
`);let p="",h=0,m=d*f.length,g=await s({models:f,quick:c,onProgress:({model:y,task:w,done:v,score:M,error:C})=>{if(!v){y!==p&&(p&&process.stdout.write(`
|
|
1633
1633
|
`),p=y,process.stdout.write(`${a.cyan}${y}${a.reset} `));return}h++;let S=C?`${a.red}\u2717${a.reset}`:M>=80?`${a.green}\xB7${a.reset}`:M>=40?`${a.yellow}\xB7${a.reset}`:`${a.red}\xB7${a.reset}`;process.stdout.write(S)}});if(p&&process.stdout.write(`
|
|
1634
1634
|
`),!c&&g&&g.length>0){let{buildCategoryWinners:y}=Wn(),{updateRoutingConfig:w,updateReadme:v,updateModelsEnv:M}=po(),C=y(g),S=w(C);if(S.changes.length>0){console.log(`
|
|
1635
|
-
${a.bold}Per-category routing saved:${a.reset}`);for(let V of S.changes)console.log(` ${a.dim}${V}${a.reset}`)}let O=
|
|
1635
|
+
${a.bold}Per-category routing saved:${a.reset}`);for(let V of S.changes)console.log(` ${a.dim}${V}${a.reset}`)}let O=tt.join(process.cwd(),"README.md");v(g,O)&&console.log(`${a.green}README.md updated${a.reset}`),M(g);let D=require("os"),K=tt.join(D.homedir(),".nex-code","benchmark-results.json");try{it.writeFileSync(K,JSON.stringify(g,null,2))}catch{}}return!0}case"/bench":{let{runJarvisBenchmark:s}=Wn(),r=o.includes("--dry-run"),i=o.find(l=>l.startsWith("--model=")),c=i?i.replace("--model=","").trim():void 0;return r||console.log(`
|
|
1636
1636
|
${a.bold}Jarvis Benchmark${a.reset} ${a.dim}5 agentic scenarios \xB7 each run as child process${a.reset}
|
|
1637
1637
|
`),await s({dryRun:r,model:c,cwd:Ht,onProgress:({id:l,name:u,done:d,score:f,grade:p})=>{if(!d)process.stdout.write(`${a.dim} \u2192 ${u}...${a.reset}`);else{let h=f>=8?a.green:f>=6?a.yellow:a.red;process.stdout.write(` ${h}${f}/10 (${p})${a.reset}
|
|
1638
1638
|
`)}}}),!0}case"/trend":{let{showScoreTrend:s}=Wn(),r=parseInt(o[0],10)||10;return s(r),!0}case"/orchestrate":{let s=o.join(" ").trim();if(!s)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}=sr();return await r(s),!0}case"/bench-orchestrator":{let{runOrchestratorBenchmark:s,printResults:r}=qg(),i=o.find(u=>u.startsWith("--models=")),c=i?i.replace("--models=","").split(",").map(u=>u.trim()):void 0,l=await s({models:c,onProgress:({model:u,scenario:d,done:f,score:p,error:h})=>{f?h?process.stdout.write(` ${a.red}ERR${a.reset}
|
|
1639
1639
|
`):process.stdout.write(` ${a.green}${p}/10${a.reset}
|
|
1640
|
-
`):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 s=
|
|
1641
|
-
`).filter(Boolean).slice(-nu)}catch{}return[]}function ya(t){try{let e=su(),n=
|
|
1642
|
-
`)}catch{}}function It(){return`${a.bold}${a.cyan}\u203A${a.reset} `}function xr(){if(!global._nexFooter)return;let{isPlanMode:t,getAutonomyLevel:e}=Vt(),{getAutoConfirm:n}=ft(),o=[];t()&&o.push("plan");let s=e();s==="semi-auto"&&o.push("semi"),s==="autonomous"&&o.push("auto"),n()&&o.push("always"),global._nexFooter.setStatusInfo({mode:o.join(" \xB7 ")})}var ou="\x1B[200~",ru="\x1B[201~";function
|
|
1640
|
+
`):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 s=tT(t);if(s)return s.agentPrompt&&(kr._pendingAgentPrompt=s.agentPrompt),!0;{let r=[...Sr,...wa()].map(u=>u.cmd.split(" ")[0]),i=(u,d)=>{let f=u.length,p=d.length,h=Array.from({length:f+1},(m,g)=>Array.from({length:p+1},(y,w)=>g===0?w:w===0?g:0));for(let m=1;m<=f;m++)for(let g=1;g<=p;g++)h[m][g]=u[m-1]===d[g-1]?h[m-1][g-1]:1+Math.min(h[m-1][g],h[m][g-1],h[m-1][g-1]);return h[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 nu=1e3;function su(){return tt.join(process.cwd(),".nex","repl_history")}function Zg(){try{let t=su();if(it.existsSync(t))return it.readFileSync(t,"utf-8").split(`
|
|
1641
|
+
`).filter(Boolean).slice(-nu)}catch{}return[]}function ya(t){try{let e=su(),n=tt.dirname(e);it.existsSync(n)||it.mkdirSync(n,{recursive:!0}),it.appendFileSync(e,t+`
|
|
1642
|
+
`)}catch{}}function It(){return`${a.bold}${a.cyan}\u203A${a.reset} `}function xr(){if(!global._nexFooter)return;let{isPlanMode:t,getAutonomyLevel:e}=Vt(),{getAutoConfirm:n}=ft(),o=[];t()&&o.push("plan");let s=e();s==="semi-auto"&&o.push("semi"),s==="autonomous"&&o.push("auto"),n()&&o.push("always"),global._nexFooter.setStatusInfo({mode:o.join(" \xB7 ")})}var ou="\x1B[200~",ru="\x1B[201~";function iT(t){return typeof t=="string"&&t.includes(ou)}function aT(t){return typeof t=="string"&&t.includes(ru)}function vr(t){return typeof t!="string"?t:t.split(ou).join("").split(ru).join("")}async function cT(){if(!QE("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"),tu("local:llama3"),!0}catch{return!1}}async function lT(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:n}=ve();t(Gg);let s=eu().some(x=>x.configured),r=(async()=>{eT();let x=En(),E=ks();return{model:x,providerName:E}})(),i=(async()=>s?!0:await cT()?(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}
|
|
1643
1643
|
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:x}=Bg();return await x()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,i,c]);!u&&!s&&(console.error(`
|
|
1644
1644
|
${a.red}\u2717 No provider configured and no local Ollama detected.${a.reset}
|
|
1645
|
-
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:p}=yn();f().then(x=>{}),p().catch(()=>{});let h=Zg(),m=
|
|
1645
|
+
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:p}=yn();f().then(x=>{}),p().catch(()=>{});let h=Zg(),m=zE.createInterface({input:process.stdin,output:process.stdout,prompt:It(),completer:Xg,history:h,historySize:nu});nT(m);let{setAskUserHandler:g}=Gt();g(async(x,E)=>{let A="\x1B[0m",T="\x1B[1m",L="\x1B[2m",ae="\x1B[36m";return process.stdout.write(`
|
|
1646
1646
|
${T}\x1B[33m\u2753${A} ${T}${x}${A}
|
|
1647
1647
|
|
|
1648
|
-
`),E.forEach((
|
|
1648
|
+
`),E.forEach((ie,Ce)=>{process.stdout.write(` ${ae}${Ce+1}${A} ${ie}
|
|
1649
1649
|
`)}),process.stdout.write(` ${L}${E.length+1}${A} ${L}Eigene Antwort\u2026${A}
|
|
1650
1650
|
`),process.stdout.write(`
|
|
1651
|
-
${
|
|
1652
|
-
`),
|
|
1653
|
-
`),
|
|
1654
|
-
`),
|
|
1651
|
+
${ae}[1-${E.length+1}]${A} \u203A `),new Promise(ie=>{m.resume(),m.once("line",Ce=>{let at=Ce.trim(),et=parseInt(at);et>=1&&et<=E.length?(process.stdout.write(`
|
|
1652
|
+
`),ie(E[et-1])):et===E.length+1||at===""?(process.stdout.write(` ${ae}\u203A${A} `),m.once("line",Tn=>{process.stdout.write(`
|
|
1653
|
+
`),ie(Tn.trim()||"")})):(process.stdout.write(`
|
|
1654
|
+
`),ie(at))})})});let y=new rT;y.activate(m),global._nexFooter=y,global._nexRawWrite=x=>y.rawWrite(x),oT(()=>xr()),process.stdout.isTTY&&process.stdout.write("\x1B[H\x1B[2J\x1B[3J");let w=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;XE(w,Ht,{yolo:Zl()});{y.setStatusInfo({model:w,branch:"",project:tt.basename(Ht)});let{execFile:x}=require("child_process");x("git",["rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"},(E,A)=>{!E&&A&&y.setStatusInfo({model:w,branch:A.trim(),project:tt.basename(Ht)})})}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}
|
|
1655
1655
|
`),await Kg(Ht);let v=!1,M=0,C=!1,S=null;function O(){Hg(),y.deactivate(),Wg(),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",O),process.on("exit",()=>{Hg()}),m.on("SIGINT",()=>{if(Wg(),M++,M>=2){O();return}if(v){nn&&nn.abort();let{cancelPendingAskUser:x}=Gt();x(),console.log(`
|
|
1656
1656
|
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),v=!1,m.setPrompt(It()),m.prompt()}else console.log(`${a.dim} (Press Ctrl+C again to exit)${a.reset}`),m.setPrompt(It()),m.prompt(),S&&clearTimeout(S),S=setTimeout(()=>{M=0,S=null},2e3)}),process.on("SIGINT",()=>{process.stdin.isTTY?(M++,M>=2&&O()):O()});let D=!1,K=[],V=0,X={},B=!1;function R(){let x=K.join(`
|
|
1657
1657
|
`).replace(/\r/g,"").trim();if(K=[],D=!1,!x)return!0;V++,B=!0;let E=V;X[E]=x;let A=x.split(`
|
|
1658
|
-
`).length,T=A>1?`[Pasted content #${E} \u2014 ${A} lines]`:`[Pasted content #${E}]`,L=m.line||"",
|
|
1658
|
+
`).length,T=A>1?`[Pasted content #${E} \u2014 ${A} lines]`:`[Pasted content #${E}]`,L=m.line||"",ae=L&&!L.endsWith(" ")?" ":"",se=L+ae+T;return m.setPrompt(It()),m.prompt(),m.line=se,m.cursor=se.length,m._refreshLine(),!0}function ye(x){return x.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(E,A)=>X[Number(A)]||"")}function be(){V=0,X={},B=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let x=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(E,...A){if(E!=="data")return x.call(process.stdin,E,...A);let T=A[0];if(Buffer.isBuffer(T)&&(T=T.toString("utf8")),typeof T!="string")return x.call(process.stdin,E,...A);let L=T.includes(ou),ae=T.includes(ru);if(L&&ae){let se=vr(T);return se&&K.push(...se.split(`
|
|
1659
1659
|
`)),R()}if(L){D=!0,K=[];let se=vr(T);return se&&K.push(...se.split(`
|
|
1660
|
-
`)),!0}if(
|
|
1660
|
+
`)),!0}if(ae){let se=vr(T);return se&&K.push(...se.split(`
|
|
1661
1661
|
`)),R()}if(D){let se=vr(T);return se&&K.push(...se.split(`
|
|
1662
1662
|
`)),!0}return T.includes(`
|
|
1663
1663
|
`)&&T.length>40&&!D?(K.push(...T.replace(/\r/g,"").split(`
|
|
1664
|
-
`)),R()):x.call(process.stdin,E,...A)}}let
|
|
1665
|
-
${L}. `).trim()}let{loadSession:k}=Jt(),{setConversationMessages:j}=ve();if(e()===0){let x=k("_autosave");if(x&&x.messages&&x.messages.length>0&&Date.now()-new Date(x.updatedAt).getTime()<1440*60*1e3){let{confirm:A}=ft();if(await A("Previous session found. Resume?")){let
|
|
1666
|
-
`),m.prompt()}return}if(
|
|
1667
|
-
`).trim();if(
|
|
1668
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${
|
|
1669
|
-
`).trim();if(
|
|
1670
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${Ce}${a.reset}`)}}let{getConversationLength:
|
|
1671
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${se}${a.reset}`)}}v=!1}m.setPrompt(It()),m.prompt();return}{let L=
|
|
1672
|
-
`);process.stdout.isTTY&&process.stdout.write(`\x1B[${se.length}A`),se.forEach((
|
|
1673
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${
|
|
1674
|
-
`)}function
|
|
1675
|
-
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=ft(),n=new Map,o=0;e((c,l)=>{let u="cfm-"+ ++o,d=l?.toolName||"",f=!1;try{let{isCritical:p}=ft();f=p(c)}catch{}return Ss({type:"confirm_request",id:u,question:c,tool:d,critical:f}),new Promise(p=>{n.set(u,p)})});let s=null,r={onToken(c){s&&Ss({type:"token",id:s,text:c})},onThinkingToken(){},onToolStart(c,l){s&&Ss({type:"tool_start",id:s,tool:c,args:l||{}})},onToolEnd(c,l,u){s&&Ss({type:"tool_end",id:s,tool:c,summary:l||"",ok:!!u})}},i=
|
|
1664
|
+
`)),R()):x.call(process.stdin,E,...A)}}let pe=0;function me(){if(pe>0){let x=y._scrollEnd,E="\x1B7";for(let A=0;A<pe;A++)E+=`\x1B[${x-pe+1+A};1H\x1B[2K`;E+="\x1B8",y.rawWrite(E),pe=0}}function xe(x){let E=[...Sr,...wa()].filter(Ce=>Ce.cmd.startsWith(x));if(!E.length||E.length===1&&E[0].cmd===x)return;let A=y._scrollEnd,T=Math.min(10,A-2);if(T<1)return;let L=E.slice(0,T),ae=Math.max(...L.map(Ce=>Ce.cmd.length));pe=L.length,E.length>T&&pe++;let se=A-pe+1,ie="\x1B7";for(let Ce=0;Ce<L.length;Ce++){let{cmd:at,desc:et}=L[Ce],Tn=at.substring(0,x.length),ba=at.substring(x.length),_a=" ".repeat(Math.max(0,ae-at.length+2));ie+=`\x1B[${se+Ce};1H\x1B[2K ${a.cyan}${Tn}${a.reset}${a.dim}${ba}${_a}${et}${a.reset}`}E.length>T&&(ie+=`\x1B[${se+L.length};1H\x1B[2K ${a.dim}\u2026 +${E.length-T} more${a.reset}`),ie+="\x1B8",y.rawWrite(ie)}process.stdin.isTTY&&process.stdin.on("keypress",(x,E)=>{me(),!(E&&(E.name==="tab"||E.name==="return"))&&setImmediate(()=>{m.line&&m.line.startsWith("/")&&xe(m.line)})});let he=null,ge=`${a.dim}...${a.reset} `;function Re(x){return(x.match(/[^\s\d](\d{1,2})\.\s+\S/g)||[]).length<2?x:x.replace(/([^\s\d])(\d{1,2})\.\s+/g,(A,T,L)=>`${T}
|
|
1665
|
+
${L}. `).trim()}let{loadSession:k}=Jt(),{setConversationMessages:j}=ve();if(e()===0){let x=k("_autosave");if(x&&x.messages&&x.messages.length>0&&Date.now()-new Date(x.updatedAt).getTime()<1440*60*1e3){let{confirm:A}=ft();if(await A("Previous session found. Resume?")){let ae=x.messages,se=ae.length>20?ae.slice(-20):ae;j(se);let{getUsage:ie,forceCompress:Ce}=Ct();if(ie(se,[]).percentage>=30){let{messages:et}=Ce(se,[]);j(et)}}}}m.setPrompt(It()),m.prompt(),m.on("line",async x=>{if(me(),Object.keys(X).length>0&&(x=ye(x),be(),m.setPrompt(It())),v){let L=x.trim();if(L){let{injectMidRunNote:ae}=ve();ae(L),process.stdout.write(`${a.cyan} \u270E Queued \u2014 will be applied in the next step${a.reset}
|
|
1666
|
+
`),m.prompt()}return}if(he!==null){if(he._mode==="triple"){if(x.trim()==='"""'){let L=he.join(`
|
|
1667
|
+
`).trim();if(he=null,L){ya(L.replace(/\n/g,"\\n")),v=!0,m.prompt(),M=0,C=!1,S&&(clearTimeout(S),S=null),nn=new AbortController;try{await n(L)}catch(se){if(!nn?.signal?.aborted){let ie=se.message?.split(`
|
|
1668
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${ie}${a.reset}`)}}v=!1;let ae=A();ae>0&&process.stdout.write(`${a.gray}[${ae} messages] ${a.reset}`)}m.setPrompt(It()),m.prompt();return}he.push(x),m.setPrompt(ge),m.prompt();return}if(x.endsWith("\\"))he.push(x.slice(0,-1));else{he.push(x);let L=he.join(`
|
|
1669
|
+
`).trim();if(he=null,L){ya(L.replace(/\n/g,"\\n")),v=!0,m.prompt(),M=0,C=!1,S&&(clearTimeout(S),S=null),nn=new AbortController;try{await n(L)}catch(ie){if(!nn?.signal?.aborted){let Ce=ie.message?.split(`
|
|
1670
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${Ce}${a.reset}`)}}let{getConversationLength:ae}=ve();v=!1;let se=ae();se>0&&process.stdout.write(`${a.gray}[${se} messages] ${a.reset}`)}m.setPrompt(It()),m.prompt();return}m.setPrompt(ge),m.prompt();return}if(x.trim()==='"""'||x.trim().startsWith('"""')){let L=x.trim().substring(3);he=L?[L]:[],he._mode="triple",m.setPrompt(ge),m.prompt();return}if(x.endsWith("\\")){he=[x.slice(0,-1)],he._mode="backslash",m.setPrompt(ge),m.prompt();return}let E=Re(x.trim());if(!E){m.setPrompt(It()),m.prompt();return}if(ya(E),E==="/"){Yg(),m.setPrompt(It()),m.prompt();return}if(E.startsWith("/")){await kr(E,m);let L=kr._pendingAgentPrompt;if(L){kr._pendingAgentPrompt=null;try{let{isPlanMode:ae,setPlanMode:se}=Vt(),{invalidateSystemPromptCache:ie}=ve();ae()&&(se(!1),ie())}catch{}v=!0,m.prompt(),M=0,C=!1,S&&(clearTimeout(S),S=null),nn=new AbortController;try{await n(L,null,{autoOrchestrate:!1,skipPhaseRouting:!0,skillLoop:!0,maxIterations:200})}catch(ae){if(!nn?.signal?.aborted){let se=ae.message?.split(`
|
|
1671
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${se}${a.reset}`)}}v=!1}m.setPrompt(It()),m.prompt();return}{let L=JE?"\x1B[48;5;237m":"\x1B[48;2;220;225;235m",ae=process.stdout.columns||80,se=E.split(`
|
|
1672
|
+
`);process.stdout.isTTY&&process.stdout.write(`\x1B[${se.length}A`),se.forEach((ie,Ce)=>{let at=Ce===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",et=2+ie.length,Tn=" ".repeat(Math.max(0,ae-et));console.log(`\x1B[2K${L}${at} ${ie}${Tn}\x1B[0m`)}),console.log()}if(process.env.NEX_AUTO_PLAN!=="0"&&!Zl()){let{isPlanMode:L,setPlanMode:ae}=Vt(),{invalidateSystemPromptCache:se}=ve(),ie=/\b(implement|refactor|migrate|redesign)\b/i,Ce=/\b(create|build|add|write|introduce|develop|set\s+up)\b/i,at=/^(how|what|why|when|where|which|explain|show|list|tell|describe|can\s+you|could\s+you|do\s+you)\b/i,et=/\b(spawn[_\s]?agents?|swarm)\b/i;!at.test(E)&&!et.test(E)&&(ie.test(E)||Ce.test(E)&&E.split(/\s+/).length>=5)&&!L()&&(ae(!0),se(),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:L}=ve();if(L()===0)try{let{detectCategory:ae,getModelForCategory:se}=In(),ie=ae(E);if(ie&&ie.id!=="coding"){let Ce=se(ie.id),at=En();if(Ce&&Ce!==at?.id&&tu(Ce)){let et=En();console.log(`${a.dim}\u21B3 ${ie.icon} ${ie.label} task \u2014 routing to ${et?.name||Ce}${a.reset}`),global._nexFooter&&global._nexFooter.setStatusInfo({model:et?.name||Ce})}}}catch{}}v=!0,m.prompt(),M=0,C=!1,S&&(clearTimeout(S),S=null),nn=new AbortController;try{await n(E)}catch(L){if(!nn?.signal?.aborted){let ae=L.message?.split(`
|
|
1673
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${ae}${a.reset}`)}}v=!1;let{getConversationLength:A}=ve(),T=A();T>0&&process.stdout.write(`${a.gray}[${T} messages] ${a.reset}`),m.setPrompt(It()),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)})}Qg.exports={startREPL:lT,getPrompt:It,loadHistory:Zg,appendHistory:ya,getHistoryPath:su,HISTORY_MAX:nu,showCommandList:Yg,completer:Xg,completeFilePath:zg,handleSlashCommand:kr,showProviders:Ql,showHelp:Jg,renderBar:Vg,hasPasteStart:iT,hasPasteEnd:aT,stripPasteSequences:vr,getAbortSignal:Gg}});var t$=Q((zR,e$)=>{"use strict";var uT=require("readline");function Ss(t){process.stdout.write(JSON.stringify(t)+`
|
|
1674
|
+
`)}function dT(){process.env.NEX_SERVER="1";let t=(...c)=>process.stderr.write(c.map(String).join(" ")+`
|
|
1675
|
+
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=ft(),n=new Map,o=0;e((c,l)=>{let u="cfm-"+ ++o,d=l?.toolName||"",f=!1;try{let{isCritical:p}=ft();f=p(c)}catch{}return Ss({type:"confirm_request",id:u,question:c,tool:d,critical:f}),new Promise(p=>{n.set(u,p)})});let s=null,r={onToken(c){s&&Ss({type:"token",id:s,text:c})},onThinkingToken(){},onToolStart(c,l){s&&Ss({type:"tool_start",id:s,tool:c,args:l||{}})},onToolEnd(c,l,u){s&&Ss({type:"tool_end",id:s,tool:c,summary:l||"",ok:!!u})}},i=uT.createInterface({input:process.stdin,output:null,terminal:!1});Ss({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();s=d;let{processInput:f}=ve();try{await f(u.text,r),Ss({type:"done",id:d})}catch(p){Ss({type:"error",id:d,message:p?.message||String(p)})}finally{s=null}break}case"confirm":{let d=n.get(u.id);d&&(n.delete(u.id),d(!!u.answer));break}case"cancel":{for(let[d,f]of n)n.delete(d),f(!1);break}case"clear":{let{clearConversation:d}=ve();d();for(let[f,p]of n)n.delete(f),p(!1);break}default:break}}),i.on("close",()=>{process.exit(0)})}e$.exports={startServerMode:dT}});var s$=Q((XR,n$)=>{n$.exports=iu()});var du=require("path");require("dotenv").config({path:du.join(__dirname,"..",".env")});require("dotenv").config();var ke=process.argv.slice(2);(ke.includes("--help")||ke.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
1676
1676
|
|
|
1677
1677
|
Options:
|
|
1678
1678
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -1692,6 +1692,6 @@ Options:
|
|
|
1692
1692
|
--mcp-config <path> Path to MCP server config (default: .nex/mcp.json)
|
|
1693
1693
|
-h, --help Show this help
|
|
1694
1694
|
-v, --version Show version
|
|
1695
|
-
`),process.exit(0));if(ke.includes("-v")||ke.includes("--version")){let t=As();console.log(t.version),process.exit(0)}var i$=ke.includes("--yolo")||ke.includes("-yolo");if(i$){let{setAutoConfirm:t}=ft();t(!0)}if(!i$)try{let t=require("fs"),e=du.join(process.cwd(),".nex","config.json");if(t.existsSync(e)&&JSON.parse(t.readFileSync(e,"utf-8")).yolo===!0){let{setAutoConfirm:o}=ft();o(!0)}}catch{}var au=ke.indexOf("--model");if(au!==-1&&ke[au+1]){let{setActiveModel:t}=je();t(ke[au+1])}var cu=ke.indexOf("--max-turns");if(cu!==-1&&ke[cu+1]){let t=parseInt(ke[cu+1],10);if(t>0){let{setMaxIterations:e}=ve();e(t)}}else try{let t=require("fs"),e=du.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let n=JSON.parse(t.readFileSync(e,"utf-8")),o=parseInt(n.maxIterations,10);if(o>0){let{setMaxIterations:s}=ve();s(o)}}}catch{}var lu=ke.indexOf("--mcp-config");lu!==-1&&ke[lu+1]&&(process.env.NEX_MCP_CONFIG=ke[lu+1]);function uu(){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
|
|
1695
|
+
`),process.exit(0));if(ke.includes("-v")||ke.includes("--version")){let t=As();console.log(t.version),process.exit(0)}var i$=ke.includes("--yolo")||ke.includes("-yolo");if(i$){let{setAutoConfirm:t}=ft();t(!0)}if(!i$)try{let t=require("fs"),e=du.join(process.cwd(),".nex","config.json");if(t.existsSync(e)&&JSON.parse(t.readFileSync(e,"utf-8")).yolo===!0){let{setAutoConfirm:o}=ft();o(!0)}}catch{}var au=ke.indexOf("--model");if(au!==-1&&ke[au+1]){let{setActiveModel:t}=je();t(ke[au+1])}var cu=ke.indexOf("--max-turns");if(cu!==-1&&ke[cu+1]){let t=parseInt(ke[cu+1],10);if(t>0){let{setMaxIterations:e}=ve();e(t)}}else try{let t=require("fs"),e=du.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let n=JSON.parse(t.readFileSync(e,"utf-8")),o=parseInt(n.maxIterations,10);if(o>0){let{setMaxIterations:s}=ve();s(o)}}}catch{}var lu=ke.indexOf("--mcp-config");lu!==-1&&ke[lu+1]&&(process.env.NEX_MCP_CONFIG=ke[lu+1]);function uu(){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 fT(){let{runSetupWizard:t}=Il();await t()}function o$(t){if(ke.includes("--auto")){let{setAutoConfirm:c}=ft();c(!0)}if(!ke.includes("--model")){let{setActiveModel:c}=je(),l=process.env.HEADLESS_MODEL||"devstral-small-2:24b";c(l)}let n=!ke.includes("--no-auto-orchestrate")&&process.env.NEX_AUTO_ORCHESTRATE!=="false",o=ke.indexOf("--orchestrator-model"),s=o!==-1?ke[o+1]:void 0;if(t.startsWith("/")){let{handleSlashCommand:c}=iu();c(t,null).then(()=>process.exit(0)).catch(l=>{console.error(l.message),process.exit(1)});return}let{processInput:r,getConversationMessages:i}=ve();r(t,null,{autoOrchestrate:n,orchestratorModel:s}).then(()=>{if(ke.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=>{ke.includes("--json")?console.log(JSON.stringify({success:!1,error:c.message})):console.error(c.message),process.exit(1)})}if(ke.includes("--server")){let{setAutoConfirm:t}=ft();t(!0),t$().startServerMode();return}var r$=ke.indexOf("--prompt-file");if(r$!==-1){let t=ke[r$+1];(!t||t.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let e=require("fs"),n;try{n=e.readFileSync(t,"utf-8").trim()}catch(o){console.error(`--prompt-file: cannot read file: ${o.message}`),process.exit(1)}if(n||(console.error("--prompt-file: file is empty"),process.exit(1)),ke.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}uu(),o$(n)}else{let t=ke.indexOf("--task")!==-1?ke.indexOf("--task"):ke.indexOf("--prompt");if(t!==-1){let e=ke[t+1];if((!e||e.startsWith("--"))&&(console.error("--task/--prompt requires a prompt"),process.exit(1)),uu(),ke.includes("--orchestrate")){let n=ke.indexOf("--orchestrator-model"),o=n!==-1?ke[n+1]:void 0,{runOrchestrated:s}=sr();s(e,{orchestratorModel:o}).then(()=>{process.exit(0)}).catch(r=>{console.error(`Orchestrator error: ${r.message}`),process.exit(1)})}else o$(e)}else fT().then(()=>{uu();let{startREPL:e}=s$();e(),setTimeout(async()=>{try{let{loadKnownModels:n,findNewModels:o}=po(),s=n(),r=s.lastChecked?new Date(s.lastChecked):null;if((r?(Date.now()-r.getTime())/864e5:999)<7||!process.env.OLLAMA_API_KEY)return;let{newModels:c}=await o();if(c.length>0){let{C:l}=Fe();process.stdout.write(`
|
|
1696
1696
|
${l.dim}\u{1F4A1} ${c.length} new Ollama Cloud model(s) available \u2014 /benchmark --discover to test them${l.reset}
|
|
1697
1697
|
`)}}catch{}},3e3)})}
|