nex-code 0.4.23 → 0.4.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -4
- package/dist/nex-code.js +272 -271
- package/dist/skills/autoresearch.js +975 -0
- package/dist/skills/devops.md +43 -0
- package/dist/skills/session-search.js +180 -0
- package/dist/skills/skill-learning.js +304 -0
- package/dist/skills/skills/autoresearch.js +975 -0
- package/dist/skills/skills/devops.md +43 -0
- package/dist/skills/skills/session-search.js +180 -0
- package/dist/skills/skills/skill-learning.js +304 -0
- package/package.json +2 -2
package/dist/nex-code.js
CHANGED
|
@@ -1,33 +1,33 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var As=Q((fT,S$)=>{S$.exports={name:"nex-code",version:"0.4.
|
|
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
|
|
2
|
+
var Q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var As=Q((fT,S$)=>{S$.exports={name:"nex-code",version:"0.4.25",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 && 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((pT,Ou)=>{"use strict";var Su="\x1B[0m",Eu="\x1B[1m",Os="\x1B[2m";function Z(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function E$(){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 Tu(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function T$(t){try{let n=require("fs").readFileSync(Tu(),"utf8"),o=JSON.parse(n);if(o&&typeof o[t]=="boolean")return o[t]}catch{}return null}function R$(t,e){try{let n=require("fs"),o=require("path"),s=Tu(),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 C$(){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=T$(n);if(o!==null)return o;let s=E$(),r=s!==null?s:!0;return R$(n,r),r}var Ru=C$(),Cu={reset:Su,bold:Eu,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"},Au={reset:Su,bold:Eu,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)},A$=Ru?Cu:Au;Ou.exports={T:A$,isDark:Ru,DARK:Cu,LIGHT:Au}});var Ms=Q((mT,Mu)=>{var{T:ne}=Yn(),Pr=5,Ns=(()=>{let t=[];for(let e=0;e<Pr;e++)t.push(e);for(let e=Pr-2;e>=1;e--)t.push(e);return t})(),Nu=["\u273D","\u2726","\u2727","\u2726"],Ra=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<Pr;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}},Ca=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}
|
|
7
|
-
`}process.stderr.write(s)}},
|
|
8
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=
|
|
7
|
+
`}process.stderr.write(s)}},Nr={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Mr={done:ne.green,in_progress:ne.cyan,pending:ne.dim,failed:ne.red},Rn=null,Aa=class{constructor(e,n){this.name=e,this.tasks=n.map(o=>({id:o.id,description:o.description,status:o.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let n=Math.floor(e/60),o=e%60;return n>0?`${n}m ${String(o).padStart(2,"0")}s`:`${o}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=Nu[this.frame%Nu.length],n=this._formatElapsed(),o=this._formatTokens(),s=[n,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=s?` ${ne.dim}(${s})${ne.reset}`:"",i=`\x1B[2K${ne.cyan}${e}${ne.reset} ${this.name}\u2026${r}
|
|
8
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=Nr[l.status]||Nr.pending,f=Mr[l.status]||Mr.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} ${p}
|
|
9
9
|
`}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let n=0;n<this.lineCount;n++)e+=`
|
|
10
10
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Rn=this}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._paused||this._renderFinal(),process.stderr.write("\x1B[?25h"),this._paused=!1,Rn===this&&(Rn=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let n=0;n<this.lineCount;n++)e+=`\x1B[2K
|
|
11
11
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let n=0;n<this.lineCount;n++)e+=`
|
|
12
12
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,n){let o=this.tasks.find(s=>s.id===e);o&&(o.status=n)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),n=this.tasks.filter(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
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=
|
|
14
|
-
`}process.stderr.write(i)}},
|
|
13
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=Nr[l.status]||Nr.pending,f=Mr[l.status]||Mr.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)}},Oa=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<Pr;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 O$(t){Rn=t}function N$(){return Rn}function M$(){Rn&&(Rn.stop(),Rn=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Mu.exports={C:ne,Spinner:Ra,MultiProgress:Ca,TaskProgress:Aa,ToolProgress:Oa,setActiveTaskProgress:O$,getActiveTaskProgress:N$,cleanupTerminal:M$}});var Na=Q((hT,ju)=>{"use strict";var ue={kw:"\x1B[34m",str:"\x1B[32m",cmt:"\x1B[90m",num:"\x1B[33m",type:"\x1B[36m",punct:"\x1B[35m",reset:"\x1B[0m"},Pu={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"])},P$={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 Lu(t){if(!t)return null;let e=t.split(".").pop().toLowerCase();return P$[e]||null}function L$(t){return t.replace(/"([^"\\]|\\.)*"\s*:/g,e=>ue.type+e+ue.reset).replace(/"([^"\\]|\\.)*"/g,e=>ue.str+e+ue.reset).replace(/\b-?(\d+(\.\d+)?([eE][+-]?\d+)?)\b/g,e=>ue.num+e+ue.reset).replace(/\b(true|false|null)\b/g,e=>ue.kw+e+ue.reset)}function I$(t){return/<!--/.test(t)?t.replace(/<!--[\s\S]*?(?:-->|$)/g,e=>ue.cmt+e+ue.reset):t.replace(/(<\/?)([a-zA-Z][a-zA-Z0-9.-]*)/g,(e,n,o)=>n+ue.type+o+ue.reset).replace(/\s([a-zA-Z][a-zA-Z0-9-]*)=/g,(e,n)=>" "+ue.kw+n+ue.reset+"=").replace(/"([^"]*)"/g,e=>ue.str+e+ue.reset)}function j$(t){return t.replace(/\/\*[\s\S]*?(?:\*\/|$)/g,e=>ue.cmt+e+ue.reset).replace(/#[0-9a-fA-F]{3,8}\b/g,e=>ue.num+e+ue.reset).replace(/\b(-?\d+(?:\.\d+)?)(px|em|rem|vh|vw|vmin|vmax|%|s|ms|deg|fr)\b/g,(e,n,o)=>ue.num+n+ue.reset+o).replace(/([a-z][a-z-]*)(\s*:)/g,(e,n,o)=>ue.type+n+ue.reset+o).replace(/"[^"]*"|'[^']*'/g,e=>ue.str+e+ue.reset)}function Iu(t,e,n){if(e==="json")return L$(t);if(e==="html"||e==="xml")return I$(t);if(e==="css")return j$(t);if(e==="md")return t;let o=Pu[e]||Pu.js,s="",r=0;if(n.inBlockComment){let i=t.indexOf("*/");if(i===-1)return ue.cmt+t+ue.reset;if(s+=ue.cmt+t.slice(0,i+2)+ue.reset,n.inBlockComment=!1,r=i+2,r>=t.length)return s}if(n.inString==="`"){let i=t.indexOf("`");if(i===-1)return ue.str+t+ue.reset;if(s+=ue.str+t.slice(0,i+1)+ue.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+=ue.cmt+t.slice(r)+ue.reset,n.inBlockComment=!0,s;s+=ue.cmt+t.slice(r,c+2)+ue.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+=ue.cmt+t.slice(r)+ue.reset,s;if(!n.inString&&(i==='"'||i==="'"||i==="`")){n.inString=i,s+=ue.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+ue.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+=ue.num+c+ue.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+=ue.punct+c+ue.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+=ue.kw+c+ue.reset:/^[A-Z][A-Za-z0-9]*$/.test(c)&&e!=="sh"?s+=ue.type+c+ue.reset:s+=c;continue}s+=i,r++}return n.inString&&n.inString!=="`"&&(s+=ue.reset,n.inString=null),s}function D$(t,e){let n=Lu(e);if(!n)return t.split(`
|
|
15
15
|
`);let o=t.split(`
|
|
16
|
-
`),s={inString:null,inBlockComment:!1};return o.map(r=>
|
|
16
|
+
`),s={inString:null,inBlockComment:!1};return o.map(r=>Iu(r,n,s))}function q$(t,e){return e?Iu(t,e,{inString:null,inBlockComment:!1}):t}ju.exports={detectLang:Lu,highlightLine:q$,highlightLines:D$}});var qu=Q((gT,Du)=>{var{T:P}=Yn(),dt=P,F$={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},Ma={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 Lr(t,e=!1,n=null){if(e)return`${P.error}\u23FA${P.reset}`;let o=F$[t]||P.tool_default;return n==="blink"?`${o}\x1B[5m\u23FA\x1B[25m${P.reset}`:`${o}${n!==null?n:"\u23FA"}${P.reset}`}function U$(t,e,n=!1,o=null){let s=(t||[]).filter(l=>l&&l.canExecute!==!1);if(s.length===0)return`${Lr("",n,o)} Step ${e}`;if(s.length===1){let l=s[0],u=l.args||{},d=Ma[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`${Lr(l.fnName,n,o)} ${dt.bold}${d}${dt.reset}${p}`}let r=s[0].fnName,i=[...new Set(s.map(l=>Ma[l.fnName]||l.fnName.replace(/_/g," ")))],c=i.length<=3?i.join(", "):`${s.length} tools`;return`${Lr(r,n,o)} ${dt.bold}${c}${dt.reset}`}function B$(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=Ma[t]||t.replace(/_/g," "),s=n?`(${dt.dim}${n}${dt.reset})`:"";return`${Lr(t)} ${dt.bold}${o}${dt.reset}${s}`}function W$(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
19
|
${P.subtle} \u2026 +${s} lines${P.reset}`),c}function H$(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 K$(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(`
|
|
23
|
-
`).length,u=e.path?require("path").basename(e.path):null,d=u?`Wrote ${u} \xB7 ${l} line${l!==1?"s":""}`:`Wrote ${l} line${l!==1?"s":""}`,{highlightLines:f}=
|
|
23
|
+
`).length,u=e.path?require("path").basename(e.path):null,d=u?`Wrote ${u} \xB7 ${l} line${l!==1?"s":""}`:`Wrote ${l} line${l!==1?"s":""}`,{highlightLines:f}=Na(),p=f(e.content||"",e.path||null),h=40,m=8;if(l<=h){let g=p.map(y=>` ${y}`).join(`
|
|
24
24
|
`);r=`${d}
|
|
25
25
|
${g}`}else{let g=p.slice(0,m).map(y=>` ${y}`).join(`
|
|
26
26
|
`);r=`${d}
|
|
27
27
|
${g}
|
|
28
28
|
${P.subtle}\u2026 +${l-m} lines${P.reset}`}break}case"edit_file":{let c=(e.old_text||"").split(`
|
|
29
29
|
`),l=(e.new_text||"").split(`
|
|
30
|
-
`),u=c.length,d=l.length,f=e.path?require("path").basename(e.path):null,p=f?` ${P.muted}${f}${P.reset}`:"",h=c.find(M=>M.trim()),m=l.find(M=>M.trim()),{highlightLine:g,detectLang:y}=
|
|
30
|
+
`),u=c.length,d=l.length,f=e.path?require("path").basename(e.path):null,p=f?` ${P.muted}${f}${P.reset}`:"",h=c.find(M=>M.trim()),m=l.find(M=>M.trim()),{highlightLine:g,detectLang:y}=Na(),w=y(e.path||null),v=[];h&&v.push(` ${P.diff_rem}- ${P.reset}${g(h.trimEnd().substring(0,72),w)}${P.reset}`),m&&v.push(` ${P.diff_add}+ ${P.reset}${g(m.trimEnd().substring(0,72),w)}${P.reset}`),r=`${P.diff_rem}\u2212${u}${P.reset} ${P.diff_add}+${d}${P.reset}${p}`+(v.length>0?`
|
|
31
31
|
`+v.join(`
|
|
32
32
|
`):"");break}case"patch_file":{let c=e.patches||[],l=c.reduce((d,f)=>d+(f.old_text||"").split(`
|
|
33
33
|
`).length,0),u=c.reduce((d,f)=>d+(f.new_text||"").split(`
|
|
@@ -48,86 +48,86 @@ ${g}
|
|
|
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
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 G$(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}
|
|
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}Du.exports={C:dt,formatToolCall:B$,formatResult:W$,getToolSpinnerText:H$,formatToolSummary:K$,formatSectionHeader:U$,formatMilestone:G$}});var Fe=Q(($T,Uu)=>{var{T:zn}=Yn(),Pa=zn,Fu=["01100110","01111110","01111110","01011010","01111110","00111100"];function Y$(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 z$(t,e,n={}){let o=Pa.bold,s=Pa.reset,r=Y$(Fu,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=Fu[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:X$,MultiProgress:J$,TaskProgress:V$,ToolProgress:Z$,setActiveTaskProgress:Q$,getActiveTaskProgress:ey,cleanupTerminal:ty}=Ms(),{formatToolCall:ny,formatResult:sy,getToolSpinnerText:oy,formatToolSummary:ry,formatSectionHeader:iy,formatMilestone:ay}=
|
|
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){
|
|
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")}},Ir=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}}))}}},jr=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 Ir(e,n)}},Dr=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}}})}}},qr=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 Dr(e,n)}},Fr=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||{}}}))}}},Ur=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 Fr(e,n)}},vy=new jr,ky=new qr,Sy=new Ur;zu.exports={WireProtocol:Ls,StreamParser:Is,OpenAICompatibleProtocol:jr,AnthropicProtocol:qr,OllamaChatProtocol:Ur,OpenAIStreamParser:Ir,AnthropicStreamParser:Dr,OllamaStreamParser:Fr,openaiProtocol:vy,anthropicProtocol:ky,ollamaProtocol:Sy}});var Vu=Q((_T,Ju)=>{var Br=require("axios"),Ey=require("http"),Ty=require("https"),{BaseProvider:Ry,readStreamErrorBody:Cy}=Ps(),{ollamaProtocol:Jn}=js(),Wr=new Ey.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Hr=new Ty.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Xu={"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}},Fa=class extends Ry{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Xu,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){Br.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Wr,httpsAgent:Hr}).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 Br.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Wr,httpsAgent:Hr})).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
|
|
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 nd.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 nd.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 My(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)}};od.exports={AnthropicProvider:Ba,ANTHROPIC_MODELS:sd}});var ld=Q((kT,cd)=>{var id=require("axios"),{BaseProvider:Ly,readStreamErrorBody:Iy}=Ps(),{openaiProtocol:Zn}=js(),ad={"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}},Wa=class extends Ly{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||ad,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 id.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 id.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 Iy(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)}};cd.exports={GeminiProvider:Wa,GEMINI_MODELS:ad}});var fd=Q((ST,dd)=>{var Kr=require("axios"),{BaseProvider:jy,readStreamErrorBody:Dy}=Ps(),{ollamaProtocol:Qn}=js(),ud="http://localhost:11434",Ha=class extends jy{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||ud,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 Kr.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 Kr.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
|
|
61
|
-
`)}}function
|
|
62
|
-
`)}function Yy(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function zy(t,e,n,o){let s=
|
|
63
|
-
`),c}catch(c){throw s.stop(),c}}async function mw(t,e){return yo.callChat(t,e)}
|
|
54
|
+
`)}var{Spinner:X$,MultiProgress:J$,TaskProgress:V$,ToolProgress:Z$,setActiveTaskProgress:Q$,getActiveTaskProgress:ey,cleanupTerminal:ty}=Ms(),{formatToolCall:ny,formatResult:sy,getToolSpinnerText:oy,formatToolSummary:ry,formatSectionHeader:iy,formatMilestone:ay}=qu();Uu.exports={C:Pa,banner:z$,Spinner:X$,MultiProgress:J$,TaskProgress:V$,ToolProgress:Z$,setActiveTaskProgress:Q$,getActiveTaskProgress:ey,cleanupTerminal:ty,formatToolCall:ny,formatResult:sy,getToolSpinnerText:oy,formatToolSummary:ry,formatSectionHeader:iy,formatMilestone:ay}});var ft=Q((yT,Yu)=>{var cy=require("readline"),{C:rn}=Fe(),ja=[/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/],Bu=[...ja,/\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 ly(t){for(let e of Bu)if(e.test(t))return e;return null}var Wu=[/\.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)/],uy=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,La=[/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 Hu(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)):La.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:La.some(c=>c.test(i))};return o.every(s)}var Da=[/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)/],Ku=[/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/],Gu=[...Da,...Ku],qa=!1,Xn=null,Ia=null;function dy(t){qa=t}function fy(t){Ia=t}function py(){return qa}function my(t){Xn=t}function hy(t){for(let e of ja)if(e.test(t))return e;return null}function gy(t){if(/ssh\s/.test(t)&&Hu(t))return!1;for(let e of Gu)if(e.test(t))return!0;return!1}function $y(t){for(let e of Da)if(e.test(t))return!0;return!1}function yy(t){if(process.env.NEX_UNPROTECT==="1"||!uy.test(t))return null;for(let e of Wu)if(e.test(t))return e;return null}function wy(t,e={}){if(qa)return Promise.resolve(!0);if(Ia)return Ia(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return by(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${rn.yellow}${t}${rn.reset}`;for(let h=0;h<n.length;h++){let m=h===s,g=m?`${rn.yellow}\u276F${rn.reset}`:" ",y=m?`${rn.yellow}${n[h]}${rn.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&&Ir(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){Ir(e.toolName),l(!0);return}};c(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",d)})}function by(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?(Ir(e.toolName),o(!0)):o(i!=="n")};if(Xn)Xn.question(`${rn.yellow}${t} ${n}${rn.reset}`,s);else{let r=cy.createInterface({input:process.stdin,output:process.stdout});r.question(`${rn.yellow}${t} ${n}${rn.reset}`,i=>{r.close(),s(i)})}})}var Ir=()=>{};function _y(t){Ir=t}Yu.exports={FORBIDDEN_PATTERNS:ja,SSH_FORBIDDEN_PATTERNS:Bu,BASH_PROTECTED_PATHS:Wu,SSH_SAFE_PATTERNS:La,isSSHReadOnly:Hu,DANGEROUS_BASH:Gu,CRITICAL_BASH:Da,NOTABLE_BASH:Ku,isForbidden:hy,isSSHForbidden:ly,isDangerous:gy,isCritical:$y,isBashPathForbidden:yy,confirm:wy,setAutoConfirm:dy,getAutoConfirm:py,setConfirmHook:fy,setReadlineInterface:my,setAllowAlwaysHandler:_y}});var Ps=Q((wT,zu)=>{async function xy(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 Fa=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`)}};zu.exports={BaseProvider:Fa,readStreamErrorBody:xy}});var js=Q((bT,Xu)=>{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")}},jr=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}}))}}},Dr=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 jr(e,n)}},qr=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}}})}}},Fr=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 qr(e,n)}},Ur=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||{}}}))}}},Br=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 Ur(e,n)}},vy=new Dr,ky=new Fr,Sy=new Br;Xu.exports={WireProtocol:Ls,StreamParser:Is,OpenAICompatibleProtocol:Dr,AnthropicProtocol:Fr,OllamaChatProtocol:Br,OpenAIStreamParser:jr,AnthropicStreamParser:qr,OllamaStreamParser:Ur,openaiProtocol:vy,anthropicProtocol:ky,ollamaProtocol:Sy}});var Zu=Q((_T,Vu)=>{var Wr=require("axios"),Ey=require("http"),Ty=require("https"),{BaseProvider:Ry,readStreamErrorBody:Cy}=Ps(),{ollamaProtocol:Jn}=js(),Hr=new Ey.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Kr=new Ty.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Ju={"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}},Ua=class extends Ry{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Ju,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){Wr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Hr,httpsAgent:Kr}).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 Wr.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Hr,httpsAgent:Kr})).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 Wr.post(`${this.baseUrl}${Jn.getEndpoint()}`,c,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Hr,httpsAgent:Kr})}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 Wr.post(`${this.baseUrl}${Jn.getEndpoint()}`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:Hr,httpsAgent:Kr})}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 Cy(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)}};Vu.exports={OllamaProvider:Ua,OLLAMA_MODELS:Ju}});var nd=Q((xT,td)=>{var Qu=require("axios"),{BaseProvider:Ay,readStreamErrorBody:Oy}=Ps(),{openaiProtocol:Vn}=js(),ed={"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}},Ba=class extends Ay{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||ed,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 Qu.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 Qu.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 Oy(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)}};td.exports={OpenAIProvider:Ba,OPENAI_MODELS:ed}});var id=Q((vT,rd)=>{var sd=require("axios"),{BaseProvider:Ny,readStreamErrorBody:My}=Ps(),{anthropicProtocol:Cn}=js(),od={"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}},Py="2023-06-01",Wa=class extends Ny{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||od,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Py}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 sd.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 sd.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 My(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)}};rd.exports={AnthropicProvider:Wa,ANTHROPIC_MODELS:od}});var ud=Q((kT,ld)=>{var ad=require("axios"),{BaseProvider:Ly,readStreamErrorBody:Iy}=Ps(),{openaiProtocol:Zn}=js(),cd={"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}},Ha=class extends Ly{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||cd,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 ad.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 ad.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 Iy(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)}};ld.exports={GeminiProvider:Ha,GEMINI_MODELS:cd}});var pd=Q((ST,fd)=>{var Gr=require("axios"),{BaseProvider:jy,readStreamErrorBody:Dy}=Ps(),{ollamaProtocol:Qn}=js(),dd="http://localhost:11434",Ka=class extends jy{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||dd,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 Gr.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 Gr.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 Gr.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 Gr.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 Dy(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}};fd.exports={LocalProvider:Ka,DEFAULT_LOCAL_URL:dd}});var An=Q((ET,hd)=>{"use strict";var Tt=require("fs"),md=require("path");function qy(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Fy(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function Uy(t,e){let n=md.dirname(t),o=md.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{Tt.existsSync(n)||Tt.mkdirSync(n,{recursive:!0}),Tt.writeFileSync(o,e,"utf-8"),Tt.renameSync(o,t)}catch(s){try{Tt.unlinkSync(o)}catch{}throw s}}function By(t,e,{timeout:n=5e3,retryMs:o=50}={}){let s=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=Tt.openSync(s,"wx"),Tt.writeSync(i,Buffer.from(String(process.pid))),Tt.closeSync(i),i=-1;try{return e()}finally{try{Tt.unlinkSync(s)}catch{}}}catch(c){if(i!==-1)try{Tt.closeSync(i)}catch{}if(c.code!=="EEXIST")throw c;try{let l=Tt.readFileSync(s,"utf-8").trim(),u=parseInt(l,10);if(!qy(u)){try{Tt.unlinkSync(s)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{Tt.unlinkSync(s)}catch{}return e()}Fy(o)}}}hd.exports={atomicWrite:Uy,withFileLockSync:By}});var qs=Q((TT,xd)=>{var Ds=require("fs"),Ga=require("path"),{atomicWrite:Wy,withFileLockSync:Hy}=An(),gd={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:{}},Yr=[],On={};function Ky(t,e,n,o){if(Yr.push({provider:t,model:e,input:n,output:o}),On[t]!==void 0){let s=bd(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 Ya(t,e){let n=gd[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function $d(t){let e=Ya(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function yd(){let t={};for(let r of Yr){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:$d(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 Gy(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:o}=yd();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 Yy(t){return!t||typeof t!="string"?0:Math.ceil(t.length/4)}function zy(t,e,n,o){let s=Ya(t,e),r=(n*s.input+o*s.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Xy(){Yr=[]}function Jy(t,e){On[t]=e}function Vy(t){delete On[t]}function Zy(){return{...On}}function wd(t){let e=0;for(let n of Yr)n.provider===t&&(e+=$d(n));return e}function bd(t){let e=wd(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 _d(){let t=Ga.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 Qy(){let t=Ga.join(process.cwd(),".nex"),e=Ga.join(t,"config.json");Ds.existsSync(t)||Ds.mkdirSync(t,{recursive:!0}),Hy(e,()=>{let n={};if(Ds.existsSync(e))try{n=JSON.parse(Ds.readFileSync(e,"utf-8"))}catch{n={}}n.costLimits=On,Wy(e,JSON.stringify(n,null,2))})}function ew(){On={}}_d();xd.exports={PRICING:gd,trackUsage:Ky,getSessionCosts:yd,formatCosts:Gy,formatCostHint:zy,resetCosts:Xy,getPricing:Ya,setCostLimit:Jy,removeCostLimit:Vy,getCostLimits:Zy,getProviderSpend:wd,checkBudget:bd,loadCostLimits:_d,saveCostLimits:Qy,resetCostLimits:ew,estimateTokens:Yy}});var zr=Q((RT,vd)=>{function za(){return process.env.NEX_DEBUG==="true"||process.argv.includes("--debug")}var tw=za();function nw(...t){za()&&console.log(...t)}function sw(...t){za()&&console.warn(...t)}vd.exports={DEBUG:tw,debugLog:nw,warnLog:sw}});var Ed=Q((CT,Sd)=>{"use strict";var ow=new Set(["read_file","grep","glob","search_files","list_directory"]),rw=new Set(["write_file","edit_file","patch_file"]),iw=new Set(["bash"]),aw=new Set(["web_search","web_fetch","perplexity_search"]);function kd(t,e){let n=0,o=0,s=0,r=0,i=0;for(let[c,l]of t)i+=l,ow.has(c)&&(n+=l),rw.has(c)&&(o+=l),iw.has(c)&&(s+=l),aw.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 Xa=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:kd(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}};Sd.exports={MilestoneTracker:Xa,_phaseName:kd}});var Fs=Q((AT,Td)=>{var yo=je(),cw={"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 lw(){return yo.getActiveModel()}function uw(t){return yo.setActiveModel(t)}function dw(){return yo.getModelNames()}function fw(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 pw(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 mw(t,e){return yo.callChat(t,e)}Td.exports={MODELS:cw,getActiveModel:lw,setActiveModel:uw,getModelNames:dw,callOllamaStream:pw,callOllama:mw,parseToolArgs:fw}});var Ad=Q((NT,Cd)=>{var Xr=require("path"),{C:q}=Fe(),{T:Ja,isDark:OT}=Yn(),{confirm:hw,getAutoConfirm:gw}=ft(),Rd=2e3;function wo(t,e){let n=t.split(`
|
|
64
64
|
`),o=e.split(`
|
|
65
|
-
`),s=[],r=n.length,i=o.length;if(r>
|
|
65
|
+
`),s=[],r=n.length,i=o.length;if(r>Rd||i>Rd){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 $w(t,e,n,o=3){console.log(`
|
|
66
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 yw(t,e,n){console.log(`
|
|
67
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 ww(t,e){console.log(`
|
|
68
68
|
${q.bold}${q.cyan} New file: ${t}${q.reset}`);let n=e.split(`
|
|
69
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 bw(t){return gw()?!0:hw(` ${t}?`)}function _w(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 xw(t,e,n,o={}){let s=o.label||"Update",r=o.context||3,i=o.annotations||[],c=
|
|
71
|
+
`)}function xw(t,e,n,o={}){let s=o.label||"Update",r=o.context||3,i=o.annotations||[],c=Xr.isAbsolute(t)?Xr.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),$e=X.type!=="remove"?i.filter(be=>be.line===X.newLine):[];X.type==="remove"?console.log(S(
|
|
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),$e=X.type!=="remove"?i.filter(be=>be.line===X.newLine):[];X.type==="remove"?console.log(S(Ja.diff_rem_bg,q.red,`${M}${R} - ${X.line}`)):X.type==="add"?console.log(S(Ja.diff_add_bg,q.green,`${M}${R} + ${X.line}`)):console.log(`${M}${q.dim}${R} ${q.reset}${X.line}`);for(let be of $e){let fe=q.cyan,pe="\u2139";be.severity==="error"?(fe=q.red,pe="\u2716"):be.severity==="warn"&&(fe=q.yellow,pe="\u26A0"),console.log(`${M} ${fe}${pe} ${be.message}${q.reset}`)}}}console.log()}function vw(t,e,n={}){let o=Xr.isAbsolute(t)?Xr.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(`${
|
|
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
|
|
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 Tw(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await
|
|
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(`${Ja.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()}Cd.exports={diffLines:wo,showEditDiff:$w,showWriteDiff:yw,showNewFilePreview:ww,confirmFileChange:bw,showSideBySideDiff:_w,showClaudeDiff:xw,showClaudeNewFile:vw}});var Nn=Q((MT,Md)=>{var Od=require("util").promisify(require("child_process").exec),kw=require("util").promisify(require("child_process").execFile),{C:Ge}=Fe();async function Va(t){try{let{stdout:e}=await Od(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Jr(...t){try{let{stdout:e}=await kw("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Sw(){return await Va("git rev-parse --is-inside-work-tree")==="true"}async function Ew(){return await Va("git branch --show-current")}async function Za(){try{let{stdout:t}=await Od("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
76
|
+
`).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function Vr(t=!1){return await Va(`git diff ${t?"--cached":""}`)||""}async function Qa(){return(await Za()).map(e=>e.file)}async function Nd(){let t=await Qa();if(t.length===0)return null;let e=await Vr(),o=await Vr(!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 Tw(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Jr("checkout","-b",n)!==null?n:null}async function Rw(t){return await Jr("add","-A"),await Jr("commit","-m",t)?await Jr("rev-parse","--short","HEAD"):null}async function Cw(){let t=await Nd();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 Aw(){return(await
|
|
82
|
+
`)}async function Aw(){return(await Za()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Ow(){let t=await Qa();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 Vr();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
|
-
`)}
|
|
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(
|
|
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
|
|
86
|
+
`)}Md.exports={isGitRepo:Sw,getCurrentBranch:Ew,getStatus:Za,getDiff:Vr,getChangedFiles:Qa,analyzeDiff:Nd,createBranch:Tw,commit:Rw,formatDiffSummary:Cw,getDiffContext:Ow,getMergeConflicts:Aw}});var yn=Q((LT,qd)=>{var st=require("fs").promises,PT=require("fs"),Dt=require("path"),Nw=require("crypto"),{execSync:bo}=require("child_process"),Mw=100*1024,Id=50,bt=[],Us=[];function Pw(t,e,n,o){for(bt.push({tool:t,filePath:e,oldContent:n,newContent:o,timestamp:Date.now()});bt.length>Id;)bt.shift();Us.length=0,jd(bt[bt.length-1]).catch(()=>{})}async function Lw(){if(bt.length===0)return null;let t=bt.pop();if(t.oldContent===null)try{await st.unlink(t.filePath)}catch{}else await st.writeFile(t.filePath,t.oldContent,"utf-8");return Us.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Iw(){if(Us.length===0)return null;let t=Us.pop();return await st.writeFile(t.filePath,t.newContent,"utf-8"),bt.push(t),{tool:t.tool,filePath:t.filePath}}function jw(t=10){return bt.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Dw(){return bt.length}function qw(){return Us.length}function Fw({diskToo:t=!0}={}){if(bt.length=0,Us.length=0,t){let e=Qr();st.readdir(e).then(n=>{for(let o of n)o.endsWith(".json")&&st.unlink(Dt.join(e,o)).catch(()=>{})}).catch(()=>{})}}function Qr(){return Dt.join(process.cwd(),".nex","history")}async function Pd(t,e){if(t==null)return{inline:!0,content:t};if(Buffer.byteLength(t,"utf-8")<=Mw)return{inline:!0,content:t};let n=Nw.createHash("sha256").update(t,"utf-8").digest("hex"),o=Dt.join(e,"blobs");return await st.mkdir(o,{recursive:!0}),await st.writeFile(Dt.join(o,n),t,"utf-8"),{inline:!1,hash:n}}async function jd(t){let e=Qr();await st.mkdir(e,{recursive:!0});let n=Dt.basename(t.filePath).replace(/[^a-zA-Z0-9]/g,"-"),o=`${t.timestamp}-${n}.json`,s=await Pd(t.oldContent,e),r=await Pd(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 st.writeFile(Dt.join(e,o),JSON.stringify(i),"utf-8")}async function Ld(t,e){if(!t)return null;if(t.inline)return t.content;let n=Dt.join(e,"blobs",t.hash);return st.readFile(n,"utf-8")}async function Uw(){let t=Qr(),e;try{e=await st.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 st.readFile(Dt.join(t,s),"utf-8"),i=JSON.parse(r),c=await Ld(i.oldContent,t),l=await Ld(i.newContent,t);bt.push({tool:i.tool,filePath:i.filePath,timestamp:i.timestamp,oldContent:c,newContent:l}),o++}catch{}for(;bt.length>Id;)bt.shift();return o}async function Bw(t=7){let e=Qr(),n;try{n=await st.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 st.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 st.unlink(Dt.join(e,u))}catch{}let l=Dt.join(e,"blobs");try{let u=await st.readdir(l);for(let d of u)if(!i.has(d))try{await st.unlink(Dt.join(l,d))}catch{}}catch{}return r}var Zr="nex-snapshot";function Ww(t,e=process.cwd()){let n=t?`${Zr}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Zr}-${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 Dd(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(Zr)?{index:parseInt(o[1],10),label:s,shortName:s.replace(`${Zr}-`,""),date:n}:null}).filter(Boolean):[]}catch{return[]}}function Hw(t,e=process.cwd()){try{let n=Dd(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}}}qd.exports={recordChange:Pw,undo:Lw,redo:Iw,getHistory:jw,getUndoCount:Dw,getRedoCount:qw,clearHistory:Fw,persistEntry:jd,loadPersistedHistory:Uw,pruneHistory:Bw,createSnapshot:Ww,listSnapshots:Dd,restoreSnapshot:Hw}});var Mn=Q((IT,Kd)=>{var Ue=require("fs"),_t=require("path"),{atomicWrite:Kw,withFileLockSync:Gw}=An(),ht=[];function _o(){return _t.join(process.cwd(),".nex","skills")}function Fd(){return _t.join(process.cwd(),".nex","config.json")}function Ud(){let t=_o();return Ue.existsSync(t)||Ue.mkdirSync(t,{recursive:!0}),t}function nc(){let t=Fd();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 Bd(t){let e=Fd(),n=_t.dirname(e);Ue.existsSync(n)||Ue.mkdirSync(n,{recursive:!0}),Gw(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,Kw(e,JSON.stringify(o,null,2))})}function Wd(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 Hd(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
|
+
`)){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 ec(t){try{let e=Ue.readFileSync(t,"utf-8").trim();if(!e)return null;let n=_t.basename(t,".md"),{triggers:o,body:s}=Hd(e);return{name:n,type:"prompt",filePath:t,instructions:s||e,triggers:o,commands:[],tools:[]}}catch{return null}}function tc(t){try{let e=require(t),{valid:n,errors:o}=Wd(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
|
|
90
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function sc(){ht=[];let t=nc(),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=ec(r):s.endsWith(".js")&&(c=tc(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")?ec(i):tc(i);u&&(u._builtin=!0,u.enabled=!t.includes(u.name),ht.push(u))}}return ht}function Yw(){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 zw(){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 Xw(){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 Jw(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 Vw(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{r.handler(o)}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return
|
|
94
|
+
`)}`}function zw(){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 Xw(){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 Jw(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 Vw(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 Zw(){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 Qw(t){let e=ht.find(o=>o.name===t);if(!e)return!1;e.enabled=!0;let n=nc().filter(o=>o!==t);return Bd(n),!0}function e0(t){let e=ht.find(o=>o.name===t);if(!e)return!1;e.enabled=!1;let n=nc();return n.includes(t)||(n.push(t),Bd(n)),!0}function t0(){return ht}async function n0(t,e={}){let{execSync:n}=require("child_process"),o=Ud(),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 sc(),{ok:!0,name:r}}async function s0(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 o0(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}),sc(),{ok:!0}}catch(n){return{ok:!1,error:n.message}}}function r0(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}
|
|
96
|
+
`);n.push({name:o.name,instructions:r})}}return n}Kd.exports={initSkillsDir:Ud,loadAllSkills:sc,getSkillInstructions:Yw,getSkillCommands:zw,getSkillToolDefinitions:Xw,routeSkillCall:Jw,handleSkillCommand:Vw,listSkills:Zw,enableSkill:Qw,disableSkill:e0,getLoadedSkills:t0,installSkill:n0,searchSkills:s0,removeSkill:o0,matchSkillTriggers:r0,_getSkillsDir:_o,_validateScriptSkill:Wd,_loadMarkdownSkill:ec,_loadScriptSkill:tc,_parseFrontmatter:Hd}});var ti=Q((jT,Vd)=>{var{spawn:i0}=require("child_process"),a0=require("path"),Gd=require("fs"),wn=new Map;function c0(){return a0.join(process.cwd(),".nex","config.json")}function oc(){let t=c0();if(!Gd.existsSync(t))return{};try{return JSON.parse(Gd.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function ei(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
|
|
99
|
-
`):JSON.stringify(s)}function
|
|
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=
|
|
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 Yd(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=i0(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...o,...e.env||{}}}),r={name:t,proc:s,tools:[],config:e};try{await ei(s,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await ei(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 zd(t){let e=wn.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return wn.delete(t),!0}function l0(){for(let[t]of wn)zd(t)}async function Xd(t,e,n={}){let o=wn.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await ei(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 Jd(){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 u0(){return Jd().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function d0(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 Xd(o,s,e)}function f0(){let t=oc();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 p0(){let t=oc(),e=[];for(let[n,o]of Object.entries(t))try{let s=await Yd(n,o);e.push({name:n,tools:s.tools.length})}catch(s){e.push({name:n,tools:0,error:s.message})}return e}Vd.exports={loadMCPConfig:oc,sendRequest:ei,connectServer:Yd,disconnectServer:zd,disconnectAll:l0,callTool:Xd,getAllTools:Jd,getMCPToolDefinitions:u0,routeMCPCall:d0,listServers:f0,connectAll:p0}});var si=Q((DT,tf)=>{var Zd=require("fs"),rc=require("path"),ni=[],xo=[],es={},vo=["onToolResult","onModelResponse","onSessionStart","onSessionEnd","onFileChange","beforeToolExec","afterToolExec"];function Qd(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 ef(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 ic(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 m0(){let t=rc.join(process.cwd(),".nex","plugins"),e=[];if(!Zd.existsSync(t))return{loaded:0,errors:[]};let n=Zd.readdirSync(t).filter(s=>s.endsWith(".js")),o={registerTool:Qd,registerHook:ef,EVENTS:vo};for(let s of n){let r=rc.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}ni.push({name:i.name||rc.basename(s,".js"),filePath:r})}catch(i){e.push(`${s}: ${i.message}`)}}return{loaded:ni.length,errors:e}}function h0(){return xo.map(t=>t.definition)}async function g0(t,e,n={}){let o=xo.find(c=>c.definition.function.name===t);if(!o)return null;let s=await ic("beforeToolExec",{name:t,args:e,options:n}),r=await o.handler(s.args||e,n);return(await ic("afterToolExec",{name:t,args:e,result:r})).result||r}function $0(){return[...ni]}function y0(){let t={};for(let e of vo)t[e]=(es[e]||[]).length;return t}function w0(){ni.length=0,xo.length=0;for(let t of Object.keys(es))delete es[t]}tf.exports={registerTool:Qd,registerHook:ef,emit:ic,loadPlugins:m0,getPluginToolDefinitions:h0,executePluginTool:g0,getLoadedPlugins:$0,getHookCounts:y0,clearPlugins:w0,EVENTS:vo}});var ac=Q((qT,rf)=>{var{getSkillToolDefinitions:b0}=Mn(),{getMCPToolDefinitions:_0}=ti(),{getPluginToolDefinitions:x0}=si(),oi=new Map;function nf(){let{TOOL_DEFINITIONS:t}=Gt();return[...t,...b0(),..._0(),...x0()]}function sf(t){if(oi.has(t))return oi.get(t);let n=nf().find(s=>s.function.name===t);if(!n)return null;let o=n.function.parameters;return oi.set(t,o),o}function v0(){oi.clear()}function ri(t,e){if(!t||e.length===0)return null;let n=null,o=1/0;for(let s of e){let r=of(t.toLowerCase(),s.toLowerCase());r<o&&(o=r,n=s)}return o<=Math.ceil(t.length/2)?n:null}function of(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 k0(t,e){let n=sf(t);if(n===null){let f=nf().map(h=>h.function.name),p=ri(t,f);return{valid:!1,error:`Unknown tool "${t}".${p?` Did you mean "${p}"?`:""}
|
|
100
|
+
Available tools: ${f.join(", ")}`}}if(!n||!n.properties)return{valid:!0};let 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=ri(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=ri(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 S0(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}}
|
|
104
|
+
Expected parameters: ${JSON.stringify(n.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}function S0(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}}rf.exports={validateToolArgs:k0,validateToolCallFormat:S0,closestMatch:ri,levenshtein:of,getCachedSchema:sf,clearSchemaCache:v0}});var uf=Q((FT,lf)=>{var{levenshtein:ii}=ac(),E0=200,T0=.3,R0=2;function cc(t){return t.replace(/\r\n/g,`
|
|
105
105
|
`).replace(/\r/g,`
|
|
106
106
|
`).replace(/\t/g," ".repeat(R0)).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 C0(t,e){if(t.includes(e))return e;if(e.length<10)return null;let n=
|
|
108
|
+
`)}function C0(t,e){if(t.includes(e))return e;if(e.length<10)return null;let n=cc(t),o=cc(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
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 A0(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?O0(n,e):M0(n,e,s)}function
|
|
115
|
-
`),u=
|
|
116
|
-
`),h=
|
|
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 L0)l.regex.test(i)&&o.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of I0)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 D0(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}
|
|
118
|
-
`).filter(Boolean),
|
|
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
|
|
114
|
+
`).length;return n.length===0||s===0?null:s===1?O0(n,e):M0(n,e,s)}function af(t){return Math.max(1,Math.floor(t/E0))}function cf(t,e){return t<=Math.ceil(e*T0)}function O0(t,e){let n=e.trim(),o=af(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=ii(c.trim(),n);l<r&&(r=l,s={text:c,distance:l,line:i+1})}return s&&o>1&&(s=N0(t,n,s,o)||s,r=s.distance),cf(r,e.length)?s:null}function N0(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=ii(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function M0(t,e,n){let o=t.length-n+1;if(o<=0)return null;let s=af(o),r=null,i=1/0;for(let c=0;c<o;c+=s){let l=t.slice(c,c+n).join(`
|
|
115
|
+
`),u=ii(l,e);u<i&&(i=u,r={text:l,distance:u,line:c+1})}return r&&s>1&&(r=P0(t,e,r,s,n,o)||r,i=r.distance),cf(i,e.length)?r:null}function P0(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=ii(p,e);h<u&&(u=h,d={text:p,distance:h,line:f+1})}return d}lf.exports={normalizeWhitespace:cc,fuzzyFindText:C0,findMostSimilar:A0}});var ff=Q((BT,df)=>{var{C:UT}=Fe(),L0=[{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}],I0=[{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 j0(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 L0)l.regex.test(i)&&o.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of I0)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 D0(){let t=process.memoryUsage();return{rss:Math.round(t.rss/1024/1024*100)/100,heapUsed:Math.round(t.heapUsed/1024/1024*100)/100}}df.exports={runDiagnostics:j0,getMemoryUsage:D0}});var pc=Q((WT,yf)=>{var Bs=require("fs").promises,Ws=require("path"),{exec:q0}=require("util").promisify(require("child_process").exec),Hs=[],fc=null,ai=!1,uc=0,F0=6e4;function mf(t){return!(Hs.length===0||fc!==t||Date.now()-uc>F0)}async function hf(t){if(!ai&&!mf(t)){ai=!0,fc=t;try{try{let{stdout:o}=await q0("rg --files",{cwd:t,timeout:5e3});Hs=o.split(`
|
|
118
|
+
`).filter(Boolean),uc=Date.now(),ai=!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,uc=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{ai=!1}}}function dc(){return Hs}function U0(){return fc}function B0(t){return Hs.filter(e=>Ws.basename(e)===t)}function W0(t){let e=t.toLowerCase();return Hs.filter(n=>n.toLowerCase().includes(e)).slice(0,20)}var lc=null,pf=0,H0=12e4,K0=new Set([".js",".ts",".jsx",".tsx",".mjs",".cjs",".py",".go",".rs",".java",".rb"]);function gf(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 $f(t){t=t||process.cwd();let e=Ws.join(t,".nex","index","content-index.json"),n={};if(lc&&Date.now()-pf<H0)return lc;try{let i=await Bs.readFile(e,"utf-8");n=JSON.parse(i)}catch{n={files:{}}}dc().length===0&&await hf(t);let s={files:{}},r=!1;for(let i of dc()){let c=Ws.extname(i);if(!K0.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=gf(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 lc=s,pf=Date.now(),s}async function G0(t,e){let n=await $f(),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)}yf.exports={refreshIndex:hf,getFileIndex:dc,getIndexedCwd:U0,findFileInIndex:B0,searchIndex:W0,isIndexValid:mf,buildContentIndex:$f,searchContentIndex:G0,extractDefinitions:gf}});var Ks=Q((HT,xf)=>{var ci=require("fs"),ui=require("path"),di=require("os"),{execFile:Y0}=require("child_process"),{promisify:z0}=require("util"),mc=z0(Y0),X0=ui.join(di.homedir(),".nex","servers.json"),li=ui.join(di.tmpdir(),"nex-ssh-sockets");function J0(){return ui.join(process.cwd(),".nex","servers.json")}function wf(){let t=o=>{if(!ci.existsSync(o))return{};try{return JSON.parse(ci.readFileSync(o,"utf-8"))}catch{return{}}},e=t(X0),n=t(J0());return{...e,...n}}function V0(t){let e=wf();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 Z0(){ci.existsSync(li)||ci.mkdirSync(li,{recursive:!0})}function bf(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,di.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),Z0();let n=t.user?`${t.user}@${t.host}`:t.host,o=ui.join(li,n.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${o}`,"-o","ControlPersist=120"),e.push(n),{args:e,target:n}}function _f(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,di.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Q0(t,e,{timeout:n=3e4,sudo:o=!1}={}){let{args:s}=bf(t),r=o&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:c}=await mc("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:fi(l,t)}}}async function eb(t,e,n,{timeout:o=12e4}={}){let s=_f(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(e,`${r}:${n}`);try{let{stdout:i,stderr:c}=await mc("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(fi(c,t)||c)}}async function tb(t,e,n,{timeout:o=12e4}={}){let s=_f(t),r=t.user?`${t.user}@${t.host}`:t.host;s.push(`${r}:${e}`,n);try{let{stdout:i,stderr:c}=await mc("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(fi(c,t)||c)}}function fi(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 nb(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}`}
|
|
126
|
-
`,"utf-8")}
|
|
125
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function nb(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}`}xf.exports={loadServerProfiles:wf,resolveProfile:V0,buildSSHArgs:bf,sshExec:Q0,scpUpload:eb,scpDownload:tb,enrichSSHError:fi,formatProfile:nb,SSH_SOCKET_DIR:li}});var $c=Q((KT,kf)=>{var ko=require("fs"),hc=require("path"),sb=hc.join(".nex","deploy.json");function gc(){return hc.join(process.cwd(),sb)}function vf(){let t=gc();if(!ko.existsSync(t))return{};try{return JSON.parse(ko.readFileSync(t,"utf-8"))}catch{return{}}}function ob(t){let e=vf();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 rb(t){let e=hc.join(process.cwd(),".nex");ko.existsSync(e)||ko.mkdirSync(e,{recursive:!0}),ko.writeFileSync(gc(),JSON.stringify(t,null,2)+`
|
|
126
|
+
`,"utf-8")}kf.exports={loadDeployConfigs:vf,resolveDeployConfig:ob,saveDeployConfigs:rb,getDeployConfigPath:gc}});var Ro=Q((GT,Tf)=>{var{getActiveModel:ib,getActiveProviderName:ab}=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"},an={};function Ef(){try{let t=require("fs"),n=require("path").join(process.cwd(),".nex","config.json");t.existsSync(n)&&(an=JSON.parse(t.readFileSync(n,"utf-8")).toolTiers||{})}catch{an={}}}Ef();function yc(){let e=ib()?.id,n=ab();return e&&an[e]?an[e]:n&&an[`${n}:*`]?an[`${n}:*`]:e&&Eo[e]?Eo[e]:n&&To[n]?To[n]:"full"}var cb=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"]),Sf={anthropic:"strict",openai:"strict",gemini:"strict",ollama:"fuzzy",local:"fuzzy"};function lb(t,e){return t&&(cb.has(t)||t.startsWith("claude-"))?"strict":e&&Sf[e]?Sf[e]:"fuzzy"}function ub(t,e){return t&&an[t]?an[t]:e&&an[`${e}:*`]?an[`${e}:*`]:t&&Eo[t]?Eo[t]:e&&To[e]?To[e]:"full"}function db(t,e){let n=e||yc();if(n==="full"||!So[n])return t;let o=new Set(So[n]);return t.filter(s=>o.has(s.function.name))}function fb(){let t=yc(),e=So[t]?So[t].length:"all";return{tier:t,toolCount:e}}Tf.exports={filterToolsForModel:db,getActiveTier:yc,getModelTier:ub,getEditMode:lb,getTierInfo:fb,TIERS:So,MODEL_TIERS:Eo,PROVIDER_DEFAULT_TIER:To,loadConfigOverrides:Ef}});var Ao=Q((YT,Af)=>{var wc=null,bn=null,Co=null,Rf=`Playwright is not installed. Install with:
|
|
127
127
|
npm install playwright && npx playwright install chromium
|
|
128
|
-
Then restart nex-code.`;function
|
|
129
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await s.close()}}async function hb(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await
|
|
130
|
-
`)}function Sb(){return gt.length>0&>.some(t=>t.status==="pending"||t.status==="in_progress")}
|
|
128
|
+
Then restart nex-code.`;function Cf(){if(Co!==null)return Co;try{require("playwright"),Co=!0}catch{Co=!1}return Co}async function pi(){if(!Cf())throw new Error(Rf);return wc||(wc=require("playwright")),(!bn||!bn.isConnected())&&(bn=await wc.chromium.launch({headless:!0})),bn}async function pb(){if(bn){try{await bn.close()}catch{}bn=null}}process.on("exit",()=>{if(bn)try{bn.close()}catch{}});async function mb(t,{timeout:e=3e4,waitFor:n="domcontentloaded"}={}){let s=await(await pi()).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 hb(t,{width:e=1280,height:n=800,fullPage:o=!1,timeout:s=3e4}={}){let i=await(await pi()).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 gb(t,{selector:e,text:n,timeout:o=3e4}={}){if(!e&&!n)throw new Error("selector or text is required");let r=await(await pi()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout: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 $b(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 pi()).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()}}Af.exports={isPlaywrightAvailable:Cf,browserNavigate:mb,browserScreenshot:hb,browserClick:gb,browserFill:$b,closeBrowser:pb,INSTALL_MSG:Rf}});var mi=Q((zT,Of)=>{var{C:Be}=Fe(),No="",gt=[],Oo=0,ts=null;function yb(t){ts=t}function wb(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 bb(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 _b(){return{name:No,tasks:gt.map(t=>({...t}))}}function xb(){No="",gt=[],Oo=0,ts&&ts("clear",{})}function vb(){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 kb(){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 Sb(){return gt.length>0&>.some(t=>t.status==="pending"||t.status==="in_progress")}Of.exports={createTasks:wb,updateTask:bb,getTaskList:_b,clearTasks:xb,getReadyTasks:vb,renderTaskList:kb,setOnChange:yb,hasActiveTasks:Sb}});var hi=Q((XT,Mf)=>{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.`}},
|
|
143
|
+
You handle complex multi-step tasks well \u2014 don't cut corners prematurely.`}},Nf={staleWarn:6e4,staleAbort:12e4,investigationCap:12,postEditCap:10};function Eb(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]}:{...Nf};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 Tb(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||""}Mf.exports={getModelProfile:Eb,getModelBriefing:Tb,PROFILES:Mo,DEFAULTS:Nf}});var qf=Q((JT,Df)=>{var{callChat:Rb}=je(),{estimateTokens:bc}=Rt(),Pf=process.env.NEX_COMPACTION!=="false",Lf=6,If=500,Cb=`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 Ab(t){if(!
|
|
149
|
-
${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:s-r}}catch{return null}}function
|
|
148
|
+
Be factual and brief. Use bullet points. Max 300 words.`;async function Ab(t){if(!Pf||t.length<Lf)return null;let e=[{role:"system",content:Cb},{role:"user",content:jf(t)}];try{let o=((await Rb(e,[],{temperature:0,maxTokens:If})).content||"").trim();if(!o)return null;let s=t.reduce((i,c)=>i+bc(c.content||"")+(c.tool_calls?bc(JSON.stringify(c.tool_calls)):0),0),r=bc(o);return r>=s*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
149
|
+
${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:s-r}}catch{return null}}function jf(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
|
-
`)}
|
|
152
|
+
`)}Df.exports={compactMessages:Ab,formatMessagesForSummary:jf,COMPACTION_ENABLED:Pf,COMPACTION_MIN_MESSAGES:Lf,COMPACTION_SUMMARY_BUDGET:If}});var Rt=Q((VT,Xf)=>{var Ob=require("path");function Uf(){return je().getActiveModel()}var Nb={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},Mb={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,Ff=1e3,_c=new WeakMap,ss=null;function Pb(){if(ss!==null)return ss;try{let t=Uf(),e=t?.provider||"ollama",n=(t?.id||"").toLowerCase();for(let[o,s]of Object.entries(Mb))if(n.startsWith(o))return ss=s,ss;return ss=Nb[e]||4,ss}catch{return 4}}function Lb(){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/Pb());if(ns.size>=Ff){let s=Ff>>1,r=ns.keys();for(let i=0;i<s;i++)ns.delete(r.next().value)}return ns.set(e,o),o}function Ib(t){if(_c.has(t))return _c.get(t);let e=JSON.stringify(t);return _c.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 jb(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 gi(t){return!t||t.length===0?0:os(JSON.stringify(t))}function $i(){return Uf()?.contextWindow||32768}function Db(t,e){let n=qt(t),o=gi(e),s=n+o,r=$i(),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,Bf=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,Wf=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Hf={essential:.6,standard:.7,full:Po};function Kf(){if(process.env.NEX_COMPRESSION_THRESHOLD)return Po;try{let{getActiveTier:t}=Ro(),e=t();return Hf[e]??Po}catch{return Po}}var qb=200,Fb=1e3;function Gf(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:Fb,o=e==="aggressive"?50:e==="medium"?100:qb;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:
|
|
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
|
|
159
|
+
`)}function Ys(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:Fb,o=e==="aggressive"?50:e==="medium"?100:qb;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:Gf(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 Yf(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(Ob.basename(l)))&&c++;s+=Math.min(30,c*10)}return Math.min(100,s)}function zf(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 Ub(){Gs={msgCount:-1,lastMsgRef:null,result:null}}async function Bb(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??Kf(),r=n.safetyMargin??Bf,i=n.keepRecent??Wf,c=$i(),l=gi(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}=qf(),B=await X(M);if(B){let $e=[...w.filter(pe=>pe._compacted),B.message],be=Pn(m,$e,v),fe=qt(be);if(fe+l<=u)return{messages:be,compressed:!0,compacted:!0,tokensRemoved:h-fe};w=$e}}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=zf([...S,...v]),V=S.map((X,B)=>({msg:X,score:Yf(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 Wb(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 Hb=6;function Kb(t,e,n=!1){let o
|
|
167
|
+
`;return c+p+u}var Hb=6;function Kb(t,e,n=!1){let o=$i(),s=gi(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:Hb,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)}}Xf.exports={estimateTokens:os,estimateMessageTokens:zs,estimateMessagesTokens:qt,estimateDeltaTokens:jb,estimateToolsTokens:gi,serializeMessage:Ib,getContextWindow:$i,getUsage:Db,compressMessage:Ys,compressToolResult:Gf,scoreMessageRelevance:Yf,extractActiveFiles:zf,fitToContext:Bb,forceCompress:Kb,truncateFileContent:Wb,invalidateTokenRatioCache:Lb,invalidateFitToContextCache:Ub,getEffectiveCompressionThreshold:Kf,COMPRESSION_THRESHOLD:Po,TIER_COMPRESSION_THRESHOLDS:Hf,SAFETY_MARGIN:Bf,KEEP_RECENT:Wf}});var _i=Q((QT,$p)=>{var{callStream:Gb,getActiveProviderName:wi,getActiveModelId:Jf,getConfiguredProviders:Yb,getProvider:Vf,getActiveProvider:Zf,parseModelSpec:Qf}=je(),{parseToolArgs:ep}=Fs(),{filterToolsForModel:zb,getModelTier:yi}=Ro(),{getModelBriefing:Xb}=hi(),{trackUsage:tp,estimateTokens:np}=qs(),{MultiProgress:Jb,C:ZT}=Fe();function sp(t){return!t||typeof t!="string"?0:typeof np=="function"?np(t):Math.ceil(t.length/4)}var ip=15,Vb=5,op=3,ap=8,Zb=2,bi=new Map,cp=600*1e3;function Qb(t,e){let n=bi.get(t);return n&&n.agentId!==e&&Date.now()-n.timestamp<cp?!1:(bi.set(t,{agentId:e,timestamp:Date.now()}),!0)}function Lo(t){bi.delete(t)}function xc(){bi.clear()}function vc(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":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 lp(t){let e=vc(t);return e==="rate_limit"||e==="server"||e==="network"}async function up(t,e,n){let o;for(let s=0;s<=op;s++)try{return await Gb(t,e,n)}catch(r){o=r;let i=vc(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<op&&lp(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 rp=new Set(["ask_user","task_list"]);function dp(t){return t>=2?new Set([...rp,"spawn_agents"]):rp}var e_=new Set(["write_file","edit_file","patch_file"]),fp={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:""}},t_=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,n_=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function pp(t){return n_.test(t)?"full":t_.test(t)?"essential":t.length>300?"full":"standard"}function mp(t){let e=Yb(),n=wi(),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(yi(r.id,s.name)===t)return{provider:s.name,model:r.id};return null}var s_={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function kc(t){if(t.model){let{provider:s,model:r}=Qf(t.model),i=s?Vf(s):Zf(),c=s||wi();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=yi(r,c);return{provider:c,model:r,tier:l}}}let e=pp(t.task),n=s_[e];if(n){let{provider:s,model:r}=Qf(n),i=s?Vf(s):Zf(),c=s||wi();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=yi(r,c);return{provider:c,model:r,tier:l}}}let o=mp(e);if(o){let s=yi(o.model,o.provider);return{provider:o.provider,model:o.model,tier:s}}return{provider:null,model:null,tier:null}}async function hp(t,e={},n=0){let o=n===0?ip:ap,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?`
|
|
@@ -186,25 +186,25 @@ TOOL STRATEGY:
|
|
|
186
186
|
ERROR RECOVERY:
|
|
187
187
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
188
188
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
189
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`,f=t.type&&
|
|
189
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`,f=t.type&&fp[t.type],p=f&&f.systemSuffix?`
|
|
190
190
|
|
|
191
|
-
${f.systemSuffix}`:"",h=
|
|
191
|
+
${f.systemSuffix}`:"",h=kc(t),m=h.provider,g=h.model,y=h.tier,w=Xb(g||Jf()),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=
|
|
197
|
-
`)}let K={};m&&(K.provider=m),g&&(K.model=g);try{for(let X=0;X<s;X++){let B=await
|
|
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}))}),pe=await Promise.all(fe);if(M.push(...pe),X>=7&&M.length>12)try{let{compressMessage:xe}=Rt(),me=M.length-6;for(let he=1;he<me;he++)M[he]._subAgentCompressed||(M[he]={...xe(M[he],"light"),_subAgentCompressed:!0})}catch{}for(let xe=0;xe<$e.length;xe++){let me=$e[xe];if(me.function.name==="bash_exec"){let he=
|
|
199
|
-
`)}catch(d){return u.stop(),
|
|
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
|
|
201
|
-
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of
|
|
196
|
+
`:"")+d+p}];M.push({role:"user",content:t.task});let{TOOL_DEFINITIONS:C,executeTool:S}=Gt(),O=dp(n),D=zb(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 up(M,D,K);if(!B||typeof B!="object")throw new Error("Empty or invalid response from provider");{let xe=m||wi(),me=g||Jf();if(B.usage){let he=B.usage.prompt_tokens||0,Re=B.usage.completion_tokens||0;c.input+=he,c.output+=Re,tp(xe,me,he,Re)}else{let he=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=sp(Re),j=sp(he);c.input+=k,c.output+=j,c._estimated=!0,tp(xe,me,k,j)}}let R=B.content||"",$e=B.tool_calls,be={role:"assistant",content:R||""};if($e&&$e.length>0&&(be.tool_calls=$e),M.push(be),!$e||$e.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 fe=$e.map(xe=>{let me=xe.function.name,he=ep(xe.function.arguments),Re=xe.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!he)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${me}`,tool_call_id:Re});let k=null;if(e_.has(me)&&he.path){let x=require("path"),E=x.isAbsolute(he.path)?he.path:x.resolve(process.cwd(),he.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 '${he.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)||!Qb(E,r))return Promise.resolve({role:"tool",content:`ERROR: File '${he.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(me),e.onUpdate&&e.onUpdate({type:"tool_call",tool:me,agentId:r}),(me==="spawn_agents"?gp(he,n+1):S(me,he,{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}))}),pe=await Promise.all(fe);if(M.push(...pe),X>=7&&M.length>12)try{let{compressMessage:xe}=Rt(),me=M.length-6;for(let he=1;he<me;he++)M[he]._subAgentCompressed||(M[he]={...xe(M[he],"light"),_subAgentCompressed:!0})}catch{}for(let xe=0;xe<$e.length;xe++){let me=$e[xe];if(me.function.name==="bash_exec"){let he=ep(me.function.arguments);if((pe[xe]?.content||"").startsWith("ERROR")&&he&&he.command){let k=he.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 gp(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?Vb:Zb,o=e===0?ip:ap,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=>kc(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 Jb(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 hp(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(),xc();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(),xc(),`ERROR: Sub-agent execution failed: ${d.message}`}}$p.exports={runSubAgent:hp,executeSpawnAgents:gp,clearAllLocks:xc,classifyTask:pp,pickModelForTier:mp,resolveSubAgentModel:kc,classifyError:vc,isRetryableError:lp,callWithRetry:up,getExcludedTools:dp,LOCK_TIMEOUT_MS:cp,SUB_AGENT_TYPES:fp}});var Do=Q((eR,Op)=>{var Ye=require("fs"),_n=require("path"),{atomicWrite:yp,withFileLockSync:wp}=An(),o_=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 vi(){return _n.join(Js(),".brain-index.json")}function Tc(){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 bp(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 r_(t,e){let n=_n.join(Js(),`${t}.md`);yp(n,e),c_(t,e),i_()}function i_(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Tc();Ye.existsSync(t)&&setImmediate(async()=>{try{await Tp()}catch{}})}function a_(t){let e=_n.join(Js(),`${t}.md`);return Ye.existsSync(e)?(Ye.unlinkSync(e),l_(t),!0):!1}function xi(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!o_.has(e))}function Rc(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 xi(c))e[l]=(e[l]||0)+3}for(let i of xi(o||t))e[i]=(e[i]||0)+1;return e}function Cc(){let t=vi();if(!Ye.existsSync(t))return{documents:{}};try{return JSON.parse(Ye.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Ac(t){yp(vi(),JSON.stringify(t,null,2))}function c_(t,e){wp(vi(),()=>{let n=Cc(),{frontmatter:o}=jo(e),s=Array.isArray(o.tags)?o.tags:[];n.documents[t]={keywords:Rc(e),tags:s,modified:new Date().toISOString()},Ac(n)})}function l_(t){wp(vi(),()=>{let e=Cc();delete e.documents[t],Ac(e)})}function Ec(){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:Rc(o),tags:r,modified:n.modified.toISOString()}}return Ac(e),e}function _p(){let t=Cc(),e=Io();for(let n of e){let o=t.documents[n.name];if(!o||new Date(o.modified)<n.modified)return Ec()}for(let n of Object.keys(t.documents))if(!e.some(o=>o.name===n))return Ec();return t}function xp(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=xi(t);if(s.length===0)return[];let r=_p(),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 vp=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Sc=400,u_=50;async function kp(){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(vp.split(":")[0]))}catch{return!1}}async function Oc(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:vp,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 Sp(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 Ep(t){let e=t.split(/\s+/),n=[],o=0;for(;o<e.length;){let s=e.slice(o,o+Sc).join(" ");if(n.push({text:s,offset:o}),o+Sc>=e.length)break;o+=Sc-u_}return n}async function Tp(){let t=Io(),e={documents:{}},n=Tc();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=Ep(r),c=[];for(let l of i){let u=await Oc(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 Rp(t,e={}){let{topK:n=3,minSimilarity:o=.3}=e,s=Tc();if(!Ye.existsSync(s))return[];let r;try{r=JSON.parse(Ye.readFileSync(s,"utf-8"))}catch{return[]}let i=await Oc(t),c=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,f="";for(let p of u.chunks||[]){let h=Sp(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 Cp(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 Ap(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=xp(t,{topK:n,minScore:o}),r=s;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await kp()){let c=await Rp(t,{topK:n});r=Cp(s,c,{topK:n})}}catch{}return r.map(i=>{let c=bp(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},d_=3e5;async function f_(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<d_)return Xs.result;let s;try{s=await Ap(t,{topK:3})}catch{return""}if(!s||s.length===0)return"";let r;try{r=Rt().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}
|
|
207
|
+
`)}`;return Xs={queryKey:o,result:u,ts:Date.now()},u}Op.exports={getBrainDir:Js,listDocuments:Io,readDocument:bp,writeDocument:r_,removeDocument:a_,buildIndex:Ec,getIndex:_p,query:Ap,getBrainContext:f_,isEmbeddingAvailable:kp,generateEmbedding:Oc,buildEmbeddingIndex:Tp,semanticQuery:Rp,cosineSimilarity:Sp,_keywordQuery:xp,_extractKeywords:Rc,_chunkText:Ep,parseFrontmatter:jo,tokenize:xi,_fuseResults:Cp}});var cn=Q((tR,Wp)=>{var Ke=require("fs"),Ct=require("path"),p_=require("os"),{atomicWrite:ki,withFileLockSync:Np}=An(),qo=["user","feedback","project","reference"],m_=50;function rs(){return Ct.join(process.cwd(),".nex","memory")}function Vs(){return Ct.join(rs(),"memory.json")}function Mp(){return Ct.join(rs(),"MEMORY.md")}function h_(){return Ct.join(process.cwd(),"NEX.md")}function Pp(){return Ct.join(p_.homedir(),".nex","NEX.md")}function Si(){let t=rs();Ke.existsSync(t)||Ke.mkdirSync(t,{recursive:!0})}function Lp(t){let e=Ct.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 Ip(t){Si(),ki(Vs(),JSON.stringify(t,null,2))}function jp(){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=Lp("project"),l=Ct.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
|
-
`;
|
|
215
|
+
`;ki(l,d)}Ei();try{Ke.renameSync(t,t+".bak")}catch{}}function g_(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=Lp(t),i=Ct.join(r,`${s}.md`);if(Ke.existsSync(i))try{if(Nc(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,11 +220,11 @@ type: ${t}
|
|
|
220
220
|
---
|
|
221
221
|
|
|
222
222
|
${n}
|
|
223
|
-
`;return
|
|
223
|
+
`;return ki(i,l),Ei(),{ok:!0,path:i,updated:!0}}function $_(t,e){if(!qo.includes(t))return!1;let n=e.replace(/[^a-z0-9_-]/gi,"-").toLowerCase(),o=Ct.join(rs(),t,`${n}.md`);if(!Ke.existsSync(o))return!1;try{return Ke.unlinkSync(o),Ei(),!0}catch{return!1}}function Nc(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 Dp(){let t=[],e=rs();for(let n of qo){let o=Ct.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=Ct.join(o,r);try{let c=Ke.readFileSync(i,"utf-8"),l=Nc(c);t.push({type:n,name:l.name||Ct.basename(r,".md"),description:l.description,filePath:i})}catch{}}}return t}function Ei(){let t=Dp(),e=["# Project Memory Index",""];for(let n of t){if(e.length>=m_+2)break;let o=`${n.type}/${Ct.basename(n.filePath)}`;e.push(`- [${n.name}](${o}) \u2014 ${n.description||"(no description)"}`)}Si(),ki(Mp(),e.join(`
|
|
224
224
|
`)+`
|
|
225
|
-
`)}function
|
|
226
|
-
${e}`);let n=
|
|
227
|
-
${n}`);let o="",s=
|
|
225
|
+
`)}function qp(){let t=Mp();if(!Ke.existsSync(t))return"";try{return Ke.readFileSync(t,"utf-8").trim()}catch{return""}}function y_(t,e){Si(),Np(Vs(),()=>{let n=Fo();n[t]={value:e,updatedAt:new Date().toISOString()},Ip(n)})}function w_(t){let e=Fo();return e[t]?e[t].value:null}function b_(t){return Si(),Np(Vs(),()=>{let e=Fo();return t in e?(delete e[t],Ip(e),!0):!1})}function Fp(){let t=Fo();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function Up(){let t=Pp();if(!Ke.existsSync(t))return"";try{return Ke.readFileSync(t,"utf-8").trim()}catch{return""}}function Bp(){let t=h_();if(!Ke.existsSync(t))return"";try{return Ke.readFileSync(t,"utf-8").trim()}catch{return""}}function __(){jp();let t=[],e=Up();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
226
|
+
${e}`);let n=Bp();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
227
|
+
${n}`);let o="",s=qp();if(s)o=s;else{let f=Fp();f.length>0&&(o=`PROJECT MEMORY:
|
|
228
228
|
${f.map(h=>` ${h.key}: ${h.value}`).join(`
|
|
229
229
|
`)}`)}let r=t.join(`
|
|
230
230
|
|
|
@@ -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
|
-
`)}
|
|
237
|
-
`;Uo.appendFileSync(
|
|
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 v_(t=1){let e=
|
|
236
|
+
`)}Wp.exports={saveMemory:g_,deleteMemory:$_,scanMemories:Dp,rebuildIndex:Ei,loadMemoryIndex:qp,remember:y_,recall:w_,forget:b_,listMemories:Fp,loadGlobalInstructions:Up,loadProjectInstructions:Bp,getMemoryContext:__,_getMemoryDir:rs,_getMemoryFile:Vs,_getGlobalNexMdPath:Pp,_parseMemoryFile:Nc,_migrateIfNeeded:jp,VALID_TYPES:qo}});var Lc=Q((nR,zp)=>{var Uo=require("fs"),Mc=require("path"),Pc=process.env.NEX_AUDIT!=="false",is=null;function Hp(){return is||(is=Mc.join(process.cwd(),".nex","audit"),Uo.existsSync(is)||Uo.mkdirSync(is,{recursive:!0}),is)}function Kp(){let t=new Date().toISOString().split("T")[0];return Mc.join(Hp(),`${t}.jsonl`)}function x_(t){if(Pc)try{let e={timestamp:new Date().toISOString(),tool:t.tool,args:Gp(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
|
+
`;Uo.appendFileSync(Kp(),n,"utf-8")}catch{}}function Gp(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 Yp(t={}){let e=Hp(),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=Mc.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 v_(t=1){let e=Yp({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 k_(t){Pc=t}function S_(){return Pc}function E_(){is=null}zp.exports={logToolExecution:x_,sanitizeArgs:Gp,readAuditLog:Yp,getAuditSummary:v_,setAuditEnabled:k_,isAuditEnabled:S_,getAuditLogPath:Kp,_reset:E_}});var rm=Q((rR,om)=>{var ze=require("fs").promises,Xp=require("fs"),Ie=require("path"),De=require("util").promisify(require("child_process").exec),Ic=require("util").promisify(require("child_process").execFile),{spawnSync:T_}=require("child_process"),jc=require("axios"),{isForbidden:R_,isSSHForbidden:C_,isDangerous:A_,isCritical:Jp,isBashPathForbidden:O_,confirm:Yt}=ft(),{showClaudeDiff:Ti,showClaudeNewFile:N_,showEditDiff:sR,confirmFileChange:Bo}=Ad(),{C:de,Spinner:M_,getToolSpinnerText:P_}=Fe(),{isGitRepo:Dc,getCurrentBranch:Vp,getStatus:L_,getDiff:I_}=Nn(),{recordChange:Ri}=yn(),{fuzzyFindText:Zp,findMostSimilar:Ko}=uf(),{runDiagnostics:Wo}=ff(),{findFileInIndex:j_,getFileIndex:oR}=pc(),{resolveProfile:Ft,sshExec:xt,scpUpload:D_,scpDownload:q_}=Ks(),{resolveDeployConfig:F_,loadDeployConfigs:U_}=$c(),{getEditMode:Qp}=Ro(),B_=/^(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/,W_=/^ssh\s/,H_=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function At(t){return ze.access(t).then(()=>!0).catch(()=>!1)}async function Ci(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),n=vt(e);if(n&&await At(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 At(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 At(l))return{fixedPath:l,message:`(auto-fixed: ${s} \u2192 ${c})`}}}let r=Ie.basename(t);if(r&&r.length>2)try{let i=j_(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 K_(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
|
|
240
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function K_(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 nm(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 nm(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 Qp=!1,as=null;function G_(){as&&(as(),as=null)}var qc=null;function Y_(t){qc=t}async function Dc(){if(!Qp){Qp=!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 z_=[/\.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 z_)if(n.test(e))return null;return e}var X_=[{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 em(t,e,n={}){switch(t){case"bash":{let o=e.command,s=R_(o);if(s){let f=K_(o);return`BLOCKED: Command matches forbidden pattern: ${s}${f?`
|
|
243
|
+
`)}function sm(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 em=!1,as=null;function G_(){as&&(as(),as=null)}var Fc=null;function Y_(t){Fc=t}async function qc(){if(!em){em=!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 z_=[/\.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 z_)if(n.test(e))return null;return e}var X_=[{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 tm(t,e,n={}){switch(t){case"bash":{let o=e.command,s=R_(o);if(s){let f=K_(o);return`BLOCKED: Command matches forbidden pattern: ${s}${f?`
|
|
244
244
|
HINT: ${f}`:""}`}let r=O_(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?
|
|
246
|
-
${h}`}}case"read_file":{let o=vt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await At(o)){let O=await
|
|
247
|
-
`+O.message:""}`}let r=Buffer.alloc(8192),i=await
|
|
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?Jp(o):A_(o)){let f=Jp(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(),Xp.accessSync(c)}catch{c=require("os").homedir(),n.silent||console.log(`${de.yellow} \u26A0 Working directory no longer exists \u2014 running in ${c}${de.reset}`)}let l=W_.test(o.trim())&&!H_.test(o.trim());if(B_.test(o.trim())||l){n.silent||console.log(`${de.dim} \u25B6 interactive: ${o}${de.reset}`);let f=T_("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=nm(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 At(o)){let O=await Ci(e.path);if(O.fixedPath)o=O.fixedPath,console.log(`${de.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ie.relative(process.cwd(),o)}${de.reset}`);else return`ERROR: File not found: ${e.path}${O.message?`
|
|
247
|
+
`+O.message:""}`}let r=Buffer.alloc(8192),i=await Xp.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
|
|
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(
|
|
253
|
+
${C}${S}`}case"write_file":{await qc();let o=vt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=await At(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(Ti(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(N_(o,e.content,{annotations:d}),!await Bo("Create"))return"CANCELLED: User declined to create file."}let i=Ie.dirname(o);await At(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),Ri("write_file",o,r,e.content);let u=l?" [chmod +x applied]":"";return`Written: ${o} (${e.content.length} chars)${u}`}case"edit_file":{await qc();let o=vt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await At(o)){let d=await Ci(e.path);if(d.fixedPath)o=d.fixedPath,console.log(`${de.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ie.relative(process.cwd(),o)}${de.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
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(Qp(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=
|
|
256
|
+
${m.text}`:`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)`}let h=Zp(r,e.old_text);if(h)i=h,c=!0,console.log(`${de.dim} \u2713 fuzzy whitespace match applied${de.reset}`);else{let m=sm(r,e.old_text,e.new_text);if(m){if(!n.autoConfirm){let M=await Wo(o,m.content);if(Ti(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),Ri("edit_file",o,r,m.content);let v=m.matchText.length>80?m.matchText.substring(0,77)+"...":m.matchText;return console.log(`${de.dim} \u2713 auto-fixed edit: line ${m.line}, distance ${m.distance}${de.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
|
|
|
@@ -263,31 +263,31 @@ ${S}
|
|
|
263
263
|
Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${O}`}let y=(e.old_text||"").trim().split(`
|
|
264
264
|
`)[0].slice(0,60),w=y?`
|
|
265
265
|
Recovery: grep -n "${y.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
|
|
266
|
-
Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${o}${w}`}}if(!n.autoConfirm){let d=r.split(i).join(e.new_text),f=await Wo(o,d);if(
|
|
267
|
-
`)||"(empty)"}case"search_files":{let o=vt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=["-rn","--null","-H"];e.file_pattern&&s.push(`--include=${e.file_pattern}`),s.push(e.pattern,o);try{let{stdout:r}=await
|
|
266
|
+
Recovery: use grep -n to locate the text, then re-read that section with line_start/line_end.`;return`ERROR: old_text not found in ${o}${w}`}}if(!n.autoConfirm){let d=r.split(i).join(e.new_text),f=await Wo(o,d);if(Ti(o,r,d,{annotations:f}),!await Bo(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(i).join(e.new_text);return await ze.writeFile(o,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||u.startsWith("#!"))&&await ze.chmod(o,493),Ri("edit_file",o,r,u),c?`Edited: ${o} (fuzzy match)`:`Edited: ${o}`}case"list_directory":{let o=vt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await At(o)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=vt(u),f=await At(d);if(d&&f)o=d;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,i=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let c=[],l=async(u,d,f)=>{if(d>r)return;let p;try{p=await ze.readdir(u,{withFileTypes:!0})}catch{return}p=p.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of p){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let m=h.isDirectory()?"/":"";c.push(`${f}${h.name}${m}`),h.isDirectory()&&await l(Ie.join(u,h.name),d+1,f+" ")}};return await l(o,1,""),c.join(`
|
|
267
|
+
`)||"(empty)"}case"search_files":{let o=vt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=["-rn","--null","-H"];e.file_pattern&&s.push(`--include=${e.file_pattern}`),s.push(e.pattern,o);try{let{stdout:r}=await Ic("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),c=[];for(let l=0;l<i.length;l+=2){let u=i[l],d=i[l+1];if(u&&d){let f=d.split(`
|
|
268
268
|
`).filter(p=>p.trim());for(let p of f)if(c.push(`${u}:${p}`),c.length>=50)break}if(c.length>=50)break}return c.join(`
|
|
269
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?vt(e.path):s,i=e.pattern,c=K=>{let V=K.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${V}$`)},l=c(i),u=i.split("/").pop(),d=c(u),{ToolProgress:f}=Ms(),p=new f("glob","Finding files...");p.start();let{getFileIndex:h,getIndexedCwd:m,refreshIndex:g,isIndexValid:y}=
|
|
269
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?vt(e.path):s,i=e.pattern,c=K=>{let V=K.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${V}$`)},l=c(i),u=i.split("/").pop(),d=c(u),{ToolProgress:f}=Ms(),p=new f("glob","Finding files...");p.start();let{getFileIndex:h,getIndexedCwd:m,refreshIndex:g,isIndexValid:y}=pc(),w=h(),v=m();y(r)||(await g(r),w=h());let M=w.filter(K=>l.test(K)||d.test(Ie.basename(K))).map(K=>Ie.join(r,K));if(M.length===0)return p.stop(),"(no matches)";let C=await Promise.all(M.slice(0,210).map(async K=>{try{let V=await ze.stat(K);return{path:K,mtime:V.mtimeMs}}catch{return{path:K,mtime:0}}}));C.sort((K,V)=>V.mtime-K.mtime);let S=C.map(K=>K.path),O=M.length>200,D=S.slice(0,200).join(`
|
|
270
270
|
`);return p.update({count:M.length,detail:e.pattern}),p.stop(),O?`${D}
|
|
271
271
|
|
|
272
272
|
\u26A0 Results truncated at 200. Use a more specific pattern.`:D}case"grep":{let o=e.path?vt(e.path):process.cwd();if(e.staged){let{getDiff:l}=Nn(),u=await l(!0);if(!u.trim())return"(no staged changes)";let d=new Set,f=u.split(`
|
|
273
|
-
`);for(let y of f)if(y.startsWith("diff --git")){let w=y.match(/diff --git a\/(.+) b\/(.+)/);w&&d.add(w[2])}let p=["-rn","-E","--null","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&p.push("-i"),e.include&&p.push(`--include=${e.include}`),e.type&&p.push(`--include=*.${e.type}`),e.context?p.push("-C",String(e.context)):(e.before_context&&p.push("-B",String(e.before_context)),e.after_context&&p.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?p.push("-l"):e.output_mode==="count"&&p.push("-c"),p.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:h}=Ms(),m=new h("grep","Searching staged content...");m.start();let g=[];for(let y of d)try{let w=Ie.join(process.cwd(),y);if(await At(w)){let v=[...p];v.push(e.pattern,w);let{stdout:M}=await
|
|
273
|
+
`);for(let y of f)if(y.startsWith("diff --git")){let w=y.match(/diff --git a\/(.+) b\/(.+)/);w&&d.add(w[2])}let p=["-rn","-E","--null","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&p.push("-i"),e.include&&p.push(`--include=${e.include}`),e.type&&p.push(`--include=*.${e.type}`),e.context?p.push("-C",String(e.context)):(e.before_context&&p.push("-B",String(e.before_context)),e.after_context&&p.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?p.push("-l"):e.output_mode==="count"&&p.push("-c"),p.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:h}=Ms(),m=new h("grep","Searching staged content...");m.start();let g=[];for(let y of d)try{let w=Ie.join(process.cwd(),y);if(await At(w)){let v=[...p];v.push(e.pattern,w);let{stdout:M}=await Ic("grep",v,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let C=M.trim().split(`
|
|
274
274
|
`).filter(S=>S.trim());g=g.concat(C)}else{let C=M.split("\0");for(let S=0;S<C.length;S+=2){let O=C[S+1];if(O){let D=O.split(`
|
|
275
275
|
`).filter(K=>K.trim());for(let K of D)g.push(`${y}:${K}`)}}}}}catch{}return m.update({count:g.length,detail:"in staged files"}),m.stop(),g.join(`
|
|
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
|
|
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 Ic("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
|
|
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=
|
|
279
|
+
`).trim()||"(no matches)"}catch(l){return c.stop(),l.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await qc();let o=vt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await At(o)){let w=await Ci(e.path);if(w.fixedPath)o=w.fixedPath,console.log(`${de.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ie.relative(process.cwd(),o)}${de.reset}`);else return`ERROR: File not found: ${e.path}${w.message?`
|
|
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=Qp(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
|
-
${C.text}`:`ERROR: Patch ${w+1} old_text not found in ${o} (strict mode \u2014 exact match required)`}else{let C=
|
|
282
|
+
${C.text}`:`ERROR: Patch ${w+1} old_text not found in ${o} (strict mode \u2014 exact match required)`}else{let C=Zp(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}
|
|
283
283
|
Most similar text (line ${S.line}, distance ${S.distance}):
|
|
284
|
-
${S.text}`}else return`ERROR: Patch ${w+1} old_text not found in ${o}`}}}let h=i;for(let{old_text:w,new_text:v}of d)h=h.split(w).join(v);if(!n.autoConfirm){let w=await Wo(o,h);if(
|
|
284
|
+
${S.text}`}else return`ERROR: Patch ${w+1} old_text not found in ${o}`}}}let h=i;for(let{old_text:w,new_text:v}of d)h=h.split(w).join(v);if(!n.autoConfirm){let w=await Wo(o,h);if(Ti(o,i,h,{annotations:w}),!await Bo(f?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await ze.writeFile(o,h,"utf-8");let m=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||h.startsWith("#!");m&&await ze.chmod(o,493),Ri("patch_file",o,i,h);let g=p?" (auto-fixed)":f?" (fuzzy match)":"",y=m?" [chmod +x applied]":"";return`Patched: ${o} (${r.length} replacements)${g}${y}`}case"web_fetch":{let o=e.url,s=e.max_length||1e4;try{let r=await jc.get(o,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof r.data=="string"?r.data:JSON.stringify(r.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,s)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${o}: ${r.message}`}}case"web_search":{let o=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let s=await jc.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=s.data?.choices?.[0]?.message?.content||"",i=s.data?.citations||[],c=`[Perplexity grounded search]
|
|
285
285
|
|
|
286
286
|
${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(`${de.dim} Perplexity search failed (${s.message}), falling back to DuckDuckGo${de.reset}`)}try{let r=(await
|
|
290
|
+
`)),c}catch(s){console.error(`${de.dim} Perplexity search failed (${s.message}), falling back to DuckDuckGo${de.reset}`)}try{let r=(await jc.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?`
|
|
@@ -301,23 +301,23 @@ ${s.text}${r}`}catch(s){return`ERROR: ${s.message}`}}case"browser_screenshot":{l
|
|
|
301
301
|
Title: ${s.title}
|
|
302
302
|
URL: ${s.url}
|
|
303
303
|
|
|
304
|
-
To analyze visually, paste the path into your next message: ${s.path}`}catch(s){return`ERROR: ${s.message}`}}case"browser_click":{let{browserClick:o}=Ao();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(s){return`ERROR: ${s.message}`}}case"browser_fill":{let{browserFill:o}=Ao();try{return await o(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(s){return`ERROR: ${s.message}`}}case"ask_user":{let{question:o,options:s=[]}=e;return
|
|
304
|
+
To analyze visually, paste the path into your next message: ${s.path}`}catch(s){return`ERROR: ${s.message}`}}case"browser_click":{let{browserClick:o}=Ao();try{return await o(e.url,{selector:e.selector,text:e.text})}catch(s){return`ERROR: ${s.message}`}}case"browser_fill":{let{browserFill:o}=Ao();try{return await o(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(s){return`ERROR: ${s.message}`}}case"ask_user":{let{question:o,options:s=[]}=e;return Fc?new Promise(r=>{as=()=>r("CANCELLED"),Fc(o,s).then(i=>{as=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});as=()=>{i.close(),r("CANCELLED")};let c=s.length>0?`
|
|
305
305
|
${s.map((l,u)=>` ${u+1}. ${l}`).join(`
|
|
306
306
|
`)}
|
|
307
307
|
`:"";console.log(`
|
|
308
|
-
${de.cyan}${de.bold} ? ${o}${de.reset}${c}`),i.question(`${de.cyan} > ${de.reset}`,l=>{as=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await
|
|
308
|
+
${de.cyan}${de.bold} ? ${o}${de.reset}${c}`),i.question(`${de.cyan} > ${de.reset}`,l=>{as=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await Dc())return"ERROR: Not a git repository";let o=await Vp()||"(detached)",s=await L_();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
|
|
310
|
+
`)}case"git_diff":{if(!await Dc())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 I_(!!e.staged);return o||"(no diff)"}case"git_log":{if(!await Dc())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}=mi(),{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(`
|
|
314
314
|
`+i()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let d=r();return d.tasks.length===0?"No active tasks":(u||console.log(`
|
|
315
|
-
`+i()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:o}=
|
|
315
|
+
`+i()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:o}=_i();return o(e)}case"switch_model":{let{setActiveModel:o,getActiveProviderName:s,getActiveModelId:r}=je();return o(e.model)?`Switched to ${s()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let o=Math.min(e.limit||10,30),s=["run","list","--limit",String(o),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&s.push("--workflow",e.workflow),e.branch&&s.push("--branch",e.branch),e.status&&s.push("--status",e.status);try{let{stdout:r}=await De(`gh ${s.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let u=l.conclusion||l.status||"unknown",d=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",f=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${d} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${u} \xB7 ${f}`}).join(`
|
|
316
316
|
`)}catch(r){let i=(r.stderr||r.message||"").toString();return i.includes("not found")||i.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${i.split(`
|
|
317
317
|
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await De(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
|
|
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
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:o}=ft(),s=e.branch||await
|
|
320
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:o}=ft(),s=e.branch||await Vp()||"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
|
${de.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${s}${de.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?`
|
|
@@ -473,7 +473,7 @@ ${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}=
|
|
476
|
+
${d}`:d||"(no log entries)"}default:return`ERROR: Unknown sysadmin action: ${e.action}`}}case"save_memory":{let{saveMemory:o}=cn(),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}=cn();return o(e.type,e.name)?`Memory deleted: ${e.type}/${e.name}`:`Memory not found: ${e.type}/${e.name}`}default:{let{executePluginTool:o}=si(),s=await o(t,e,n);return s!==null?s:`ERROR: Unknown tool: ${t}`}}}async function J_(t,e,n={}){let{emit:o}=si(),{logToolExecution:s}=Lc(),r=Date.now(),i=n.silent?null:P_(t,e);if(!i){let l=await tm(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 M_(i);c.start();try{let l=await tm(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}}om.exports={TOOL_DEFINITIONS:X_,executeTool:J_,resolvePath:vt,autoFixPath:Ci,autoFixEdit:sm,enrichBashError:nm,cancelPendingAskUser:G_,setAskUserHandler:Y_,fileExists:At}});var Gt=Q((iR,im)=>{im.exports=rm()});var Bc=Q((cR,am)=>{var{loadServerProfiles:Go,resolveProfile:aR,sshExec:V_}=Ks(),Uc={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 Z_(){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&&Uc[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 Uc[s])n.push(`- ${i}`)}}return n.join(`
|
|
477
477
|
`)}function Q_(t){let e=Go();return Object.values(e).some(n=>n.os&&n.os.startsWith(t))}function ex(){return Object.keys(Go())}function tx(){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)
|
|
@@ -504,30 +504,30 @@ ${u}
|
|
|
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
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 sx(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 V_(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}}
|
|
508
|
-
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function ax(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 cx(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=$t.join(t,".gitignore"),r=[...o,...ix(s)],i=0,c=[$t.basename(t)+"/"];function l(u,d,f){if(f>e||i>=n)return;let p;try{p=
|
|
509
|
-
`)}var
|
|
507
|
+
`+i.trim()}catch{return null}}am.exports={getServerContext:Z_,getDeploymentContextBlock:tx,hasServerOS:Q_,getProfileNames:ex,probeUrlServer:sx,OS_HINTS:Uc}});var Ni=Q((lR,um)=>{var zt=require("fs").promises,cm=require("fs"),$t=require("path"),Ai=require("util").promisify(require("child_process").exec),{C:Zs}=Fe(),{getMergeConflicts:lm}=Nn(),{getServerContext:ox}=Bc(),rx=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function ix(t){try{return cm.readFileSync(t,"utf-8").split(`
|
|
508
|
+
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function ax(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 cx(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=$t.join(t,".gitignore"),r=[...o,...ix(s)],i=0,c=[$t.basename(t)+"/"];function l(u,d,f){if(f>e||i>=n)return;let p;try{p=cm.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=>!(rx.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||ax(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 Wc=new Map,Qs=new Map,Oi=null,lx=3e4;async function Ln(t){try{return await t()}catch{return null}}async function ux(){if(!Oi||Date.now()>Oi)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 dx(){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 fx(t){let e="fileContext",n=Wc.get(e),o=!1;if(n&&await ux()&&(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
|
-
`),
|
|
515
|
+
`),Wc.set(e,n),Oi=Date.now()+lx,await dx()}let s=[n],[r,i,c,l]=await Promise.all([Ln(async()=>{let{stdout:u}=await Ai("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Ln(async()=>{let{stdout:u}=await Ai("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Ln(async()=>{let{stdout:u}=await Ai("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),lm()]);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
519
|
${u}`)}try{let u=ox();u&&s.push(u)}catch{}return s.join(`
|
|
520
520
|
|
|
521
|
-
`)}async function px(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 Ci("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),cm()]);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()}lm.exports={gatherProjectContext:fx,printContext:px,generateFileTree:cx,_clearContextCache:()=>{Bc.clear(),Qs.clear(),Ai=null}}});var Jt=Q((uR,fm)=>{var Xt=require("fs"),Ni=require("path"),{atomicWrite:mx}=An();function zo(){return Ni.join(process.cwd(),".nex","sessions")}function Wc(){let t=zo();Xt.existsSync(t)||Xt.mkdirSync(t,{recursive:!0})}function Hc(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Ni.join(zo(),`${e}.json`)}function Kc(t,e,n={}){Wc();let o=Hc(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 mx(o,JSON.stringify(s,null,2)),{path:o,name:t}}function um(t){let e=Hc(t);if(!Xt.existsSync(e))return null;try{return JSON.parse(Xt.readFileSync(e,"utf-8"))}catch{return null}}function dm(){Wc();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(Ni.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 hx(t){let e=Hc(t);return Xt.existsSync(e)?(Xt.unlinkSync(e),!0):!1}function gx(){let t=dm();return t.length===0?null:um(t[0].name)}var cs=null,_n=null,Yo=null;function $x(t,e={}){t.length!==0&&(cs&&clearTimeout(cs),_n=t,Yo=e||{},cs=setTimeout(()=>{_n&&_n.length>0&&Kc("_autosave",_n,Yo),cs=null,_n=null,Yo=null},5e3))}function yx(){cs&&(clearTimeout(cs),cs=null),_n&&_n.length>0&&(Kc("_autosave",_n,Yo),_n=null,Yo=null)}function wx(){Wc();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=Ni.join(t,r);try{let c=Xt.statSync(i);new Date(c.mtime)<o&&(Xt.unlinkSync(i),s++)}catch{}}return s}fm.exports={saveSession:Kc,loadSession:um,listSessions:dm,deleteSession:hx,getLastSession:gx,autoSave:$x,flushAutoSave:yx,clearOldSessions:wx,_getSessionsDir:zo}});var Mi=Q((dR,bm)=>{"use strict";var Xo=require("fs"),pm=require("path");function mm(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 bx(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 hm(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 gm(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 $m(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 ym(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 wm(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=mm(t),s=hm(t),r=o.length,i=bx(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=gm(t),m=$m(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=ym(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 ce=L-T,re=j-k||1;if(ce/re>=.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,ce]of j.ranges){if(T.length>0&&K(L,ce,T)){A=!0;break}T.push([L,ce])}if(!A)continue}if(j.count-j.ranges.length<=2&&j.ranges.length>=1){let A=!1,T=[];for(let[L,ce]of j.ranges){if(T.length>0&&K(L,ce,T)){A=!0;break}T.push([L,ce])}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 $e=new Map;for(let k of c)if(k.name==="grep"&&k.input?.path&&k.input?.pattern){let j=k.input.path;$e.has(j)||$e.set(j,new Set),$e.get(j).add(k.input.pattern)}let be=0,fe="";for(let[k,j]of $e)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 ce=L.split(/\s+/),re=ce[ce.length-1];for(let we of k)(we.endsWith(re)||re.endsWith(we.split("/").pop()))&&j.add(we)}}}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(re=>re&&(re.type==="text"||typeof re=="string")).map(re=>typeof re=="string"?re:re.text||"").join("")),j.length<=5e3)continue;let x=j.split(/(?<=\. )/).filter(re=>re.trim().length>0);if(x.length<6)continue;let E=new Map;for(let re=0;re<=x.length-3;re++){let we=x.slice(re,re+3).join("").trim();we.length>30&&E.set(we,(E.get(we)||0)+1)}let A=0,T="";for(let[re,we]of E)we>A&&(A=we,T=re);if(A<3)continue;let ce=T.length*A/j.length;if(ce>=.4||A>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${A}\xD7 same paragraph, ${Math.round(ce*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 px(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 Ai("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),lm()]);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()}um.exports={gatherProjectContext:fx,printContext:px,generateFileTree:cx,_clearContextCache:()=>{Wc.clear(),Qs.clear(),Oi=null}}});var Jt=Q((uR,pm)=>{var Xt=require("fs"),Mi=require("path"),{atomicWrite:mx}=An();function zo(){return Mi.join(process.cwd(),".nex","sessions")}function Hc(){let t=zo();Xt.existsSync(t)||Xt.mkdirSync(t,{recursive:!0})}function Kc(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Mi.join(zo(),`${e}.json`)}function Gc(t,e,n={}){Hc();let o=Kc(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 mx(o,JSON.stringify(s,null,2)),{path:o,name:t}}function dm(t){let e=Kc(t);if(!Xt.existsSync(e))return null;try{return JSON.parse(Xt.readFileSync(e,"utf-8"))}catch{return null}}function fm(){Hc();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(Mi.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 hx(t){let e=Kc(t);return Xt.existsSync(e)?(Xt.unlinkSync(e),!0):!1}function gx(){let t=fm();return t.length===0?null:dm(t[0].name)}var cs=null,xn=null,Yo=null;function $x(t,e={}){t.length!==0&&(cs&&clearTimeout(cs),xn=t,Yo=e||{},cs=setTimeout(()=>{xn&&xn.length>0&&Gc("_autosave",xn,Yo),cs=null,xn=null,Yo=null},5e3))}function yx(){cs&&(clearTimeout(cs),cs=null),xn&&xn.length>0&&(Gc("_autosave",xn,Yo),xn=null,Yo=null)}function wx(){Hc();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=Mi.join(t,r);try{let c=Xt.statSync(i);new Date(c.mtime)<o&&(Xt.unlinkSync(i),s++)}catch{}}return s}pm.exports={saveSession:Gc,loadSession:dm,listSessions:fm,deleteSession:hx,getLastSession:gx,autoSave:$x,flushAutoSave:yx,clearOldSessions:wx,_getSessionsDir:zo}});var Pi=Q((dR,_m)=>{"use strict";var Xo=require("fs"),mm=require("path");function hm(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 bx(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 gm(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 $m(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 ym(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 wm(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 bm(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=hm(t),s=gm(t),r=o.length,i=bx(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=$m(t),m=ym(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=wm(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 $e=new Map;for(let k of c)if(k.name==="grep"&&k.input?.path&&k.input?.pattern){let j=k.input.path;$e.has(j)||$e.set(j,new Set),$e.get(j).add(k.input.pattern)}let be=0,fe="";for(let[k,j]of $e)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 ae=L.split(/\s+/),se=ae[ae.length-1];for(let we of k)(we.endsWith(se)||se.endsWith(we.split("/").pop()))&&j.add(we)}}}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 we=x.slice(se,se+3).join("").trim();we.length>30&&E.set(we,(E.get(we)||0)+1)}let A=0,T="";for(let[se,we]of E)we>A&&(A=we,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 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(`
|
|
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 he=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:he,issues:n,summary:Re}}function _x(t){try{let{loadSession:e}=Jt(),n=e(t);return n?
|
|
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 he=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:he,issues:n,summary:Re}}function _x(t){try{let{loadSession:e}=Jt(),n=e(t);return n?bm(n.messages||[]):null}catch{return null}}function xx(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 vx(t,e={}){try{let n=
|
|
527
|
+
${s}(+${u} more)${r}`),l}function vx(t,e={}){try{let n=mm.join(process.cwd(),".nex");Xo.existsSync(n)||Xo.mkdirSync(n,{recursive:!0});let o=mm.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{}}_m.exports={scoreMessages:bm,scoreSession:_x,formatScore:xx,appendScoreHistory:vx,_extractToolCalls:hm,_extractToolResults:gm,_getLastAssistantText:$m,_getLastNAssistantTexts:ym,_countDuplicateToolCalls:wm}});var In=Q((fR,Tm)=>{"use strict";var kx=require("os"),xm=require("path"),Jo=require("fs"),Vo=xm.join(kx.homedir(),".nex-code","model-routing.json"),Li={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}},vm=["agentic","frontend","sysadmin","data","coding"];function Sx(t){if(!t||t.length<8)return null;for(let e of vm){let n=Li[e];if(!n.pattern||n.pattern.test(t))return n}return Li.coding}function Zo(){try{if(Jo.existsSync(Vo))return JSON.parse(Jo.readFileSync(Vo,"utf-8"))}catch{}return{}}function km(t){let e=Li[t];return e?.envVar&&process.env[e.envVar]?process.env[e.envVar]:Zo()[t]||null}var Sm={plan:10,implement:35,verify:8},Yc={plan:"qwen3-coder:480b",implement:null,verify:"devstral-small-2:24b"};function Em(){let t=Zo();if(t.phases&&Object.keys(t.phases).length>0)return t.phases;try{let{getActiveProviderName:e}=je();if(e()==="ollama")return Yc}catch{}return process.env.NEX_PHASE_ROUTING==="1"?Yc:null}function Ex(t,e){let n=Em();return n?.[t]?n[t]:e?km(e):null}function Tx(t){return Zo().phaseBudgets?.[t]||Sm[t]||20}function Rx(){return process.env.NEX_PHASE_ROUTING==="0"?!1:Em()!==null}function Cx(t){let e=xm.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))}Tm.exports={CATEGORIES:Li,DETECTION_ORDER:vm,detectCategory:Sx,getModelForCategory:km,getModelForPhase:Ex,getPhaseBudget:Tx,isPhaseRoutingEnabled:Rx,DEFAULT_PHASE_BUDGETS:Sm,BUILTIN_PHASE_DEFAULTS:Yc,saveRoutingConfig:Cx,loadRoutingConfig:Zo,ROUTING_CONFIG_PATH:Vo}});var Om=Q((pR,Am)=>{"use strict";var ls=require("fs"),Qo=require("path"),Ax=require("os"),{detectCategory:Ox}=In(),eo=Qo.join(Ax.homedir(),".nex-code","examples"),zc=Qo.join(__dirname,"..","examples");function Rm(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
|
|
530
|
+
`).trim();return{user:s,assistant:u}}catch{return null}}function Cm(t){let e=`${t}.md`,n=Qo.join(eo,e);if(ls.existsSync(n)){let s=Rm(n);if(s)return s}let o=Qo.join(zc,e);return ls.existsSync(o)?Rm(o):null}function Nx(t){if(process.env.NEX_FEW_SHOT==="0"||!t||t.length<8)return null;let e=Ox(t);return e?Cm(e.id):null}function Mx(){let t=new Set;for(let e of[eo,zc])try{for(let n of ls.readdirSync(e))n.endsWith(".md")&&t.add(n.replace(".md",""))}catch{}return[...t].sort()}function Px(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,14 +535,14 @@ 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")}
|
|
538
|
+
`;ls.writeFileSync(Qo.join(eo,`${t}.md`),n,"utf-8")}Am.exports={getFewShotForInput:Nx,loadExampleForCategory:Cm,listAvailableExamples:Mx,savePrivateExample:Px,PRIVATE_EXAMPLES_DIR:eo,BUNDLED_EXAMPLES_DIR:zc}});var tr=Q((hR,Im)=>{var Ot=require("fs"),to=require("path"),{C:mR}=Fe(),{atomicWrite:Lx,withFileLockSync:Ix}=An(),Ii={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={...Ii};function Nm(){let t=to.join(process.cwd(),".nex","config.json");if(Ot.existsSync(t))try{let e=JSON.parse(Ot.readFileSync(t,"utf-8"));e.permissions&&(no={...Ii,...e.permissions})}catch{}}function jx(){let t=to.join(process.cwd(),".nex"),e=to.join(t,"config.json");Ot.existsSync(t)||Ot.mkdirSync(t,{recursive:!0}),Ix(e,()=>{let n={};if(Ot.existsSync(e))try{n=JSON.parse(Ot.readFileSync(e,"utf-8"))}catch{n={}}n.permissions=no,Lx(e,JSON.stringify(n,null,2))})}function Mm(t){return no[t]||"ask"}function Dx(t,e){return["allow","ask","deny"].includes(e)?(no[t]=e,!0):!1}function qx(t){return Mm(t)}function Fx(){return Object.entries(no).map(([t,e])=>({tool:t,mode:e}))}function Ux(){no={...Ii}}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 Pm(){let t=to.join(process.cwd(),".nex","config.json");try{return Ot.existsSync(t)&&JSON.parse(Ot.readFileSync(t,"utf-8")).teamPermissions||null}catch{return null}}function Bx(t){let e=to.join(process.cwd(),".nex"),n=to.join(e,"config.json");Ot.existsSync(e)||Ot.mkdirSync(e,{recursive:!0});let o={};try{Ot.existsSync(n)&&(o=JSON.parse(Ot.readFileSync(n,"utf-8")))}catch{o={}}o.teamPermissions=t,Ot.writeFileSync(n,JSON.stringify(o,null,2),"utf-8")}function Lm(){let t=Pm();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 Wx(t){let e=Lm();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 Hx(){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}))}Nm();Im.exports={getPermission:Mm,setPermission:Dx,checkPermission:qx,listPermissions:Fx,loadPermissions:Nm,savePermissions:jx,resetPermissions:Ux,DEFAULT_PERMISSIONS:Ii,PERMISSION_PRESETS:er,loadPresetConfig:Pm,savePresetConfig:Bx,getEffectivePreset:Lm,isToolAllowed:Wx,listPresets:Hx}});var ln=Q(($R,Um)=>{var ds=require("fs"),ji=require("path"),gR=require("readline"),{C:Me}=Fe(),Oe=null,Jc=!1,Vc=null,jm=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show"]);function Di(){return ji.join(process.cwd(),".nex","plans")}function Dm(){let t=Di();ds.existsSync(t)||ds.mkdirSync(t,{recursive:!0})}function Kx(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 Gx(){return Oe}function Yx(t){Jc=t}function zx(){return Jc}function Xx(){return!Oe||Oe.status!=="draft"?!1:(Oe.status="approved",Oe.updatedAt=new Date().toISOString(),!0)}function Jx(){return!Oe||Oe.status!=="approved"?!1:(Oe.status="executing",!0)}function Xc(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 Vx(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 Zx(t){if(t||(t=Oe),!t)return null;
|
|
541
|
+
`)}function Zx(t){if(t||(t=Oe),!t)return null;Dm();let e=ji.join(Di(),`${t.name}.json`);return ds.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function Qx(t){let e=ji.join(Di(),`${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 ev(){Dm();let t=Di(),e=ds.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(ds.readFileSync(ji.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 tv(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 nv(t){Vc=t}function sv(){return Vc}function ov(){Oe=null,Jc=!1,Vc=null,cv()}function rv(){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)
|
|
545
|
-
You may ONLY use these tools: ${[...
|
|
545
|
+
You may ONLY use these tools: ${[...jm].join(", ")}
|
|
546
546
|
Any other tool call will be blocked and returned with an error.
|
|
547
547
|
|
|
548
548
|
# MANDATORY: Read Before You Plan
|
|
@@ -586,23 +586,23 @@ 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 iv(){!Oe||Oe.status!=="executing"||(us>0&&
|
|
590
|
-
`),n=[],o=!1,s="";for(let r of e){let i=
|
|
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
|
|
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 iv(){!Oe||Oe.status!=="executing"||(us>0&&Xc(us-1,"done"),us<Oe.steps.length&&(Xc(us,"in_progress"),us++))}function av(){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 cv(){us=0}var qm=["interactive","semi-auto","autonomous"],Fm="interactive";function lv(t){return qm.includes(t)?(Fm=t,!0):!1}function uv(){return Fm}Um.exports={createPlan:Kx,getActivePlan:Gx,setPlanMode:Yx,isPlanMode:zx,approvePlan:Xx,startExecution:Jx,updateStep:Xc,formatPlan:Vx,savePlan:Zx,loadPlan:Qx,listPlans:ev,clearPlan:ov,getPlanModePrompt:rv,setPlanContent:nv,getPlanContent:sv,extractStepsFromText:tv,advancePlanStep:iv,getPlanStepInfo:av,PLAN_MODE_ALLOWED_TOOLS:jm,setAutonomyLevel:lv,getAutonomyLevel:uv,AUTONOMY_LEVELS:qm}});var Zm=Q((yR,Vm)=>{var{C:N}=Fe();function Bm(){return Math.max(10,(process.stdout.columns||80)-2)}function dv(t){if(!t)return"";let e=t.split(`
|
|
590
|
+
`),n=[],o=!1,s="";for(let r of e){let i=Bm();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(` ${Qc(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
|
+
`)}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 Qc(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Wm(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Hm(t):e==="json"||e==="jsonc"?Km(t):e==="python"||e==="py"?Gm(t):e==="go"||e==="golang"?Ym(t):e==="rust"||e==="rs"?zm(t):e==="css"||e==="scss"||e==="less"?Xm(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Jm(t):t:""}function Wm(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 Hm(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 Km(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 Gm(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 Ym(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 zm(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 Xm(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 Jm(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
593
|
`+n,c=i,s=n.length+1),i++}return o+=t.slice(c),o}function fv(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 pv(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
|
|
594
|
+
`)}function pv(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 Zc=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
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=
|
|
596
|
+
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){let n=Bm();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}
|
|
598
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
598
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${Qc(e,this.codeBlockLang)}
|
|
599
599
|
`);return}if(e.startsWith("### ")){this._safeWrite(`${N.bold}${N.cyan} ${fs(e.substring(4))}${N.reset}
|
|
600
600
|
`);return}if(e.startsWith("## ")){this._safeWrite(`${N.bold}${N.cyan} ${fs(e.substring(3))}${N.reset}
|
|
601
601
|
`);return}if(e.startsWith("# ")){this._safeWrite(`${N.bold}${N.cyan}${fs(e.substring(2))}${N.reset}
|
|
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
|
-
`)}};
|
|
605
|
+
`)}};Vm.exports={renderMarkdown:dv,renderInline:ps,stripHeadingMarkers:fs,highlightCode:Qc,highlightJS:Wm,highlightBash:Hm,highlightJSON:Km,highlightPython:Gm,highlightGo:Ym,highlightRust:zm,highlightCSS:Xm,highlightHTML:Jm,renderTable:fv,renderProgress:pv,wrapAnsi:ms,StreamRenderer:Zc}});var nl=Q((wR,nh)=>{var{execSync:mv}=require("child_process"),el=require("path"),nr=require("fs"),tl=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Qm(){return el.join(process.cwd(),".nex","hooks")}function hv(){return el.join(process.cwd(),".nex","config.json")}function eh(){let t=hv();if(!nr.existsSync(t))return{};try{return JSON.parse(nr.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function qi(t){if(!tl.includes(t))return[];let e=[],n=Qm(),o=el.join(n,t);nr.existsSync(o)&&e.push(o);let s=eh();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function th(t,e={},n=3e4){try{return{success:!0,output:mv(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 gv(t,e={}){let n=qi(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=th(r,o);if(s.push({command:r,...i}),!i.success&&t.startsWith("pre-"))break}return s}function $v(t){return qi(t).length>0}function yv(){let t=[];for(let e of tl){let n=qi(e);n.length>0&&t.push({event:e,commands:n})}return t}function wv(){let t=Qm();return nr.existsSync(t)||nr.mkdirSync(t,{recursive:!0}),t}nh.exports={HOOK_EVENTS:tl,loadHookConfig:eh,getHooksForEvent:qi,executeHook:th,runHooks:gv,hasHooks:$v,listHooks:yv,initHooksDir:wv}});var sr=Q((vR,hh)=>{"use strict";var{callWithRetry:oh,runSubAgent:bv,clearAllLocks:_v}=_i(),{parseModelSpec:rh,getActiveProviderName:bR,getActiveModelId:_R}=je(),{detectCategory:xv,getModelForCategory:sh}=In(),{MultiProgress:vv,C:ge}=Fe(),{getModelBriefing:xR}=hi(),ih=parseInt(process.env.NEX_MAX_PARALLEL||"4",10),Fi=parseInt(process.env.NEX_MAX_SUBTASKS||"8",10),ah="devstral-2:123b",ch="kimi-k2.5",lh=`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.
|
|
@@ -617,7 +617,7 @@ RULES:
|
|
|
617
617
|
- If the request is simple (single goal), return an array with exactly 1 item.
|
|
618
618
|
|
|
619
619
|
USER REQUEST:
|
|
620
|
-
{prompt}`,
|
|
620
|
+
{prompt}`,uh=`You are a result synthesis engine. Given the results of multiple sub-agents that worked on parts of a larger task, produce a unified summary.
|
|
621
621
|
|
|
622
622
|
RULES:
|
|
623
623
|
- Output ONLY a JSON object with these fields:
|
|
@@ -631,16 +631,16 @@ ORIGINAL REQUEST:
|
|
|
631
631
|
{prompt}
|
|
632
632
|
|
|
633
633
|
SUB-AGENT RESULTS:
|
|
634
|
-
{results}`;async function
|
|
635
|
-
${e.slice(0,200)}`)}async function
|
|
634
|
+
{results}`;async function dh(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 fh(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 kv(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 sl(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
|
+
${e.slice(0,200)}`)}async function ph(t,e,n={}){let o=n.maxSubTasks||Fi,r=[{role:"system",content:lh.replace("{maxSubTasks}",String(o)).replace("{prompt}",t)},{role:"user",content:t}],i={};if(e){let g=rh(e);g.provider&&(i.provider=g.provider),g.model&&(i.model=g.model)}let l=(await oh(r,[],i)).content||"",u=sl(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=Fi*d;if(h>m){let{debugLog:g}=zr();g(`\x1B[33m \u26A0 Orchestrator: total estimated calls ${h} > ${m} \u2014 consider raising maxSubTasks\x1B[0m`)}return p}async function mh(t,e,n){if(!t||t.length===0)return{summary:"No sub-tasks were executed.",conflicts:[],commitMessage:"",filesChanged:[]};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:
|
|
640
|
+
`),r=[{role:"system",content:uh.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let d=rh(n);d.provider&&(i.provider=d.provider),d.model&&(i.model=d.model)}let l=(await oh(r,[],i)).content||"",u=sl(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 Sv(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||ch,o=e.workerModel||ah,s=e.maxParallel||ih,r=e.maxSubTasks||Fi,i=e.onProgress||(()=>{}),c={input:0,output:0};console.log(`
|
|
641
641
|
${ge.bold}Orchestrator${ge.reset} ${ge.dim}model: ${n} | workers: ${o} | max parallel: ${s}${ge.reset}
|
|
642
|
-
`),i("decomposing"),console.log(`${ge.dim}Phase 1: Decomposing prompt into sub-tasks...${ge.reset}`);let l;try{l=await
|
|
643
|
-
`);let d=Date.now(),f=
|
|
642
|
+
`),i("decomposing"),console.log(`${ge.dim}Phase 1: Decomposing prompt into sub-tasks...${ge.reset}`);let l;try{l=await ph(t,n,{maxSubTasks:r})}catch(B){return console.log(`${ge.red}Decompose failed: ${B.message}${ge.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${B.message}`,conflicts:[],commitMessage:"",filesChanged:[]},totalTokens:c}}if(l.length===0)return console.log(`${ge.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${ge.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",filesChanged:[]},totalTokens:c};console.log(`${ge.green}Decomposed into ${l.length} sub-tasks:${ge.reset}`);for(let B of l){console.log(` ${ge.dim}${B.id}:${ge.reset} ${B.task}`);let R=B.scope.filter(Boolean);R.length>0&&console.log(` ${ge.dim}scope: ${R.join(", ")}${ge.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(`${ge.dim}Phase 2: Running ${l.length} sub-agents (max ${s} parallel)...${ge.reset}
|
|
643
|
+
`);let d=Date.now(),f=fh(s),p={findings:[],_lock:!1},h=l.map(B=>{let R=xv(B.task);return(R?sh(R.id):null)||o}),m=l.map((B,R)=>{let $e=`Agent ${R+1} [${h[R]}]: `,be=Math.max(20,60-$e.length),fe=B.task.substring(0,be)+(B.task.length>be?"...":"");return $e+fe}),g=new vv(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
|
|
|
@@ -664,37 +664,37 @@ RULES:
|
|
|
664
664
|
`,w=l.map(async(B,R)=>{let $e=await f();try{let be=p.findings.filter(x=>x.agentId!==B.id).map(x=>`Agent ${x.agentId} found: ${x.summary}`).join(`
|
|
665
665
|
`),fe=[...u.entries()].filter(([,x])=>x===R).map(([x])=>x),pe=[...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(", ")}`:"",fe.length>0?`You OWN these files (may read+write): ${fe.join(", ")}`:"",pe.length>0?`READ ONLY (owned by other agents, do NOT write): ${pe.join(", ")}`:""].filter(Boolean),me=h[R],he=process.env.NEX_FALLBACK_MODEL||
|
|
667
|
+
`:"",B.scope.length>0?`Focus on files: ${B.scope.join(", ")}`:"",fe.length>0?`You OWN these files (may read+write): ${fe.join(", ")}`:"",pe.length>0?`READ ONLY (owned by other agents, do NOT write): ${pe.join(", ")}`:""].filter(Boolean),me=h[R],he=process.env.NEX_FALLBACK_MODEL||sh("agentic")||o,Re=0,k=await dh(async()=>{let x=Re>0;x&&(g.update(R,"retry"),process.stderr.write(` ${ge.dim}[Agent ${R+1}] retrying after error...${ge.reset}
|
|
668
668
|
`)),Re++;let E=x&&me!==he?he:me;return bv({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:pe},{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{$e()}}),v;try{v=await Promise.all(w)}finally{g.stop({silent:!0}),_v()}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")?`${ge.green}\u2713${ge.reset}`:`${ge.red}\u2717${ge.reset}`,fe=R._scope&&R._scope.length>0?R._scope.map(me=>me.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],pe=fe.length>0?fe.join(", "):R.task.substring(0,35)+(R.task.length>35?"...":""),xe=B===v.length-1;console.log(` ${be} Agent ${B+1} ${ge.dim}${pe}${ge.reset}${xe?` ${ge.dim}${C}${ge.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${ge.dim}Phase 3: Synthesizing results...${ge.reset}`);let S;try{S=await
|
|
669
|
+
`):void 0,max_iterations:Math.min(B.estimatedCalls||10,15),model:E,_skipLog:!0,_systemPrompt:y,_readOnlyFiles:pe},{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{$e()}}),v;try{v=await Promise.all(w)}finally{g.stop({silent:!0}),_v()}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")?`${ge.green}\u2713${ge.reset}`:`${ge.red}\u2717${ge.reset}`,fe=R._scope&&R._scope.length>0?R._scope.map(me=>me.replace(/^.*\//,"").replace(/\/$/,"")).filter(Boolean):[],pe=fe.length>0?fe.join(", "):R.task.substring(0,35)+(R.task.length>35?"...":""),xe=B===v.length-1;console.log(` ${be} Agent ${B+1} ${ge.dim}${pe}${ge.reset}${xe?` ${ge.dim}${C}${ge.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${ge.dim}Phase 3: Synthesizing results...${ge.reset}`);let S;try{S=await mh(v,t,n)}catch(B){console.log(`${ge.yellow}Synthesize failed: ${B.message} \u2014 using raw results.${ge.reset}`),S={summary:v.map(R=>R.result).join(`
|
|
670
670
|
`),conflicts:[],commitMessage:"",filesChanged:[]}}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?` ${ge.dim}(agents shared context)${ge.reset}`:"";if(console.log(`
|
|
671
671
|
${ge.bold}Summary:${ge.reset} ${S.summary}${V}`),S.conflicts.length>0){console.log(`${ge.yellow}Conflicts:${ge.reset}`);for(let B of S.conflicts)console.log(` - ${B}`)}S.commitMessage&&console.log(`${ge.dim}Suggested commit: ${S.commitMessage}${ge.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(`${ge.dim}Tokens: ${X}${ge.reset}
|
|
672
|
-
`),{results:v,synthesis:S,totalTokens:c}}
|
|
673
|
-
`)}var
|
|
672
|
+
`),{results:v,synthesis:S,totalTokens:c}}hh.exports={runOrchestrated:Sv,decompose:ph,synthesize:mh,detectComplexPrompt:kv,extractJSON:sl,createSemaphore:fh,DECOMPOSE_PROMPT:lh,SYNTHESIZE_PROMPT:uh,DEFAULT_ORCHESTRATOR_MODEL:ch,DEFAULT_WORKER_MODEL:ah,DEFAULT_MAX_PARALLEL:ih,DEFAULT_MAX_SUBTASKS:Fi,withRetry:dh}});var Se=Q((CR,Dh)=>{var{C:$,Spinner:oo,TaskProgress:Ev,formatToolCall:Tv,formatToolSummary:Ah,formatSectionHeader:Ui,formatMilestone:Rv,setActiveTaskProgress:kR}=Fe(),{debugLog:W,warnLog:SR}=zr(),{MilestoneTracker:Cv}=Ed(),{callStream:gh}=je(),{parseToolArgs:Av}=Fs(),{executeTool:Ov}=Gt(),{gatherProjectContext:Nv}=Ni(),{fitToContext:Mv,forceCompress:un,getUsage:Vt,estimateTokens:Pv}=Rt(),{autoSave:Lv,flushAutoSave:Iv}=Jt(),{scoreMessages:jv,formatScore:Dv,appendScoreHistory:qv}=Pi(),{detectCategory:Fv,getModelForPhase:pl,getPhaseBudget:hs,isPhaseRoutingEnabled:Uv}=In();function Ze(t){Lv(t),Iv()}function Bv(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 $h(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=jv(t);if(!n)return;console.log(Dv(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();qv(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:Wv}=cn(),{getDeploymentContextBlock:Hv,probeUrlServer:Kv}=Bc(),{getFewShotForInput:Gv}=Om(),{checkPermission:Yv,setPermission:zv,savePermissions:Xv}=tr(),{confirm:Oh,setAllowAlwaysHandler:Jv,getAutoConfirm:Vv}=ft(),{isPlanMode:fr,getPlanModePrompt:Zv,PLAN_MODE_ALLOWED_TOOLS:Nh,setPlanContent:Qv,extractStepsFromText:ek,createPlan:tk,getActivePlan:ER,startExecution:TR,advancePlanStep:nk,getPlanStepInfo:sk}=ln(),{StreamRenderer:ok}=Zm(),{runHooks:yh}=nl(),{routeMCPCall:rk,getMCPToolDefinitions:ik}=ti(),{getSkillInstructions:ak,getSkillToolDefinitions:ck,routeSkillCall:lk,matchSkillTriggers:uk}=Mn(),{trackUsage:wh,estimateTokens:bh}=qs();function _h(t){return!t||typeof t!="string"?0:typeof bh=="function"?bh(t):Math.ceil(t.length/4)}var{validateToolArgs:dk}=ac(),{filterToolsForModel:xh,getModelTier:fk,PROVIDER_DEFAULT_TIER:RR}=Ro(),{getConfiguredProviders:pk,getActiveProviderName:ro,getActiveModelId:fn,setActiveModel:vh,MODEL_EQUIVALENTS:ea}=je(),{getModelProfile:mk,getModelBriefing:hk}=hi(),kl=require("fs"),Sl=require("path"),gk=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function $k(t){let e=Rv(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
|
|
673
|
+
`)}var kh=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function yk(t){let e=[],n;for(kh.lastIndex=0;(n=kh.exec(t))!==null;){let o=n[1].trim(),s=o.startsWith("~")?o.replace("~",process.env.HOME||""):Sl.resolve(o);kl.existsSync(s)&&e.push({raw:o,abs:s})}return e}function wk(t){let e=kl.readFileSync(t),n=Sl.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 Mh(t){let e=yk(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}=wk(o.abs);n.push({type:"image",media_type:r,data:s})}catch{}return n.length>1?n:t}function bk(t){if(!t||t.length<200)return{text:t,truncated:!1,repeatCount:0};let n=t.split(/(?<=\. )/).filter(l=>l.trim().length>0);if(n.length<6)return{text:t,truncated:!1,repeatCount:0};let 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
|
-
[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
|
|
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 ml(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
|
|
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 ol=null,rl=null,il=null;function pt(){if(ol===null){let{TOOL_DEFINITIONS:t}=Gt();ol=t}return rl===null&&(rl=ck()),il===null&&(il=ik()),[...ol,...rl,...il]}var hl=50;function _k(t){Number.isFinite(t)&&t>0&&(hl=t)}var Hi=()=>null;function xk(t){Hi=t}var ir=null,gl=null,io=null,Ki=new Map,vk=1e4,kk=6e3,Sk=/\b((?:API|ACCESS|AUTH|BEARER|CLIENT|GITHUB|GITLAB|SLACK|STRIPE|TWILIO|SENDGRID|AWS|GCP|AZURE|OPENAI|ANTHROPIC|GEMINI|OLLAMA)[_A-Z0-9]*(?:KEY|TOKEN|SECRET|PASS(?:WORD)?|CREDENTIAL)[_A-Z0-9]*)\s*=\s*["']?([A-Za-z0-9\-_.+/=]{10,})["']?/g;function Ek(t){return!t||typeof t!="string"?t:t.replace(Sk,(e,n)=>`${n}=***REDACTED***`)}var Tk=7e3,Rk=4e3;function Ck(t,e=null){let n=Ek(t),o=Pv(n),s=e==="read_file"?Tk:vk,r=e==="read_file"?Rk:kk;if(o>s)try{let{compressToolResult:i}=Rt();return i(n,r)}catch{return n}return n}function Ph(t){try{let{getActiveModel:e}=je(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(Ki.has(o))return Ki.get(o);let s=xh(t);return Ki.set(o,s),s}catch{return xh(t)}}function Ak(){Ki.clear()}var ar={hash:null,ts:0},Ok=3e4;async function Lh(){if(ar.hash&&Date.now()-ar.ts<Ok)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}=cn(),c=i();c&&s.push(`memory:${c}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(kl.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 $l(){ir=null,gl=null,ar={hash:null,ts:0},io=null}var Nk=new Set(["spawn_agents"]),al=5,cl=3,Bi=2,Sh=6e4,ll=12e4,Mk=process.env.NEX_STALE_AUTO_SWITCH!=="0";function Pk(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{}}Jv(t=>{zv(t,"allow"),Xv(),console.log(`${$.green} \u2713 ${t}: always allow${$.reset}`)});async function Lk(t){let e=t.function.name,n=Av(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
684
|
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}let s=dk(e,n);if(!s.valid){W(`${$.yellow} \u26A0 ${e}: ${s.error.split(`
|
|
685
|
-
`)[0]}${$.reset}`);let u=(
|
|
685
|
+
`)[0]}${$.reset}`);let u=(Rh.get(e)||0)+1;Rh.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()&&!
|
|
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()&&!Nh.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=Yv(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 Oh(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 Ik(t,e,n={}){let o=await lk(t,e);if(o!==null)return o;let s=await rk(t,e);return s!==null?s:Ov(t,e,n)}function jk(t,e){switch(t){case"read_file":case"write_file":case"edit_file":case"patch_file":case"list_directory":return e.path||"";case"bash":return(e.command||"").substring(0,60);case"grep":case"search_files":case"glob":return e.pattern||"";case"web_fetch":return(e.url||"").substring(0,50);case"web_search":return(e.query||"").substring(0,40);default:return""}}async function ul(t,e=!1){e||console.log(Tv(t.fnName,t.args));let n=yh("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}`);pn?.onToolStart&&pn.onToolStart(t.fnName,t.args);let o=await Ik(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=
|
|
689
|
+
`)[0],c=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),l=Ah(t.fnName,t.args,r,c);e||console.log(l),pn?.onToolEnd&&pn.onToolEnd(t.fnName,l,!c);let u=yh("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=Ck(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 Dk=[{re:/TypeError:\s*([^\n]{0,120})/i,label:"TypeError"},{re:/SyntaxError:\s*([^\n]{0,120})/i,label:"SyntaxError"},{re:/ReferenceError:\s*([^\n]{0,120})/i,label:"ReferenceError"},{re:/Cannot find module\s*'([^']+)'/i,label:"Cannot find module"},{re:/Error:\s*ENOENT[^\n]{0,120}/i,label:"ENOENT"},{re:/Error:\s*EACCES[^\n]{0,120}/i,label:"EACCES"},{re:/Error:\s*EADDRINUSE[^\n]{0,120}/i,label:"EADDRINUSE"},{re:/ImportError:\s*([^\n]{0,120})/i,label:"ImportError"},{re:/ModuleNotFoundError:\s*([^\n]{0,120})/i,label:"ModuleNotFoundError"},{re:/NameError:\s*([^\n]{0,120})/i,label:"NameError"},{re:/AttributeError:\s*([^\n]{0,120})/i,label:"AttributeError"},{re:/KeyError:\s*([^\n]{0,120})/i,label:"KeyError"},{re:/ValueError:\s*([^\n]{0,120})/i,label:"ValueError"},{re:/panic:\s*([^\n]{0,120})/i,label:"Go panic"},{re:/java\.lang\.\w+Exception[^\n]{0,80}/i,label:"Java exception"}];function
|
|
693
|
-
`)):(
|
|
694
|
-
`)}function rr(t,e,n,o){if(!Te)return null;let s=Xe;Xe=t,
|
|
695
|
-
${
|
|
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 Dk=[{re:/TypeError:\s*([^\n]{0,120})/i,label:"TypeError"},{re:/SyntaxError:\s*([^\n]{0,120})/i,label:"SyntaxError"},{re:/ReferenceError:\s*([^\n]{0,120})/i,label:"ReferenceError"},{re:/Cannot find module\s*'([^']+)'/i,label:"Cannot find module"},{re:/Error:\s*ENOENT[^\n]{0,120}/i,label:"ENOENT"},{re:/Error:\s*EACCES[^\n]{0,120}/i,label:"EACCES"},{re:/Error:\s*EADDRINUSE[^\n]{0,120}/i,label:"EADDRINUSE"},{re:/ImportError:\s*([^\n]{0,120})/i,label:"ImportError"},{re:/ModuleNotFoundError:\s*([^\n]{0,120})/i,label:"ModuleNotFoundError"},{re:/NameError:\s*([^\n]{0,120})/i,label:"NameError"},{re:/AttributeError:\s*([^\n]{0,120})/i,label:"AttributeError"},{re:/KeyError:\s*([^\n]{0,120})/i,label:"KeyError"},{re:/ValueError:\s*([^\n]{0,120})/i,label:"ValueError"},{re:/panic:\s*([^\n]{0,120})/i,label:"Go panic"},{re:/java\.lang\.\w+Exception[^\n]{0,80}/i,label:"Java exception"}];function dl(t){for(let{re:e,label:n}of Dk){let o=t.match(e);if(o){let s=(o[1]||"").trim();return s?`${n}: ${s}`:n}}return null}async function qk(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=jk(d.fnName,d.args);u=`\u23FA ${d.fnName}${f?`(${f})`:""}`}else{let d=l.map(f=>f.fnName).join(", ");u=`\u23FA ${l.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}i=new oo(u),i.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await ul(t[l],e);o[l]=u,s.push(d)}else{let l=r.map(d=>ul(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(Ah(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(Nk.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await ul(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=[],Eh=300,Ih=900*1e3;function gs(t,e){let n=t.get(e);return n?Date.now()-n.ts>Ih?(t.delete(e),0):n.count:0}function $s(t,e){let n=t.get(e),o=n&&Date.now()-n.ts<=Ih?n.count+1:1;return t.set(e,{count:o,ts:Date.now()}),o}function Th(t,e,n){t.set(e,{count:n,ts:Date.now()})}var El=new Map,Tl=new Map,pr=new Map,Rl=new Map,mr=new Map,xs=new Map,Dn=new Map,Cl=new Map,ys=new Map,vs=new Map,Rh=new Map,ta=new Map,na=new Map,Ut=0,cr=0,Gi=0,yl="",Yi=0,Nt=!1,Wi=0,zi=0,ws=-1,wl=!1,Xi=0,Ji=!1,dn=0,Zt=!1,vn=0,Qt=0,ot=!1,kt="",lr=0,jn=0,Vi="",bs=0,_s=0,Zi="",Bt=!1,bl=!1,hr=new Map,gr=new Set,ur=null,fl=!1,or=0,Ch=!1,Xe="plan",sa=0,Te=!1,qn=0,kn=null,_l=null,xl=null,dr=0,ao=null;function so(t,e){t===yl?(Yi++,zr().DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${Yi})${$.reset}
|
|
693
|
+
`)):(yl=t,Yi=1,W(`${e} \u26A0 ${t}${$.reset}`))}var Qi=[];function Fk(t){Qi.push(t.trim())}function Uk(){return Qi.length===0?null:Qi.splice(0,Qi.length).join(`
|
|
694
|
+
`)}function rr(t,e,n,o){if(!Te)return null;let s=Xe;Xe=t,sa=0,kn=pl(t,ao),dn=0,Zt=!1,vn=0,Qt=0,xs.clear(),Dn.clear(),vs.clear(),ta.clear(),na.clear(),Tl.clear(),pr.clear(),Rl.clear(),mr.clear(),El.clear(),Cl.clear();let r;if(t==="implement")_l=e?.slice(0,800)||"",r=`[PHASE: IMPLEMENTATION] Analysis complete. Based on the analysis:
|
|
695
|
+
${_l}
|
|
696
696
|
|
|
697
|
-
Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`;else if(t==="verify"){
|
|
697
|
+
Now implement the fix/changes. Do not investigate further \u2014 edit files directly.`;else if(t==="verify"){xl=e?.slice(0,500)||"";let i=n?[...n].join(", "):"none";r=`[PHASE: VERIFICATION] Implementation complete. Verify the changes:
|
|
698
698
|
1. Read each modified file and confirm changes are correct
|
|
699
699
|
2. If test command exists (npm test / pytest): run it
|
|
700
700
|
3. If linter exists: run it
|
|
@@ -702,7 +702,7 @@ 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: ${
|
|
705
|
+
Summary: ${xl}`}return W(`${$.cyan} \u21B3 Phase transition: ${s} \u2192 ${t} (model: ${kn||"default"})${$.reset}`),r?{role:"user",content:r}:null}function Bk(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,n=process.env.NEX_COMMIT_LANGUAGE,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
|
`)+`
|
|
@@ -713,7 +713,7 @@ This is a hard requirement. Always respond in ${o}. Do NOT switch to any other l
|
|
|
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
|
|
716
|
+
`;return io=o,o}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),io="",""}}async function vl(){let t=await Lh()+":"+fn();if(ir!==null&&t===gl)return ir;let e=await Nv(process.cwd()),n=Wv(),o=ak(),s=fr()?Zv():"",r=Bk(),i=Hv(),c=hk(fn());return ir=`${c?`## Model Briefing
|
|
717
717
|
${c}
|
|
718
718
|
|
|
719
719
|
---
|
|
@@ -1150,97 +1150,97 @@ 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
|
-
`,
|
|
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=
|
|
1153
|
+
`,gl=t,ir}function jh(){El.clear(),Tl.clear(),pr.clear(),Rl.clear(),mr.clear(),xs.clear(),Dn.clear(),Cl.clear(),ys.clear(),vs.clear(),ta.clear(),na.clear(),Ut=0,cr=0,Gi=0,Nt=!1,zi=0,ws=-1,wl=!1,Xi=0,Ji=!1,dn=0,Zt=!1,vn=0,Qt=0,ot=!1,kt="",lr=0,Vi="",bs=0,Zi="",_s=0,Bt=!1,bl=!1,Xe="plan",sa=0,Te=!1,kn=null,_l=null,xl=null,dr=0,qn=0,ao=null,hr.clear(),gr.clear(),yl="",Yi=0}function Hk(){H=[],ur=null,jh()}function Kk(){H.length>Eh&&H.splice(0,H.length-Eh)}function Gk(){return H.length}function Yk(){return H}function zk(t){H=t}async function Xk(){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
|
+
`):[]).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=Sl.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
1155
|
\u{1F4E6} ${h}${m}`}}catch{}return u}function Jk(t){if(process.platform==="darwin")try{let{execFileSync:e}=require("child_process");e("osascript",["-e",`display notification "${t.replace(/"/g,'\\"')}" with title "nex-code"`],{timeout:3e3,stdio:"ignore"})}catch{}}function 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`;Jk(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 Vk(){if(!process.stdout.isTTY)return{action:"quit"};let t=ro(),e=
|
|
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
|
|
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`;Jk(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 Vk(){if(!process.stdout.isTTY)return{action:"quit"};let t=ro(),e=fn(),n=ea.fast?.[t],o=ea.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 pn=null;async function Zk(t,e=null,n={}){let o=mk(fn());Sh=o.staleWarn,ll=o.staleAbort,pn=e;let s=t;ur&&typeof t=="string"&&(s=`${ur}
|
|
1158
1158
|
|
|
1159
|
-
${t}`,ur=null);let r=
|
|
1159
|
+
${t}`,ur=null);let r=Mh(s);H.push({role:"user",content:r}),Kk();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}=mi(),u=null,d=0;l((Ae,Ne)=>{Ae==="create"?(u&&u.stop(),u=new Ev(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 vl(),p=f;try{let{getBrainContext:Ae}=Do(),Ne=await Ae(t);Ne&&(p=f+`
|
|
1160
1160
|
`+Ne+`
|
|
1161
1161
|
`)}catch(Ae){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",Ae.message)}let m=uk(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
1165
|
`}let g=[{role:"system",content:p},...H],y=new oo("Thinking...");y.start();let w=H.length===1,v=w?Xk().catch(()=>null):Promise.resolve(null),M=w?Kv(typeof t=="string"?t:"").catch(()=>null):Promise.resolve(null),C=pt(),[{messages:S,compressed:O,compacted:D,tokensRemoved:K},V,X]=await Promise.all([Mv(g,C),v,M]),B=Vt(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=Gv(typeof t=="string"?t:"");Ae&&(R=[R[0],{role:"user",content:Ae.user},{role:"assistant",content:Ae.assistant},...R.slice(1)])}if(Vt(R,pt()).percentage>=65){let{messages:Ne,tokensRemoved:qe}=
|
|
1167
|
-
`),Ne=
|
|
1166
|
+
${X}`},{role:"assistant",content:"Understood \u2014 I have the server context. Proceeding with the task."},...R.slice(1)]),w){let Ae=Gv(typeof t=="string"?t:"");Ae&&(R=[R[0],{role:"user",content:Ae.user},{role:"assistant",content:Ae.assistant},...R.slice(1)])}if(Vt(R,pt()).percentage>=65){let{messages:Ne,tokensRemoved:qe}=un(R,pt());qe>0&&(R=Ne,console.log(`${$.dim} [pre-flight compress \u2014 ${qe} tokens freed, now ${Math.round(Vt(R,pt()).percentage)}% used]${$.reset}`))}let $e=0,be=0,fe=0,pe=0,xe=0,me=9,he=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(!ot){let Ae=H.filter(qe=>qe.role==="user"||qe.role==="tool").map(qe=>typeof qe.content=="string"?qe.content:"").join(`
|
|
1167
|
+
`),Ne=dl(Ae);Ne&&(ot=!0,kt=Ne.slice(0,120),W(`${$.yellow} \u26A1 Root cause in briefing: ${kt} \u2014 fix phase active from start (read budget: 3)${$.reset}`))}!ot&&!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&&(Te=Uv(),Te&&(ao=Fv(Re)?.id||"coding",Xe="plan",kn=pl("plan",ao),sa=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 Cv(gk),se=Cl,we=3,Ce=5,tt=El,nt=5,Tn=8,wa=Tl,ba=Te?6:4,i$=Te?10:7,du=pr,a$=Te?5:3,fu=Te?8:5,c$=Rl,l$=Te?4:3,u$=Te?6:4,d$=3,f$=4,Er=xs,p$=Te?3:2,m$=Te?5:3,ho=Te?6:4,h$=25,Hn=0,g$=6,$$=10,Kn=0,pu=5,Gn=0,y$=2,w$=3,_a=0,go=10,b$=16,mu=o.investigationCap,Ve,nn=Te?hs(Xe):hl,xa=0,hu=3,va=!1;e:for(;;){for(va=!1,Ve=0;Ve<nn&&!Hi()?.aborted;Ve++){{let _=pt(),b=Vt(R,_),re=x===0?65:78;if(b.percentage>=re){let{messages:I,tokensRemoved:F}=un(R,_,x===0);if(F>0&&(R=I,F>50&&console.log(`${$.dim} [auto-compressed \u2014 ~${F} tokens freed, now ${Math.round(Vt(R,_).percentage)}%]${$.reset}`),Bt&&A.size>=3)){let ce=[...A].map(ye=>ye.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(Nt&&!ot&&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}`)}Nt||(lr=0);let Ne=!0;x>0&&nk();let qe=null;if(u&&u.isActive())u._paused&&u.resume();else if(!u){let _,b=sk();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,It="",Ts=!1,ct=new ok,sn,ka=Date.now(),Tr=!1,Sa=new AbortController,gu=setInterval(()=>{let _=Date.now()-ka;if(_>=ll)ct._clearCursorLine(),W(`${$.yellow} \u26A0 Stream stale for ${Math.round(_/1e3)}s \u2014 aborting and retrying${$.reset}`),Sa.abort();else if(_>=Sh&&!Tr){Tr=!0,ct._clearCursorLine();let b=ea.fast?.[ro()],re=fe>0?` (retry ${fe+1}/${Bi})`:"",I=Math.round((ll-_)/1e3);W(`${$.yellow} \u26A0 No tokens received for ${Math.round(_/1e3)}s \u2014 waiting...${re}${$.reset}`),b&&b!==fn()?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="",mn=null;try{let _=Ph(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=>Nh.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=Hi(),ce=new AbortController;F&&F.addEventListener("abort",()=>ce.abort(),{once:!0}),Sa.signal.addEventListener("abort",()=>ce.abort(),{once:!0}),sn=await gh(R,I,{signal:ce.signal,...kn?{model:kn}:{},onThinkingToken:()=>{ka=Date.now(),Tr=!1,pn?.onThinkingToken&&pn.onThinkingToken()},onToken:G=>{if(ka=Date.now(),Tr=!1,pn?.onToken){pn.onToken(G),It+=G;return}if(It+=G,!Ts&&It.length>400&&It.length%250<G.length+1){let ye=ml(It,3);ye.truncated&&(Ts=!0,ct._clearCursorLine?.(),W(`${$.yellow} \u26A0 LLM stream loop detected (${ye.repeatCount}\xD7 repeated) \u2014 suppressing display${$.reset}`))}Ts||(jt+=G,process.stdout.isTTY?mn||(mn=setTimeout(()=>{jt&&ct&&ct.push(jt),jt="",mn=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(gu),mn&&(clearTimeout(mn),mn=null),jt&&ct&&(ct.push(jt),jt=""),u&&!u._paused&&u.pause(),qe&&qe.stop(),ct.stopCursor(),Sa.signal.aborted&&!Hi()?.aborted){if(fe++,fe>Bi){if(pe<1){pe++,so("Stale retries exhausted \u2014 last-resort force-compress...",$.yellow);let ye=pt(),{messages:U,tokensRemoved:Y}=un(R,ye);R=U,Y>50&&W(`${$.dim} [force-compressed \u2014 ~${Y} tokens freed]${$.reset}`),fe=0,Ve--;continue}u&&(u.stop(),u=null);let G=await Vk();if(G.action==="quit"){l(null),Qe(x,E,A,T,L),Ze(H);break}G.action==="switch"&&(vh(`${G.provider}:${G.model}`),console.log(`${$.green} \u2713 Switched to ${G.provider}:${G.model}${$.reset}`)),fe=0,Ve--;continue}let F=fe===1?3e3:5e3;if(fe>=1&&he<1){he++,so(`Stale retry ${fe}/${Bi} \u2014 force-compressing before retry...`,$.yellow);let G=pt(),{messages:ye,tokensRemoved:U}=un(R,G,!0);if(R=ye,U>0&&U>50&&W(`${$.dim} [force-compressed \u2014 ~${U} tokens freed]${$.reset}`),Mk){let Y=ea.fast?.[ro()];Y&&Y!==fn()&&(vh(`${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 ${fe}/${Bi} \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): ${fn?fn():"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(pe<3&&xe<me){pe++,xe++;let F=x===0&&pe===1,ce=F||pe===3||he>0;if(F){pe=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 ${pe}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${pe}/3)`,$.yellow);let G=pt(),{messages:ye,tokensRemoved:U}=un(R,G,ce);R=ye,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:ye}=Rt(),U=Rt().estimateMessagesTokens(G),Y=Rt().estimateMessagesTokens(R);if(U<Y){let z=[],ee=H.filter(ie=>ie.role==="assistant"&&typeof ie.content=="string"&&ie.content.trim().length>30).slice(-5).map(ie=>ie.content.trim().slice(0,300).replace(/\n+/g," "));ee.length>0&&z.push(`Key findings:
|
|
1168
1168
|
`+ee.map(ie=>`- ${ie}`).join(`
|
|
1169
1169
|
`));let te=H.filter(ie=>ie.role==="tool"&&typeof ie.content=="string"&&!ie.content.startsWith("BLOCKED:")&&ie.content.trim().length>10).slice(-5).map(ie=>ie.content.trim().split(`
|
|
1170
1170
|
`).slice(0,8).join(`
|
|
1171
1171
|
`).slice(0,500));if(te.length>0&&z.push(`Tool results summary:
|
|
1172
1172
|
`+te.map(ie=>`- ${ie}`).join(`
|
|
1173
|
-
`)),A.size>0){let ie=[...A].map(He=>He.split("/").slice(-2).join("/")).join(", ");z.unshift(`Already modified: ${ie} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(T.size>0){let ie=[...T].map(He=>He.split("/").slice(-2).join("/")).join(", ");z.push(`Files already investigated: ${ie}`)}let le=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(le,JSON.stringify({filesWritten:[...A].map(ie=>ie.split("/").slice(-2).join("/")),filesRead:[...T].map(ie=>ie.split("/").slice(-2).join("/")),isCreationTask:Bt,wipeNumber:cr+1,timestamp:Date.now()},null,2)),z.push(`Session checkpoint: ${le} \u2014 read it for exact file list`)}catch{}let _e=0;{let He=((typeof
|
|
1174
|
-
${JSON.stringify(
|
|
1173
|
+
`)),A.size>0){let ie=[...A].map(He=>He.split("/").slice(-2).join("/")).join(", ");z.unshift(`Already modified: ${ie} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(T.size>0){let ie=[...T].map(He=>He.split("/").slice(-2).join("/")).join(", ");z.push(`Files already investigated: ${ie}`)}let le=require("os").tmpdir()+"/nex-session-checkpoint.json";try{require("fs").writeFileSync(le,JSON.stringify({filesWritten:[...A].map(ie=>ie.split("/").slice(-2).join("/")),filesRead:[...T].map(ie=>ie.split("/").slice(-2).join("/")),isCreationTask:Bt,wipeNumber:cr+1,timestamp:Date.now()},null,2)),z.push(`Session checkpoint: ${le} \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 Et=[...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:Et?Et.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 ie={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
|
|
1175
1175
|
${z.join(`
|
|
1176
1176
|
`)}
|
|
1177
1177
|
Continue implementing the fixes based on these findings.`};G.push(ie)}if(cr>=3){let ie=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.${ie?$.dim+ie:""}${$.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),
|
|
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.${ie?$.dim+ie:""}${$.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),wl=!0,Xi=A.size,Ji=!1,Ut=0,j=0;for(let[ie,He]of xs){let lt=He?.count??He??0;Th(xs,ie,lt>=2?lt:1)}for(let[ie]of Dn)gs(xs,ie)<2&&Dn.delete(ie);ys.clear(),vs.clear(),Bt&&Qt>0&&(Zt=!0,W(`${$.cyan} \u26A1 Post-wipe creation guard: cap pre-fired (${Qt} edits already made)${$.reset}`));for(let[ie]of pr)Th(pr,ie,fu-1);if(so(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${Y-U} tokens freed)`,$.yellow),cr>=1){let ie=[...xs.entries()].filter(([,Et])=>Et>=ho).map(([Et])=>Et.split("/").slice(-1)[0]),He=ie.length>0?`
|
|
1179
1179
|
|
|
1180
|
-
Files already at read cap \u2014 use grep_search instead: ${ie.join(", ")}`:"",Kt={role:"user",content:Nt&&!ot?"[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)}pe=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($e++,$e>
|
|
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: ${ie.join(", ")}`:"",Kt={role:"user",content:Nt&&!ot?"[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)}pe=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($e++,$e>al){console.log(`${$.red} Rate limit: max retries (${al}) 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,$e-1),12e4),ce=new oo(`Rate limit \u2014 waiting ${Math.round(F/1e3)}s (retry ${$e}/${al})`);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>cl){console.log(`${$.red} Network error: max retries (${cl}) 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}/${cl}). 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(gu),$e=0,be=0,Es&&(u&&!u._paused&&u.pause(),qe&&qe.stop()),mn&&(clearTimeout(mn),mn=null),jt&&ct&&(ct.push(jt),jt=""),It&&ct.flush(),be=0,fe=0,sn&&sn.usage){let _=sn.usage.prompt_tokens||0,b=sn.usage.completion_tokens||0;wh(ro(),fn(),_,b),d+=_+b,u&&u.setStats({tokens:d})}else if(sn&&!sn.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=_h(_),re=_h(sn.content||It||"");wh(ro(),fn(),b,re),d+=b+re,u&&u.setStats({tokens:d})}let{content:$u,tool_calls:hn}=sn,Rr=ml($u||""),yu=Rr.truncated?Rr.text:$u;Rr.truncated&&W(`${$.yellow} \u26A0 LLM output loop detected (${Rr.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${$.reset}`);let Cr=bk(yu||""),gn=Cr.truncated?Cr.text:yu;Cr.truncated&&W(`${$.yellow} \u26A0 LLM output loop detected (${Cr.repeatCount}\xD7 repeated window) \u2014 response truncated${$.reset}`);let Ea={role:"assistant",content:gn||""};if(hn&&hn.length>0&&(Ea.tool_calls=hn),H.push(Ea),R.push(Ea),!ot&&gn&&hn&&hn.length>0){let _=dl(gn);if(_){ot=!0,kt=_.slice(0,120),dn=0,Zt=!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(!hn||hn.length===0){let _=(gn||"").trim().length>0||It.trim().length>0,b=!1;if(Nt&&_&&(Wi>=2?W(`${$.yellow} \u26A0 SSH permanently blocked after ${Wi} storm warnings \u2014 no further SSH calls allowed${$.reset}`):(Nt=!1,Ut=go-4,b=!0)),b&&_){let I=(gn||"").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<hl-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((gn||"").slice(0,600)))if(wl&&ws<=0||Nt){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(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,nn=hs("implement");continue}}if(Te&&_){let I=(gn||It||"").trim();if(Xe==="plan"){let F=rr("implement",I);if(F){H.push(F),R.push(F),Ve=0,nn=hs("implement");continue}}else if(Xe==="implement"&&A.size>0){let F=H.find(ye=>ye.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,nn=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",
|
|
1184
|
+
Fix the identified issues. This is the final attempt.`};Xe="implement",kn=pl("implement",ao),H.push(G),R.push(G),Ve=0,nn=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(Gi++,Gi>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 (${
|
|
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 (${Gi}/2): no files read \u2014 forcing investigation${$.reset}`);continue}if(fr()&&_){let I=(gn||It||"").trim();Qv(I),Pk(I);let F=ek(I);if(F.length>0){let ce=H.find(Y=>Y.role==="user"),G=typeof ce?.content=="string"?ce.content.slice(0,120):"Task";tk(G,F);let ye=F.length===1?"step":"steps",U=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:Y,startExecution:z,setPlanMode:ee}=ln();process.stdout.write(`
|
|
1187
1187
|
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${F.length} ${ye})${$.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,le=await new Promise(_e=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",ie=>{try{process.stdin.setRawMode(te||!1)}catch{}let He=ie.toString().toLowerCase()[0]||"\r";_e(He)})});if(process.stdout.write(`
|
|
1188
|
-
`),le==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(le==="e")console.log(`${$.yellow}Type /plan edit to open in editor, or give feedback.${$.reset}`);else if(Y()){z(),ee(!1)
|
|
1188
|
+
`),le==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(le==="e")console.log(`${$.yellow}Type /plan edit to open in editor, or give feedback.${$.reset}`);else if(Y()){z(),ee(!1),$l(),console.log(`${$.green}${$.bold}Approved!${$.reset} Executing ${F.length} ${ye}...`);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} ${ye} 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} ${ye} 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:ye,setPlanMode:U}=ln();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
|
-
`),z==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(G()){ye(),U(!1)
|
|
1195
|
+
`),z==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(G()){ye(),U(!1),$l(),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()||
|
|
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),gh(H);return}x++,na++,x>=1&&(Ne=!1);for(let _ of mn){let b=_.function.name;E.set(b,(E.get(b)||0)+1)}if(x>=30&&!Rh){Rh=!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 ke=await Promise.all(mn.map(_=>Lk(_)));{let _=Vt(R,pt()),b=_.percentage,oe=ke.some(G=>G.canExecute&&G.fnName==="read_file"&&!G.args?.line_end),I=ke.filter(G=>G.canExecute&&G.fnName==="read_file"&&G.args?.path&&gs(Sr,G.args.path)>=1&&!G.args?.line_start).map(G=>G.args.path.split("/").slice(-2).join("/")),F=I.length>0;if(b>=70&&oe&&ba<70||b>=85&&ba<85||F){ba=b;let G=b>=85?"URGENT":"WARNING",ye;F?(G="WARNING",ye=`Full-file read of ${I.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):oe?ye=`Unbounded read at ${Math.round(b)}% context \u2014 use line_start/line_end to avoid overflow.`:ye="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). ${ye}`};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 Ea=new Map;for(let _ of ke){if(!_.canExecute||_.fnName!=="read_file")continue;let b=_.args?.path;if(!b)continue;let oe=gs(Sr,b),I=Ea.get(b)||0,F=oe+I,ae=_.args?.line_start!=null,G=ys.get(b)||0,ye=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(ye&&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(ye&&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 ie=Math.max(Y,le),He=Math.min(z,_e);if(He>ie){let lt=He-ie,Kt=z-Y||1,Et=_e-le||1,gn=lt/Et>=.7&</Kt<.7;if(!(z-Y<=h$)&&(lt/Kt>=.7||lt/Et>=.7)){let Rs=b.split("/").slice(-2).join("/"),xu=`${b}:${Y}-${z}`,Cs=(ea.get(xu)||0)+1;if(ea.set(xu,Cs),W(gn?`${$.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 vu={role:"user",content:gn?`[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(vu),R.push(vu)}_.canExecute=!1,_.errorResult={role:"tool",content:gn?`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&&Ea.set(b,(Ea.get(b)||0)+1)}if(jn>=3)for(let _ of ke)_.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 ke){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 ke)_.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 ke){if(!_.canExecute||_.fnName!=="write_file")continue;let b=_.args?.path,oe=_.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(oe,"utf8"),ye=ae>0?G/ae:1;if(ye<.6&&ae>200){let U=b.split("/").slice(-2).join("/");console.log(`${$.red} \u2716 write_file shrink guard: "${U}" would shrink to ${Math.round(ye*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(ye*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 yu=new Map;for(let _ of ke){if(!_.canExecute||_.fnName!=="grep")continue;let b=_.args?.path;if(!b)continue;let oe=yu.get(b)||0,I=gs(uu,b)+oe;if(I>=du){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&&yu.set(b,oe+1)}let _$=5,wu=new Map;for(let _ of ke){if(!_.canExecute||_.fnName!=="ssh_exec")continue;let oe=(_.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),I=wu.get(oe)||0,F=gs(tt,oe)+I;F>=_$&&(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&&wu.set(oe,I+1)}if(Nt){let _=ke.filter(I=>I.canExecute&&I.fnName==="ssh_exec"),b=ke.some(I=>I.canExecute&&I.fnName!=="ssh_exec"),oe=k&&j<3;if(_.length>0&&!b&&oe&&Yi<1)Nt=!1,Yi++,Ut=Math.max(0,go-2),W(`${$.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${Yi}/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&&!Nt){for(let _ of ke)if(_.canExecute&&["bash","read_file","find_files"].includes(_.fnName)){j++;{let b=pt(),{messages:oe}=ln(R,b);R=oe}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&&Zt&&Bt&&Qt>=1){let _=["read_file","grep","search_files","glob","list_directory","find_files"];for(let b of ke)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 _=ke.filter(b=>b.canExecute).length;if(_>0&&(ws-=_,ws<0))if(!Xi&&A.size>zi){Xi=!0,ws=5,W(`${$.green} \u2713 Post-wipe progress detected (${A.size-zi} 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 oe of ke)oe.canExecute&&(oe.canExecute=!1,oe.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:oe.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 x$=new Set(["edit_file","write_file","bash","ssh_exec","ask_user","spawn_agents","browser_click","browser_fill","browser_open"]);for(let _ of ke){if(!_.canExecute||x$.has(_.fnName))continue;let b=JSON.stringify(_.args||{}),oe=`${_.fnName}|${b}`,I=gs(ta,oe);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(ta,oe)}let $o=u?{skipSpinner:!0,skipSummaries:!0}:{},v$=ke.some(_=>_.fnName==="ask_user"),bu=!$o.skipSummaries&&!Ne,Cr=null;bu&&!v$?(Ne=!0,$o.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(Fi(ke,x,!1,"blink")),Cr=!0):fn||process.stdout.write(Fi(ke,x,!1)+`
|
|
1202
|
-
`)):
|
|
1203
|
-
`)),!$o.skipSummaries){let _=k$.filter((I,F)=>!(ke[F]&&ke[F].fnName==="ask_user"));for(let I of _)console.log(I);console.log("");let b=ke.filter(I=>I&&I.fnName!=="ask_user").map(I=>I.fnName),
|
|
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(
|
|
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===
|
|
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===Vi?_s++:(Vi=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 Vi="",_s=0}if(b.fnName==="bash"&&b.canExecute&&!dl&&b.args?.command){let U=sn[_]?.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"))){dl=!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(dl&&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(ya,U);if(Y===wa){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>=i$){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(uu,b.args.path),ee=gs(Sr,b.args.path)>=1;if(z===(ee?1:a$)){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(c$,U);if(Y===l$){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>=u$){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===f$){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===d$){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&&oe.includes('"valid":true')){{let Y=pt();if(Vt(R,Y).percentage>=60){let{messages:ee,tokensRemoved:te}=ln(R,Y);te>0&&(R=ee,console.log(`${$.dim} [pre-stop-compress \u2014 ~${te} tokens freed before STOP injection, now ${Math.round(Vt(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(oe.startsWith("BLOCKED:")){if(Kn++,Kn>=fu){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,xa=!0;else if(Hn++,Hn===g$){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(`${$.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(Sr,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===p$){{let le=pt();if(Vt(R,le).percentage>=60){let{messages:ie}=ln(R,le);R=ie}}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>=m$){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=(oe.match(/\bStatus: done\b/g)||[]).length;if((oe.match(/\bStatus: truncated\b/g)||[]).length>0&&U===0){if(Gn++,Gn===y$){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>=w$){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 sn)H.push(_),R.push(_);if(!ot)for(let _=0;_<sn.length;_++){if(!ke[_]||ke[_].fnName!=="ssh_exec")continue;let b=sn[_];if(!b||typeof b.content!="string")continue;let oe=ul(b.content);if(oe){ot=!0,kt=oe.slice(0,120),un=0,Zt=!1,xn=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;_<sn.length;_++){let b=ke[_];if(!b)continue;let oe=typeof sn[_]?.content=="string"?sn[_].content:"";if(b.fnName==="create_task"){let I=oe.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")&&!oe.startsWith("BLOCKED:")&&oe.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,ye]of hr){if(gr.has(G))continue;let U=ye.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}: ${ye.slice(0,60)}${$.reset}`))}}}{let _=pt();if(Vt(R,_).percentage>=78){let{messages:oe,tokensRemoved:I}=ln(R,_);I>0&&(R=oe,console.log(`${$.dim} [auto-compressed \u2014 ~${I} tokens freed, now ${Math.round(Vt(R,_).percentage)}%]${$.reset}`))}}let _u=Uk();if(_u){let _={role:"user",content:`[User note mid-run]: ${_u}`};H.push(_),R.push(_),console.log(`${$.cyan} \u270E Context added${$.reset}`)}}if(Ve>=tn){if(u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L),Ze(H),gh(H),Te&&Xe==="plan"){let Es=[...H].reverse().find(ct=>ct.role==="assistant"),It=typeof Es?.content=="string"?Es.content:"",Ts=rr("implement",It);if(Ts){H.push(Ts),R=[{role:"system",content:await xl()},...H],tn=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"&&_a<mu){if(A.size===0&&!xa){console.log(`${$.yellow} \u26A0 Max iterations reached with no progress. Stopping.${$.reset}`);break e}_a++,tn=20,console.log(`${$.dim} \u2500\u2500 auto-extending (+20 turns, ext ${_a}/${mu}) \u2500\u2500${$.reset}`);continue e}if(console.log(`
|
|
1207
|
-
${$.yellow}\u26A0 Max iterations reached.${$.reset}`),await
|
|
1208
|
-
`),await t(c,i,d)}catch(u){if(n=u,!
|
|
1209
|
-
`),await t(c,i,f)}catch(p){if(n=p,!
|
|
1199
|
+
${getPlanContent()||sn.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")),ye=F&&!G?"npm install not yet run":ce?"pip install not yet run":null;ur=`[Previous session created ${A.size} files: ${I}`+(ye?` \u2014 ${ye}`:"")+". Use this context to answer follow-up questions without re-reading files.]"}if(Bt&&!bl&&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 le=Array.isArray(te.tool_calls)?te.tool_calls:[],_e=Array.isArray(te.content)?te.content.filter(ie=>ie?.type==="tool_use"):[];return[...le,..._e]}).filter(te=>{let le=te.function?.name||te.name||"";return le==="bash"||le==="Bash"}).map(te=>{try{let le=te.function?.arguments??te.input??{};return(typeof le=="string"?JSON.parse(le):le)?.command||""}catch{return""}}),ye=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&&!ye||I&&!ce&&!U||z){bl=!0;let te=[];F&&!ye&&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 le=`[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:le}),R.push({role:"user",content:le});continue}}if(x>0&&!n._isSummaryTurn&&Bv(gn))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 gh(F,[],{}))?.content||"").trim();G&&(console.log(`
|
|
1201
|
+
${G}`),H.push({role:"user",content:I},{role:"assistant",content:G}))}catch{}Ze(H),$h(H);return}x++,sa++,x>=1&&(Ne=!1);for(let _ of hn){let b=_.function.name;E.set(b,(E.get(b)||0)+1)}if(x>=30&&!Ch){Ch=!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 ke=await Promise.all(hn.map(_=>Lk(_)));{let _=Vt(R,pt()),b=_.percentage,re=ke.some(G=>G.canExecute&&G.fnName==="read_file"&&!G.args?.line_end),I=ke.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&&_a<70||b>=85&&_a<85||F){_a=b;let G=b>=85?"URGENT":"WARNING",ye;F?(G="WARNING",ye=`Full-file read of ${I.join(", ")} already done \u2014 use line_start/line_end for specific sections instead.`):re?ye=`Unbounded read at ${Math.round(b)}% context \u2014 use line_start/line_end to avoid overflow.`:ye="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). ${ye}`};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 Ta=new Map;for(let _ of ke){if(!_.canExecute||_.fnName!=="read_file")continue;let b=_.args?.path;if(!b)continue;let re=gs(Er,b),I=Ta.get(b)||0,F=re+I,ce=_.args?.line_start!=null,G=ys.get(b)||0,ye=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(ye&&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(ye&&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 ie=Math.max(Y,le),He=Math.min(z,_e);if(He>ie){let lt=He-ie,Kt=z-Y||1,Et=_e-le||1,$n=lt/Et>=.7&</Kt<.7;if(!(z-Y<=h$)&&(lt/Kt>=.7||lt/Et>=.7)){let Rs=b.split("/").slice(-2).join("/"),vu=`${b}:${Y}-${z}`,Cs=(ta.get(vu)||0)+1;if(ta.set(vu,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 ku={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(ku),R.push(ku)}_.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&&Ta.set(b,(Ta.get(b)||0)+1)}if(jn>=3)for(let _ of ke)_.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 ke){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 ke)_.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 ke){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"),ye=ce>0?G/ce:1;if(ye<.6&&ce>200){let U=b.split("/").slice(-2).join("/");console.log(`${$.red} \u2716 write_file shrink guard: "${U}" would shrink to ${Math.round(ye*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(ye*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 wu=new Map;for(let _ of ke){if(!_.canExecute||_.fnName!=="grep")continue;let b=_.args?.path;if(!b)continue;let re=wu.get(b)||0,I=gs(du,b)+re;if(I>=fu){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&&wu.set(b,re+1)}let _$=5,bu=new Map;for(let _ of ke){if(!_.canExecute||_.fnName!=="ssh_exec")continue;let re=(_.args?.command||"").replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),I=bu.get(re)||0,F=gs(tt,re)+I;F>=_$&&(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&&bu.set(re,I+1)}if(Nt){let _=ke.filter(I=>I.canExecute&&I.fnName==="ssh_exec"),b=ke.some(I=>I.canExecute&&I.fnName!=="ssh_exec"),re=k&&j<3;if(_.length>0&&!b&&re&&zi<1)Nt=!1,zi++,Ut=Math.max(0,go-2),W(`${$.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${zi}/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&&!Nt){for(let _ of ke)if(_.canExecute&&["bash","read_file","find_files"].includes(_.fnName)){j++;{let b=pt(),{messages:re}=un(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&&Zt&&Bt&&Qt>=1){let _=["read_file","grep","search_files","glob","list_directory","find_files"];for(let b of ke)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 _=ke.filter(b=>b.canExecute).length;if(_>0&&(ws-=_,ws<0))if(!Ji&&A.size>Xi){Ji=!0,ws=5,W(`${$.green} \u2713 Post-wipe progress detected (${A.size-Xi} 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 ke)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 x$=new Set(["edit_file","write_file","bash","ssh_exec","ask_user","spawn_agents","browser_click","browser_fill","browser_open"]);for(let _ of ke){if(!_.canExecute||x$.has(_.fnName))continue;let b=JSON.stringify(_.args||{}),re=`${_.fnName}|${b}`,I=gs(na,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(na,re)}let $o=u?{skipSpinner:!0,skipSummaries:!0}:{},v$=ke.some(_=>_.fnName==="ask_user"),_u=!$o.skipSummaries&&!Ne,Ar=null;_u&&!v$?(Ne=!0,$o.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(Ui(ke,x,!1,"blink")),Ar=!0):pn||process.stdout.write(Ui(ke,x,!1)+`
|
|
1202
|
+
`)):_u&&(Ne=!0,$o.skipSpinner=!0),u&&u._paused&&u.resume();let Or=null;if(Ar&&process.stdout.isTTY&&ke.some(b=>b.canExecute&&(b.fnName==="bash"||b.fnName==="ssh_exec"))){let b=Date.now();Or=setInterval(()=>{let re=Math.round((Date.now()-b)/1e3);re>=3&&process.stdout.write(`\r\x1B[2K${Ui(ke,x,!1,"blink")} ${$.dim}[${re}s]${$.reset}`)},1e3)}let{results:on,summaries:k$}=await qk(ke,!0,{...$o,skipSummaries:!0});if(Or&&(clearInterval(Or),Or=null),Ar&&(Ar=null,process.stdout.write(`\r\x1B[2K${Ui(ke,x,!1)}
|
|
1203
|
+
`)),!$o.skipSummaries){let _=k$.filter((I,F)=>!(ke[F]&&ke[F].fnName==="ask_user"));for(let I of _)console.log(I);console.log("");let b=ke.filter(I=>I&&I.fnName!=="ask_user").map(I=>I.fnName),re=ae.record(0,b,T,A);re&&$k(re)}for(let _ of ke){if(_.canExecute||!_.errorResult)continue;let b=typeof _.errorResult.content=="string"?_.errorResult.content:"";if((b.startsWith("BLOCKED:")||b.startsWith("PLAN MODE:"))&&(Kn++,Kn>=pu)){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;_<ke.length;_++){let b=ke[_];if(!b.canExecute)continue;let re=on[_].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===we){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>=Ce){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)?(dn=0,Zt=!1,vn=0,Qt++):U.includes(b.fnName)&&(dn++,Zt&&vn++);let z=o.postEditCap,ee=Te&&Xe==="implement"?Math.min(mu,6):mu,te=ot?3:Bt?Qt>0?2:4:Qt>0?z:ee,le=3;if(!Te&&Zt&&(ot||Bt&&Qt>=1||vn>=le)&&U.includes(b.fnName)){let ie=ot?`root cause already identified (${kt})`:vn>=le?`${dn} consecutive reads without an edit`:`${Qt} file edit(s) already made`;W(`${$.red} \u2716 Blocked read-only tool: cap fired, ${ie}${$.reset}`),b.canExecute=!1,b.errorResult={role:"tool",content:ot?`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>=le?`BLOCKED: You have read ${dn} 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: ${Qt} 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(dn>=te&&!Zt){if(Zt=!0,W(`${$.yellow} \u26A0 Investigation cap: ${dn} 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:"",Et=rr("implement",Kt);Et&&(H.push(Et),R.push(Et),Ve=0,nn=hs("implement"))}let ie;ot?ie=`[SYSTEM] Root cause was already identified (${kt}). Edit the file now \u2014 do not read more files.`:Nt?ie="[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.":ie="[SYSTEM] You have read enough files. Now implement your fix using edit_file.";let He={role:"user",content:ie};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(tt,U);if(Y===nt){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>=Tn){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=(on[_]?.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===Vi?bs++:(Vi=z,bs=1),bs===3&&!Nt){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 Vi="",bs=0}if(Ut>=b$){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}=un(R,z);R=ee}Nt=!0,Wi++,W(`${$.yellow} \u26A0 SSH storm warning (#${Wi}): ${Ut} consecutive ssh_exec calls \u2014 blocking further SSH${$.reset}`);let Y={role:"user",content:ot?`[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=(on[_]?.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===Zi?_s++:(Zi=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 Zi="",_s=0}if(b.fnName==="bash"&&b.canExecute&&!fl&&b.args?.command){let U=on[_]?.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"))){fl=!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(fl&&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(wa,U);if(Y===ba){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>=i$){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(du,b.args.path),ee=gs(Er,b.args.path)>=1;if(z===(ee?1:a$)){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(c$,U);if(Y===l$){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>=u$){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===f$){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===d$){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 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(Vt(R,Y).percentage>=60){let{messages:ee,tokensRemoved:te}=un(R,Y);te>0&&(R=ee,console.log(`${$.dim} [pre-stop-compress \u2014 ~${te} tokens freed before STOP injection, now ${Math.round(Vt(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>=pu){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,va=!0;else if(Hn++,Hn===g$){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(`${$.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===p$){{let le=pt();if(Vt(R,le).percentage>=60){let{messages:ie}=un(R,le);R=ie}}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>=m$){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===y$){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>=w$){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 on)H.push(_),R.push(_);if(!ot)for(let _=0;_<on.length;_++){if(!ke[_]||ke[_].fnName!=="ssh_exec")continue;let b=on[_];if(!b||typeof b.content!="string")continue;let re=dl(b.content);if(re){ot=!0,kt=re.slice(0,120),dn=0,Zt=!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;_<on.length;_++){let b=ke[_];if(!b)continue;let re=typeof on[_]?.content=="string"?on[_].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,ye]of hr){if(gr.has(G))continue;let U=ye.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}: ${ye.slice(0,60)}${$.reset}`))}}}{let _=pt();if(Vt(R,_).percentage>=78){let{messages:re,tokensRemoved:I}=un(R,_);I>0&&(R=re,console.log(`${$.dim} [auto-compressed \u2014 ~${I} tokens freed, now ${Math.round(Vt(R,_).percentage)}%]${$.reset}`))}}let xu=Uk();if(xu){let _={role:"user",content:`[User note mid-run]: ${xu}`};H.push(_),R.push(_),console.log(`${$.cyan} \u270E Context added${$.reset}`)}}if(Ve>=nn){if(u&&(u.stop(),u=null),l(null),Qe(x,E,A,T,L),Ze(H),$h(H),Te&&Xe==="plan"){let Es=[...H].reverse().find(ct=>ct.role==="assistant"),It=typeof Es?.content=="string"?Es.content:"",Ts=rr("implement",It);if(Ts){H.push(Ts),R=[{role:"system",content:await vl()},...H],nn=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"&&xa<hu){if(A.size===0&&!va){console.log(`${$.yellow} \u26A0 Max iterations reached with no progress. Stopping.${$.reset}`);break e}xa++,nn=20,console.log(`${$.dim} \u2500\u2500 auto-extending (+20 turns, ext ${xa}/${hu}) \u2500\u2500${$.reset}`);continue e}if(console.log(`
|
|
1207
|
+
${$.yellow}\u26A0 Max iterations reached.${$.reset}`),await Oh(" Continue for 20 more turns?")){nn=20;continue e}console.log(`${$.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${$.reset}`)}break e}}Dh.exports={processInput:Zk,clearConversation:Hk,getConversationLength:Gk,getConversationMessages:Yk,setConversationMessages:zk,setAbortSignalGetter:xk,setMaxIterations:_k,invalidateSystemPromptCache:$l,clearToolFilterCache:Ak,getCachedFilteredTools:Ph,buildSystemPrompt:vl,getProjectContextHash:Lh,buildUserContent:Mh,detectAndTruncateLoop:ml,injectMidRunNote:Fk,resetSessionTracking:jh}});var je=Q((AR,Wh)=>{var{OllamaProvider:Qk}=Zu(),{OpenAIProvider:eS}=nd(),{AnthropicProvider:tS}=id(),{GeminiProvider:nS}=ud(),{LocalProvider:sS}=pd(),{checkBudget:oS}=qs(),Nl={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"}},Al=(process.env.OLLAMA_FALLBACK_CHAIN||"").split(",").map(t=>t.trim()).filter(Boolean),Fh={};for(let[t,e]of Object.entries(Nl))for(let n of Object.values(e))Fh[n]=t;function Ol(t,e){let n=Fh[t];return n&&Nl[n][e]||t}var rt={},St=null,Je=null,$r=[];function Wt(){if(Object.keys(rt).length>0)return;co("ollama",new Qk),co("openai",new eS),co("anthropic",new tS),co("gemini",new nS),co("local",new sS);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;rt[t]?(St=t,Je=e||rt[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){rt[t]=e}function rS(t){return Wt(),rt[t]||null}function Ml(){return Wt(),rt[St]||null}function iS(){return Wt(),St}function aS(){return Wt(),Je}function cS(){Wt();let t=Ml();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 Uh(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(rt[n]||["ollama","openai","anthropic","gemini","local"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function lS(t){Wt();let{provider:e,model:n}=Uh(t);if(e){let s=rt[e];return s&&(s.getModel(n)||e==="local"||e==="ollama")?(St=e,Je=n,oa(),!0):!1}let o=Ml();if(o&&o.getModel(n))return Je=n,oa(),!0;for(let[s,r]of Object.entries(rt))if(r.getModel(n))return St=s,Je=n,oa(),!0;return!1}function oa(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Se();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Rt();t()}catch{}}function uS(){Wt();let t=new Set;for(let e of Object.values(rt))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function dS(){return Wt(),Object.entries(rt).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===St&&n.id===Je}))}))}function fS(){Wt();let t=[];for(let[e,n]of Object.entries(rt)){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 pS(t){$r=Array.isArray(t)?t:[]}function mS(){return[...$r]}function qh(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 Bh(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=rt[i];if(!c||!c.isConfigured())continue;s++;let l=oS(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?Ol(Je,i):Je;return u&&d!==Je&&process.stderr.write(` [fallback: ${i}:${d}]
|
|
1208
|
+
`),await t(c,i,d)}catch(u){if(n=u,!qh(u)||r>=e.length-1)throw u;if(i==="ollama"&&Al.length>0){let d=isFallback?Ol(Je,i):Je;for(let f of Al)if(f!==d)try{return process.stderr.write(` [ollama fallback: ${f}]
|
|
1209
|
+
`),await t(c,i,f)}catch(p){if(n=p,!qh(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 hS(t,e,n={}){return Wt(),Bh((o,s,r)=>o.stream(t,e,{model:r,signal:n.signal,...n}))}async function gS(t,e,n={}){if(Wt(),n.provider){let o=rt[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 Bh(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 $S(){Wt();let t=[];for(let[e,n]of Object.entries(rt))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function yS(){for(let t of Object.keys(rt))delete rt[t];St=null,Je=null,$r=[]}Wh.exports={registerProvider:co,getProvider:rS,getActiveProvider:Ml,getActiveProviderName:iS,getActiveModelId:aS,getActiveModel:cS,setActiveModel:lS,getModelNames:uS,parseModelSpec:Uh,listProviders:dS,listAllModels:fS,callStream:hS,callChat:gS,getConfiguredProviders:$S,setFallbackChain:pS,getFallbackChain:mS,resolveModelForProvider:Ol,MODEL_EQUIVALENTS:Nl,OLLAMA_FALLBACK_MODELS:Al,_reset:yS}});var Ll=Q((OR,Hh)=>{"use strict";var Sn=require("fs"),ra=require("path"),wS=require("readline"),Ee="\x1B[0m",ia="\x1B[1m",mt="\x1B[2m",aa="\x1B[33m",Pl="\x1B[36m",yr="\x1B[32m";function bS(t){return(e,n="")=>new Promise(o=>{let s=n?` ${mt}[${n}]${Ee}`:"";t.question(` ${Pl}${e}${s}${Ee}: `,r=>o(r.trim()||n))})}function wr(t,e){return new Promise(n=>{e&&e.pause(),process.stdout.write(` ${Pl}${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 _S({rl:t=null,force:e=!1}={}){if(!e){let p=
|
|
1213
|
-
`),console.log(` ${
|
|
1214
|
-
`),console.log(` ${yr}1)${Ee} ${
|
|
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 _S({rl:t=null,force:e=!1}={}){if(!e){let p=Sn.existsSync(ra.join(process.cwd(),".env"))||Sn.existsSync(ra.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||wS.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),s=bS(o),r=!e;console.log(),console.log(r?`${aa}${ia} \u2726 Welcome to nex-code! No configuration found.${Ee}`:`${Pl}${ia} \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
|
+
`),console.log(` ${ia}Which AI provider do you want to use?${Ee}
|
|
1214
|
+
`),console.log(` ${yr}1)${Ee} ${ia}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}
|
|
1216
1216
|
`);return}if(i==="1"){console.log(),console.log(`
|
|
1217
1217
|
${yr}Ollama Cloud${Ee} ${mt}(recommended): uses ollama.com API \u2014 flat-rate, 47+ models.${Ee}`),console.log(` ${mt}Get your API key at: https://ollama.com/settings/api-keys${Ee}
|
|
1218
1218
|
`);let p=await wr("OLLAMA_API_KEY (leave blank for local)",t),h=p?"https://ollama.com":await s("Ollama host","http://localhost:11434"),m=await s("Default model",p?"devstral-2:123b":"qwen3-coder");c.push("DEFAULT_PROVIDER=ollama",`DEFAULT_MODEL=${m}`,`OLLAMA_HOST=${h}`),p&&c.push(`OLLAMA_API_KEY=${p}`),process.env.DEFAULT_PROVIDER="ollama",process.env.DEFAULT_MODEL=m,process.env.OLLAMA_HOST=h,p&&(process.env.OLLAMA_API_KEY=p)}else if(i==="2"){console.log(),console.log(` ${mt}Get your key: https://console.anthropic.com/settings/keys${Ee}`);let p=await wr("ANTHROPIC_API_KEY",t);if(!p){n&&o.close(),console.log(`
|
|
1219
|
-
${
|
|
1219
|
+
${aa} No key entered \u2014 cancelled.${Ee}
|
|
1220
1220
|
`);return}let h=await s("Default model","claude-sonnet-4-6");c.push("DEFAULT_PROVIDER=anthropic",`DEFAULT_MODEL=${h}`,`ANTHROPIC_API_KEY=${p}`),process.env.DEFAULT_PROVIDER="anthropic",process.env.DEFAULT_MODEL=h,process.env.ANTHROPIC_API_KEY=p}else if(i==="3"){console.log(),console.log(` ${mt}Get your key: https://platform.openai.com/api-keys${Ee}`);let p=await wr("OPENAI_API_KEY",t);if(!p){n&&o.close(),console.log(`
|
|
1221
|
-
${
|
|
1221
|
+
${aa} No key entered \u2014 cancelled.${Ee}
|
|
1222
1222
|
`);return}let h=await s("Default model","gpt-4o");c.push("DEFAULT_PROVIDER=openai",`DEFAULT_MODEL=${h}`,`OPENAI_API_KEY=${p}`),process.env.DEFAULT_PROVIDER="openai",process.env.DEFAULT_MODEL=h,process.env.OPENAI_API_KEY=p}else if(i==="4"){console.log(),console.log(` ${mt}Get your key: https://aistudio.google.com/app/apikey${Ee}`);let p=await wr("GEMINI_API_KEY",t);if(!p){n&&o.close(),console.log(`
|
|
1223
|
-
${
|
|
1224
|
-
`);return}let h=await s("Default model","gemini-2.0-flash");c.push("DEFAULT_PROVIDER=gemini",`DEFAULT_MODEL=${h}`,`GEMINI_API_KEY=${p}`),process.env.DEFAULT_PROVIDER="gemini",process.env.DEFAULT_MODEL=h,process.env.GEMINI_API_KEY=p}if(console.log(),(await s("Add Perplexity key for grounded web search? (y/N)","n")).toLowerCase()==="y"){console.log(` ${mt}Get your key: https://www.perplexity.ai/settings/api${Ee}`);let p=await wr("PERPLEXITY_API_KEY",t);p&&(c.push(`PERPLEXITY_API_KEY=${p}`),process.env.PERPLEXITY_API_KEY=p)}console.log();let u=
|
|
1223
|
+
${aa} No key entered \u2014 cancelled.${Ee}
|
|
1224
|
+
`);return}let h=await s("Default model","gemini-2.0-flash");c.push("DEFAULT_PROVIDER=gemini",`DEFAULT_MODEL=${h}`,`GEMINI_API_KEY=${p}`),process.env.DEFAULT_PROVIDER="gemini",process.env.DEFAULT_MODEL=h,process.env.GEMINI_API_KEY=p}if(console.log(),(await s("Add Perplexity key for grounded web search? (y/N)","n")).toLowerCase()==="y"){console.log(` ${mt}Get your key: https://www.perplexity.ai/settings/api${Ee}`);let p=await wr("PERPLEXITY_API_KEY",t);p&&(c.push(`PERPLEXITY_API_KEY=${p}`),process.env.PERPLEXITY_API_KEY=p)}console.log();let u=ra.join(process.cwd(),".env"),d=(Sn.existsSync(u),"y"),f=await s(`Save to ${u}? (Y/n)`,d);if(n&&o.close(),f.toLowerCase()!=="n"){let p=Sn.existsSync(u)?Sn.readFileSync(u,"utf-8").trimEnd()+`
|
|
1225
1225
|
|
|
1226
|
-
`:"";
|
|
1226
|
+
`:"";Sn.writeFileSync(u,p+c.join(`
|
|
1227
1227
|
`)+`
|
|
1228
|
-
`);let h=
|
|
1229
|
-
`).some(g=>g.trim()===".env")||
|
|
1228
|
+
`);let h=ra.join(process.cwd(),".gitignore");Sn.existsSync(h)&&(Sn.readFileSync(h,"utf-8").split(`
|
|
1229
|
+
`).some(g=>g.trim()===".env")||Sn.appendFileSync(h,`
|
|
1230
1230
|
.env
|
|
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
|
-
`)}
|
|
1235
|
-
`))}function
|
|
1236
|
-
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,o=>`<${o.charCodeAt(0).toString(16).padStart(2,"0")}>`);
|
|
1237
|
-
`)}function
|
|
1234
|
+
`)}Hh.exports={runSetupWizard:_S}});var zh=Q((NR,Yh)=>{"use strict";var ca=require("fs"),{T:en,isDark:xS}=Yn(),Mt="\x1B[0m",vS=!xS,kS=process.env.FOOTER_DEBUG==="1"||process.env.FOOTER_DEBUG==="2",SS=process.env.FOOTER_DEBUG==="2",lo=null;function Fn(...t){kS&&(lo||(lo=ca.openSync("/tmp/footer-debug.log","w")),ca.writeSync(lo,t.join(" ")+`
|
|
1235
|
+
`))}function Kh(t,e){if(!SS||typeof e!="string")return;lo||(lo=ca.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
|
+
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,o=>`<${o.charCodeAt(0).toString(16).padStart(2,"0")}>`);ca.writeSync(lo,`${t}: ${n}
|
|
1237
|
+
`)}function Gh(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Il=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 en.footer_sep+"\u2500".repeat(e)+Mt;let i=` ${en.footer_divider}\xB7${Mt} `,c=[];n&&c.push(`${en.footer_model}${n}${Mt}`),o&&c.push(`${en.footer_branch}${o}${Mt}`),s&&c.push(`${en.footer_project}${s}${Mt}`);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`${en.footer_sep}${d}${Mt}${l}${en.footer_sep} ${g} ${Mt}${en.footer_mode}${r}${Mt}${en.footer_sep} \u2500\u2500${Mt}`}let f=Math.max(0,e-d.length-u-2),p="\u2500".repeat(f);return`${en.footer_sep}${d}${Mt}${l}${en.footer_sep} ${p}${Mt}`}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(vS)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 Kh("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(Kh("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
|
-
`);for(let C=0;C<v.length;C++){let S=
|
|
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)+Mt+"\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)+Mt+"\x1B[2K");let m=n._cols,g=e._prompt||"",y=
|
|
1239
|
+
`);for(let C=0;C<v.length;C++){let S=Gh(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)+Mt+"\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)+Mt+"\x1B[2K");let m=n._cols,g=e._prompt||"",y=Gh(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}}};Yh.exports={StickyFooter:Il}});var Vh=Q((MR,Jh)=>{var{C:We}=Fe(),{listProviders:ES,getActiveProviderName:TS,getActiveModelId:RS,setActiveModel:CS}=je();function Xh(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 AS(t){let e=ES(),n=TS(),o=RS(),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
|
|
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 AS(t){let e=ES(),n=TS(),o=RS(),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 Xh(t,s,{title:"Select Model"});return r?(CS(r),console.log(`${We.green}Switched to ${r}${We.reset}`),!0):(console.log(`${We.dim}Cancelled${We.reset}`),!1)}Jh.exports={pickFromList:Xh,showModelPicker:AS}});var Dl=Q((LR,rg)=>{var Zh=require("fs"),OS=require("path"),{atomicWrite:NS,withFileLockSync:MS}=An(),{callChat:Qh}=je(),{remember:PS,listMemories:PR,recall:LS}=cn(),jl=4,IS=`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:
|
|
@@ -1266,15 +1266,15 @@ Rules:
|
|
|
1266
1266
|
- value: concise actionable instruction, max 120 chars
|
|
1267
1267
|
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
1268
1268
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
1269
|
-
- Return ONLY the JSON, no markdown, no explanation`;function
|
|
1269
|
+
- Return ONLY the JSON, no markdown, no explanation`;function eg(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
|
|
1271
|
+
`)}async function tg(t){if(t.filter(s=>s.role==="user").length<jl)return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=eg(t);if(!n.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let o=[{role:"system",content:IS},{role:"user",content:`Conversation to analyze:
|
|
1272
1272
|
|
|
1273
|
-
${n}`}];try{let i=((await
|
|
1273
|
+
${n}`}];try{let i=((await Qh(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 ng(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=LS(s);i!==r&&(PS(s,r),e.push({key:s,value:r,action:i?"updated":"added"}))}return e}function sg(t){if(!t||t.length===0)return[];let e=OS.join(process.cwd(),"NEX.md");return MS(e,()=>{let n="";try{Zh.existsSync(e)&&(n=Zh.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
|
-
`),NS(e,s)),o})}async function jS(t){let e=await
|
|
1277
|
+
`),NS(e,s)),o})}async function jS(t){let e=await tg(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let n=ng(e.memories),o=sg(e.nex_additions);return{applied:n,nexAdded:o,summary:e.summary}}var DS=`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,43 +1308,43 @@ 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
|
|
1311
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function og(t){if(t.filter(s=>s.role==="user").length<jl)return{documents:[],skip_reason:"Session too short"};let n=eg(t);if(!n.trim())return{documents:[],skip_reason:"No usable content"};let o=[{role:"system",content:DS},{role:"user",content:`Conversation to analyze:
|
|
1312
1312
|
|
|
1313
|
-
${n}`}];try{let i=((await
|
|
1313
|
+
${n}`}];try{let i=((await Qh(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 qS(t){let e=await og(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}}
|
|
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}}rg.exports={learnFromSession:jS,learnBrainFromSession:qS,reflectOnSession:tg,reflectBrain:og,applyMemories:ng,applyNexAdditions:sg,LEARN_MIN_MESSAGES:jl}});var Un=Q((IR,ig)=>{var{C:Pe}=Fe();function FS(t){return t.tree&&t.tree.branches?t.tree:{branches:{main:{messages:t.messages||[],parentBranch:null,forkIndex:0}},activeBranch:"main"}}function US(t){let e=t.branches[t.activeBranch];return e?e.messages:[]}function BS(t,e){let n=t.branches[t.activeBranch];n&&(n.messages=e)}function WS(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 HS(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 KS(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 GS(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 YS(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
1319
|
`)}function zS(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
|
-
`)}
|
|
1321
|
+
`)}ig.exports={initTree:FS,getActiveMessages:US,setActiveMessages:BS,createBranch:WS,switchBranch:HS,gotoMessage:KS,deleteBranch:GS,renderTree:YS,renderTimeline:zS}});var fg=Q((jR,dg)=>{var{spawn:XS}=require("child_process"),ag=require("path"),cg=require("fs"),JS=require("os"),Bn=new Map;function lg(t){return typeof t!="string"?t:t.replace(/\$\{([^}]+)\}/g,(e,n)=>process.env[n]!==void 0?process.env[n]:"")}function ug(t){let e=t||process.env.NEX_MCP_CONFIG||null,n=e?[e]:[ag.join(process.cwd(),".nex","mcp.json"),ag.join(JS.homedir(),".nex","mcp.json")];for(let o of n)if(cg.existsSync(o))try{return JSON.parse(cg.readFileSync(o,"utf-8"))}catch{}return{servers:{}}}function la(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 VS(t){let n=
|
|
1324
|
-
`):JSON.stringify(s)}function QS(){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 eE(){for(let[t,e]of Bn){try{e.proc.kill()}catch{}Bn.delete(t)}}function tE(){let t=[];for(let[e,n]of Bn)t.push({name:e,connected:!0,toolCount:n.tools.length});return t}
|
|
1325
|
-
${
|
|
1326
|
-
`);let o=Object.keys(n);if(o.length>0&&(console.log(`${
|
|
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 VS(t){let n=ug(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]=lg(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=XS(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 la(u,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.4.8"}});let d=await la(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 ZS(t,e,n={}){let o=Bn.get(t);if(!o)throw new Error(`MCP server not connected: ${t}`);let s=await la(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 QS(){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 eE(){for(let[t,e]of Bn){try{e.proc.kill()}catch{}Bn.delete(t)}}function tE(){let t=[];for(let[e,n]of Bn)t.push({name:e,connected:!0,toolCount:n.tools.length});return t}dg.exports={loadMcpServers:VS,callMcpTool:ZS,getMcpTools:QS,shutdownMcpServers:eE,listMcpServers:tE,_interpolateEnv:lg,_readConfig:ug,_sendRequest:la}});var gg=Q((qR,hg)=>{var yt=require("fs"),fo=require("path"),DR=require("os"),nE=require("readline"),{C:oe}=Fe(),pg=".nex",ql=null;function sE(t){ql=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(ql)ql.question(o,r);else{let i=nE.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 Fl(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 oE(){let t=fo.join(process.cwd(),pg),e=fo.join(t,"servers.json"),n={};if(yt.existsSync(e))try{n=JSON.parse(yt.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
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
|
+
`);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(`
|
|
1328
|
-
${
|
|
1329
|
-
${
|
|
1328
|
+
${oe.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${oe.reset}`);let l=await wt("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${oe.red} Name is required.${oe.reset}`);continue}let u=await wt("Host / IP address");if(!u){console.log(`${oe.red} Host is required.${oe.reset}`);continue}let d=await wt("SSH user","root"),f=await wt("SSH port","22"),p=parseInt(f,10)||22,h=await wt("SSH key path (leave empty for SSH agent)",""),m=await Fl("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await uo("Allow sudo commands?",!0),y={host:u,user:d};p!==22&&(y.port=p),h&&(y.key=h),m!=="other"&&(y.os=m),g&&(y.sudo=!0),s[l]=y,console.log(`
|
|
1329
|
+
${oe.green}\u2713${oe.reset} Profile "${l}" added: ${d}@${u}${p!==22?`:${p}`:""}${m!=="other"?` [${m}]`:""}`),r=await uo(`
|
|
1330
1330
|
Add another server?`,!1)}yt.existsSync(t)||yt.mkdirSync(t,{recursive:!0}),yt.writeFileSync(e,JSON.stringify(s,null,2)+`
|
|
1331
1331
|
`,"utf-8"),console.log(`
|
|
1332
|
-
${
|
|
1332
|
+
${oe.green}\u2713 Saved .nex/servers.json (${Object.keys(s).length} profile${Object.keys(s).length!==1?"s":""})${oe.reset}`);let i=fo.join(process.cwd(),".gitignore");yt.existsSync(i)&&(yt.readFileSync(i,"utf-8").includes(".nex/")||await uo("Add .nex/ to .gitignore?",!0)&&(yt.appendFileSync(i,`
|
|
1333
1333
|
# nex-code server profiles
|
|
1334
1334
|
.nex/
|
|
1335
|
-
`),console.log(`${
|
|
1336
|
-
Set up deploy configs (.nex/deploy.json)?`,!1)&&await
|
|
1337
|
-
${
|
|
1338
|
-
`)}async function
|
|
1339
|
-
${
|
|
1340
|
-
`);let i=Object.keys(s);i.length>0&&console.log(`${
|
|
1341
|
-
${
|
|
1342
|
-
${
|
|
1335
|
+
`),console.log(`${oe.green}\u2713 Added .nex/ to .gitignore${oe.reset}`))),await uo(`
|
|
1336
|
+
Set up deploy configs (.nex/deploy.json)?`,!1)&&await mg(s,t),console.log(`
|
|
1337
|
+
${oe.dim}Use /servers to list profiles, /servers ping to check connectivity.${oe.reset}
|
|
1338
|
+
`)}async function mg(t,e){let n=e||fo.join(process.cwd(),pg),o=fo.join(n,"deploy.json"),s={};if(yt.existsSync(o))try{s=JSON.parse(yt.readFileSync(o,"utf-8"))}catch{}if(!t){let u=fo.join(n,"servers.json");if(yt.existsSync(u))try{t=JSON.parse(yt.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
1339
|
+
${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 Deploy Config 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}
|
|
1340
|
+
`);let i=Object.keys(s);i.length>0&&console.log(`${oe.dim}Existing deploy configs: ${i.join(", ")}${oe.reset}`);let c={...s},l=!0;for(;l;){console.log(`
|
|
1341
|
+
${oe.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${oe.reset}`);let u=await wt("Config name (e.g. prod, staging)");if(!u){console.log(`${oe.red} Name is required.${oe.reset}`);continue}let d;r.length>0?d=await Fl("Target server",r,r[0]):d=await wt("Target server (profile name or user@host)");let f=await Fl("Deploy method",["rsync","git"],"rsync"),p="",h=[],m="";if(f==="rsync"){p=await wt("Local path to sync (e.g. dist/ or ./build)","dist/");let C=await wt("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env");h=C?C.split(",").map(S=>S.trim()).filter(Boolean):[]}else m=await wt("Branch to pull (leave empty for current remote branch)","main");let g=await wt(f==="git"?"Remote repo path (e.g. /home/jarvis/my-app)":"Remote destination path (e.g. /var/www/app)");if(!g){console.log(`${oe.red} Remote path is required.${oe.reset}`);continue}let y=await wt("Command to run on remote after deploy (leave empty to skip)",""),w=await wt("Health check URL or remote command (leave empty to skip)",""),v={server:d,method:f,remote_path:g};f==="rsync"?(v.local_path=p,h.length>0&&(v.exclude=h)):m&&(v.branch=m),y&&(v.deploy_script=y),w&&(v.health_check=w),c[u]=v;let M=f==="git"?`${d}:${g}${m?` (${m})`:""}`:`${p.endsWith("/")?p:p+"/"} \u2192 ${d}:${g}`;console.log(`
|
|
1342
|
+
${oe.green}\u2713${oe.reset} Deploy config "${u}": [${f}] ${M}`),y&&console.log(` ${oe.dim} Then: ${y}${oe.reset}`),w&&console.log(` ${oe.dim} Health: ${w}${oe.reset}`),l=await uo(`
|
|
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
|
-
${
|
|
1346
|
-
`)}
|
|
1347
|
-
`);return`${
|
|
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
|
+
`)}hg.exports={runServerWizard:oE,runDeployWizard:mg,setWizardRL:sE}});var po=Q((FR,wg)=>{"use strict";var fa=require("os"),br=require("path"),it=require("fs"),rE=require("axios"),iE=require("https"),ua=br.join(fa.homedir(),".nex-code","known-models.json"),aE="https://ollama.com/api/tags",cE=60,lE={"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 Ul(){try{if(it.existsSync(ua))return JSON.parse(it.readFileSync(ua,"utf-8"))}catch{}return{benchmarked:[],lastChecked:null}}function uE(t){let e=br.dirname(ua);it.existsSync(e)||it.mkdirSync(e,{recursive:!0}),it.writeFileSync(ua,JSON.stringify(t,null,2))}function dE(t){let e=Ul(),n=new Set(e.benchmarked);for(let o of t)n.add(o);e.benchmarked=[...n],e.lastChecked=new Date().toISOString(),uE(e)}async function $g(){let t=process.env.OLLAMA_API_KEY;if(!t)throw new Error("OLLAMA_API_KEY not set");let e=new iE.Agent({keepAlive:!0});return((await rE.get(aE,{headers:{Authorization:`Bearer ${t}`},timeout:15e3,httpsAgent:e})).data?.models||[]).map(o=>(o.name||o.model||"").replace(/:latest$/,"")).filter(Boolean)}async function fE(){let t=await $g(),e=Ul(),n=new Set(e.benchmarked),o=t.filter(s=>!n.has(s));return{allCloud:t,newModels:o,store:e}}var Bl="<!-- nex-benchmark-start -->",da="<!-- nex-benchmark-end -->",pE={"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 mE(t){return t?t>=25e4?"256K":t>=19e4?"200K":t>=128e3?"131K":t>=64e3?"64K":`${Math.round(t/1024)}K`:"?"}function yg(t,e){let n=["\u{1F947}","\u{1F948}","\u{1F949}"],o=(e||new Date().toISOString()).split("T")[0],s=t.filter(r=>r.score>=cE).map((r,i)=>{let c=n[i]||"\u2014",l=mE(lE[r.model]),u=pE[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
|
+
`);return`${Bl}
|
|
1348
1348
|
<!-- Updated: ${o} \u2014 run \`/benchmark --discover\` after new Ollama Cloud releases -->
|
|
1349
1349
|
|
|
1350
1350
|
| Rank | Model | Score | Avg Latency | Context | Best For |
|
|
@@ -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
|
-
${
|
|
1356
|
+
${da}`}function hE(t,e){if(!it.existsSync(e))return!1;let n=it.readFileSync(e,"utf-8"),o=n.indexOf(Bl),s=n.indexOf(da);if(o===-1||s===-1)return!1;let r=n.slice(0,o),i=n.slice(s+da.length),c=yg(t);return it.writeFileSync(e,r+c+i),!0}function gE(t){let e=br.join(fa.homedir(),".nex-code","models.env");if(!it.existsSync(e)||t.length===0)return{updated:!1,reason:"models.env not found or empty summary"};let n=t[0],o=it.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)`),it.writeFileSync(e,o),{updated:!0,previousModel:r,newModel:n.model}}function $E(t){let{saveRoutingConfig:e}=In(),n=br.join(fa.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(it.existsSync(n)){let c=it.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
|
-
`;it.writeFileSync(n,c),i=!0}return{saved:!0,envUpdated:i,changes:o}}var yE=/thinking|reasoning|instruct|planner|orchestrat/i;function wE(t){return yE.test(t)}function bE(t){if(!t||t.length===0)return{updated:!1};let e=br.join(
|
|
1363
|
+
`;it.writeFileSync(n,c),i=!0}return{saved:!0,envUpdated:i,changes:o}}var yE=/thinking|reasoning|instruct|planner|orchestrat/i;function wE(t){return yE.test(t)}function bE(t){if(!t||t.length===0)return{updated:!1};let e=br.join(fa.homedir(),".nex-code","models.env");if(!it.existsSync(e))return{updated:!1};let n=it.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}}yg.exports={findNewModels:fE,fetchCloudModels:gg,loadKnownModels:Fl,markBenchmarked:dE,updateReadme:hE,updateModelsEnv:gE,updateRoutingConfig:$E,generateBenchmarkBlock:$g,checkOrchestratorCandidate:wE,updateOrchestratorModel:bE,SENTINEL_START:Ul,SENTINEL_END:ua}});var Wn=Q((UR,Rg)=>{"use strict";var{C:J}=Fe(),_E=je(),{TOOL_DEFINITIONS:wg}=Gt(),{saveRoutingConfig:xE}=In(),Hl=[{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}],bg=[{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)}],ma=[...Hl,...bg],Bl=["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 vE(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return Bl;let o=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(o)||o.length===0?Bl: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 Bl}}var Kl=vE(),kE=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],_g=(()=>{let t=Kl.slice(0,3);return t.length>=3?t:kE})(),SE=7,fa={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},EE="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 Wl(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:EE},{role:"user",content:t.prompt}],s=Date.now();try{let r=await _E.callChat(o,wg,{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=wg.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?fa.producedToolCall:0)+(t.correctTool?fa.correctTool:0)+(t.validArgs?fa.validArgs:0)+(t.schemaCompliant?fa.schemaCompliant:0))*100}var xg={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 Gl(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=>xg[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 vg(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=>xg[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 kg(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
|
+
`,it.writeFileSync(e,n),{updated:!0,previousModel:s,newModel:i.model}}wg.exports={findNewModels:fE,fetchCloudModels:$g,loadKnownModels:Ul,markBenchmarked:dE,updateReadme:hE,updateModelsEnv:gE,updateRoutingConfig:$E,generateBenchmarkBlock:yg,checkOrchestratorCandidate:wE,updateOrchestratorModel:bE,SENTINEL_START:Bl,SENTINEL_END:da}});var Wn=Q((UR,Cg)=>{"use strict";var{C:J}=Fe(),_E=je(),{TOOL_DEFINITIONS:bg}=Gt(),{saveRoutingConfig:xE}=In(),Kl=[{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}],_g=[{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)}],ha=[...Kl,..._g],Wl=["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 vE(){try{let n=require("path").join(require("os").homedir(),".nex-code","benchmark-results.json");if(!require("fs").existsSync(n))return Wl;let o=JSON.parse(require("fs").readFileSync(n,"utf-8"));return!Array.isArray(o)||o.length===0?Wl: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 Wl}}var Gl=vE(),kE=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],xg=(()=>{let t=Gl.slice(0,3);return t.length>=3?t:kE})(),SE=7,pa={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},EE="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 Hl(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:EE},{role:"user",content:t.prompt}],s=Date.now();try{let r=await _E.callChat(o,bg,{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=bg.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?pa.producedToolCall:0)+(t.correctTool?pa.correctTool:0)+(t.validArgs?pa.validArgs:0)+(t.schemaCompliant?pa.schemaCompliant:0))*100}var vg={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 Yl(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=>vg[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 kg(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=>vg[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 Sg(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
|
|
1369
|
-
${J.dim} Routing updated: ${r.join(", ")}${J.reset}`))}catch{}}async function TE({models:t,quick:e=!1,onProgress:n,parallelModels:o=1}={}){let s=e?
|
|
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 Eg(t){if(!(!t||t.length<2))try{let e=kg(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&&(xE(s),console.log(`
|
|
1369
|
+
${J.dim} Routing updated: ${r.join(", ")}${J.reset}`))}catch{}}async function TE({models:t,quick:e=!1,onProgress:n,parallelModels:o=1}={}){let s=e?Kl.slice(0,SE):ha,r=t?.length>0?t:e?xg:Gl,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 Hl(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 Hl(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=Yl(i);return Sg(c,s.length),Eg(c),c}async function RE({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 ha){n?.({model:i,task:c.id,done:!1});let l=await Hl(c,i);o[i].push(l),n?.({model:i,task:c.id,done:!0,score:mo(l),error:l.error})}}let r=[...Yl(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),Sg(r,ha.length),Eg(r),r}var ma=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function Tg(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": [
|
|
@@ -1379,28 +1379,28 @@ ${J.dim} Routing updated: ${r.join(", ")}${J.reset}`))}catch{}}async function T
|
|
|
1379
1379
|
}
|
|
1380
1380
|
]
|
|
1381
1381
|
}
|
|
1382
|
-
`),
|
|
1383
|
-
`),
|
|
1384
|
-
`),
|
|
1382
|
+
`),ma;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
|
+
`),ma):s.scenarios}catch(s){return console.log(`${J.yellow}Failed to parse benchmark-config.json: ${s.message}${J.reset}
|
|
1384
|
+
`),ma}}function Rg(t,e){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=Pi(),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 CE(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 AE(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
1386
|
`)}function OE(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 NE({dryRun:t=!1,model:e,cwd:n,onProgress:o}={}){let s=As(),r=
|
|
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 NE({dryRun:t=!1,model:e,cwd:n,onProgress:o}={}){let s=As(),r=Tg(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 CE(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=
|
|
1392
|
+
${J.dim}Running scenario: ${l.name}...${J.reset}`);let{messages:u,timedOut:d}=await CE(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=Rg(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}=Pi();h(f.score,{version:s.version,model:i,sessionName:`bench:${l.id}`,issues:f.issues})}catch{}}return AE(c,s.version,i),c}Cg.exports={runBenchmark:TE,runDiscoverBenchmark:RE,buildSummary:Yl,buildCategoryWinners:kg,TASKS:Kl,PHASE_TASKS:_g,ALL_TASKS:ha,scoreResult:mo,DEFAULT_MODELS:Gl,QUICK_MODELS:xg,runJarvisBenchmark:NE,showScoreTrend:OE,loadScenarios:Tg,DEFAULT_SCENARIOS:ma,scoreJarvisScenario:Rg}});var Dg=Q((BR,jg)=>{"use strict";var ME=require("os"),Ng=require("path"),zl=require("fs"),{callWithRetry:Ag}=_i(),{parseModelSpec:PE}=je(),{extractJSON:Og,DECOMPOSE_PROMPT:LE,SYNTHESIZE_PROMPT:IE}=sr(),{C:Pt}=Fe(),ga=Ng.join(ME.homedir(),".nex-code","orchestrator-bench.json"),Mg=[{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 Pg(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 Lg(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 Ig(t,e){let n={};if(e){let s=PE(e);s.provider&&(n.provider=s.provider),s.model&&(n.model=s.model)}let o=Date.now();try{if(t.type==="decompose"){let s=LE.replace("{maxSubTasks}",String(t.maxSubTasks)).replace("{prompt}",t.prompt),r=await Ag([{role:"system",content:s},{role:"user",content:t.prompt}],[],n),i=Og(r.content||""),c=Date.now()-o;return{score:Pg(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=IE.replace("{prompt}",t.prompt).replace("{results}",s),i=await
|
|
1397
|
+
`),r=IE.replace("{prompt}",t.prompt).replace("{results}",s),i=await Ag([{role:"system",content:r},{role:"user",content:"Synthesize the sub-agent results above."}],[],n),c=Og(i.content||""),l=Date.now()-o;return{score:Lg(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 jE(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 Mg){n({model:r,scenario:h.id,done:!1});let m=await Ig(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=Ng.dirname(ga);return zl.existsSync(s)||zl.mkdirSync(s,{recursive:!0}),zl.writeFileSync(ga,JSON.stringify({date:new Date().toISOString().slice(0,10),results:o},null,2)),o}function DE(t){console.log(`
|
|
1398
1398
|
${Pt.bold}${Pt.cyan}Orchestrator Model Benchmark${Pt.reset}
|
|
1399
1399
|
`);let e=` ${"Model".padEnd(25)} ${"Decompose".padEnd(10)} ${"Synthesize".padEnd(11)} ${"Speed".padEnd(8)} ${"Score".padEnd(8)}`;console.log(`${Pt.dim}${e}${Pt.reset}`),console.log(` ${Pt.dim}${"\u2500".repeat(65)}${Pt.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)} ${Pt.bold}${n.overall}/10${Pt.reset}`)}t.length>0&&(console.log(`
|
|
1400
|
-
${Pt.green}Best orchestrator: ${t[0].model} (${t[0].overall}/10)${Pt.reset}`),console.log(` ${Pt.dim}Saved to ${
|
|
1401
|
-
`))}
|
|
1400
|
+
${Pt.green}Best orchestrator: ${t[0].model} (${t[0].overall}/10)${Pt.reset}`),console.log(` ${Pt.dim}Saved to ${ga}${Pt.reset}
|
|
1401
|
+
`))}jg.exports={runOrchestratorBenchmark:jE,ORCHESTRATOR_SCENARIOS:Mg,scoreDecompose:Pg,scoreSynthesize:Lg,runScenario:Ig,printResults:DE,RESULTS_PATH:ga}});var Ug=Q((WR,Fg)=>{var qE=require("axios"),_r=require("fs"),qg=require("path"),FE="nex-code",Xl=qg.join(process.cwd(),".nex"),Jl=qg.join(Xl,"last-version-check");_r.existsSync(Xl)||_r.mkdirSync(Xl,{recursive:!0});async function UE(){try{let t=WE(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};HE(e);let n=BE(),s=(await qE.get(`https://registry.npmjs.org/${FE}/latest`,{timeout:5e3})).data.version,r=KE(s,n);return{hasNewVersion:r,latestVersion:r?s:void 0,currentVersion:r?n:void 0}}catch{return{hasNewVersion:!1}}}function BE(){return As().version}function WE(){try{if(_r.existsSync(Jl)){let t=_r.readFileSync(Jl,"utf8");return parseInt(t,10)}}catch{}return null}function HE(t){try{_r.writeFileSync(Jl,t.toString())}catch{}}function KE(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}}Fg.exports={checkForNewVersion:UE}});var ru=Q((KR,Zg)=>{var GE=require("readline"),at=require("fs"),et=require("path"),{C:a,banner:YE,cleanupTerminal:Bg}=Fe(),{isDark:zE}=Yn(),{listProviders:Ql,getActiveProviderName:ks,listAllModels:HR,setFallbackChain:XE,getFallbackChain:JE,getProvider:VE}=je(),{flushAutoSave:Wg}=Jt(),{getActiveModel:En,setActiveModel:eu}=Fs(),{printContext:Hg}=Ni(),{loadAllSkills:ZE,getSkillCommands:ya,handleSkillCommand:QE}=Mn(),{setReadlineInterface:eT,setAutoConfirm:tT,getAutoConfirm:Vl,setAllowAlwaysHandler:nT}=ft(),{StickyFooter:sT}=zh(),Ht=process.cwd(),Le=null,tn=null;function Kg(){return tn?.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 Gg(){let t=ya(),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
|
|
1403
|
+
`)}function Yg(t){try{let e,n;t.endsWith("/")||t.endsWith(et.sep)?(e=t,n=""):(e=et.dirname(t),n=et.basename(t)),e.startsWith("~")&&(e=et.join(require("os").homedir(),e.slice(1)));let o=et.isAbsolute(e)?e:et.resolve(Ht,e);if(!at.existsSync(o)||!at.statSync(o).isDirectory())return[];let s=at.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(et.sep)?t:et.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?i.name:c+i.name;r.push(i.isDirectory()?l+"/":l)}return r}catch{return[]}}function zg(t){if(t.startsWith("/")){let o=[...Sr,...ya()],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("~"))?[Yg(n),n]:[[],t]}function Xg(){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}
|
|
@@ -1473,21 +1473,21 @@ ${a.bold}${a.cyan}Undo / Redo:${a.reset}
|
|
|
1473
1473
|
${a.cyan}/benchmark --all --parallel=N${a.reset}${a.dim} Override concurrency (default 3)${a.reset}
|
|
1474
1474
|
|
|
1475
1475
|
${a.cyan}/exit${a.reset} ${a.dim}Quit${a.reset}
|
|
1476
|
-
`)}function
|
|
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
|
|
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=
|
|
1476
|
+
`)}function Jg(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 Zl(){let t=Ql(),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 Xg(),!0;case"/model":{let s=o.join(" ").trim();if(!s){if(e){let{showModelPicker:r}=Vh();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 Zl(),!0;if(eu(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 Zl(),!0;case"/fallback":{let s=o.join(" ").trim();if(!s){let i=JE();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 XE(r),console.log(`${a.green}Fallback chain: ${r.join(" \u2192 ")}${a.reset}`),!0}case"/tokens":{let{getConversationMessages:s}=Se(),{getUsage:r}=Rt(),{TOOL_DEFINITIONS:i}=Gt(),c=s(),l=r(c,i),u=En(),d=ks();console.log(`
|
|
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=Jg(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()}
|
|
1481
|
-
`),!0)}case"/budget":{let{getCostLimits:s,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=qs(),d=o[0];if(!d){let h=s(),m=
|
|
1482
|
-
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let y of m){let w=r(y.provider),v=h[y.provider];if(v!==void 0){g=!0;let M=Math.min(100,Math.round(w/v*100)),C=10,S=Math.round(M/100*C),O=C-S,K=`${M>=100?a.red:M>=80?a.yellow:a.green}${"\u2588".repeat(S)}${a.dim}${"\u2591".repeat(O)}${a.reset}`;console.log(` ${a.bold}${y.provider}:${a.reset} $${w.toFixed(2)} / $${v.toFixed(2)} (${M}%) ${K}`)}else y.provider==="ollama"||y.provider==="local"?console.log(` ${a.bold}${y.provider}:${a.reset} ${a.dim}free (no limit)${a.reset}`):w>0&&console.log(` ${a.bold}${y.provider}:${a.reset} $${w.toFixed(2)} ${a.dim}(no limit)${a.reset}`)}return g||console.log(` ${a.dim}No limits set. Use /budget <provider> <amount> to set one.${a.reset}`),console.log(),!0}let f=o[1];if(!f){let h=i(d);return h.limit!==null?console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} ${a.dim}(no limit)${a.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return c(d),l(),console.log(`${a.green}Removed cost limit for ${d}${a.reset}`),!0;let p=parseFloat(f);return isNaN(p)||p<=0?(console.log(`${a.red}Invalid amount: ${f}. Use a positive number or 'off'.${a.reset}`),!0):(u(d,p),l(),console.log(`${a.green}Set ${d} budget limit: $${p.toFixed(2)}${a.reset}`),!0)}case"/clear":{let{clearConversation:s,getConversationMessages:r}=Se(),{clearHistory:i}
|
|
1481
|
+
`),!0)}case"/budget":{let{getCostLimits:s,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=qs(),d=o[0];if(!d){let h=s(),m=Ql();console.log(`
|
|
1482
|
+
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let y of m){let w=r(y.provider),v=h[y.provider];if(v!==void 0){g=!0;let M=Math.min(100,Math.round(w/v*100)),C=10,S=Math.round(M/100*C),O=C-S,K=`${M>=100?a.red:M>=80?a.yellow:a.green}${"\u2588".repeat(S)}${a.dim}${"\u2591".repeat(O)}${a.reset}`;console.log(` ${a.bold}${y.provider}:${a.reset} $${w.toFixed(2)} / $${v.toFixed(2)} (${M}%) ${K}`)}else y.provider==="ollama"||y.provider==="local"?console.log(` ${a.bold}${y.provider}:${a.reset} ${a.dim}free (no limit)${a.reset}`):w>0&&console.log(` ${a.bold}${y.provider}:${a.reset} $${w.toFixed(2)} ${a.dim}(no limit)${a.reset}`)}return g||console.log(` ${a.dim}No limits set. Use /budget <provider> <amount> to set one.${a.reset}`),console.log(),!0}let f=o[1];if(!f){let h=i(d);return h.limit!==null?console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} ${a.dim}(no limit)${a.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return c(d),l(),console.log(`${a.green}Removed cost limit for ${d}${a.reset}`),!0;let p=parseFloat(f);return isNaN(p)||p<=0?(console.log(`${a.red}Invalid amount: ${f}. Use a positive number or 'off'.${a.reset}`),!0):(u(d,p),l(),console.log(`${a.green}Set ${d} budget limit: $${p.toFixed(2)}${a.reset}`),!0)}case"/clear":{let{clearConversation:s,getConversationMessages:r}=Se(),{clearHistory:i}=yn(),c=r();if(c.filter(d=>d.role==="user").length>=4){process.stdout.write(`${a.dim}Reflecting on session...${a.reset} `);let{learnFromSession:d}=Dl();d(c).then(f=>{if(!f.skipped&&!f.error&&(f.applied.length>0||f.nexAdded.length>0)){let p=f.applied.length+f.nexAdded.length;process.stdout.write(`${a.green}${p} learning(s) saved${a.reset}
|
|
1483
1483
|
`)}else process.stdout.write(`${a.dim}nothing new${a.reset}
|
|
1484
1484
|
`)}).catch(()=>process.stdout.write(`
|
|
1485
1485
|
`))}s(),i(),Le=null;let{deleteSession:u}=Jt();return u("_autosave"),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/retry":{let{getConversationMessages:s,setConversationMessages:r,processInput:i}=Se(),c=s(),l=c.map(g=>g.role).lastIndexOf("user");if(l===-1)return console.log(`${a.yellow}Nothing to retry \u2014 no user message found.${a.reset}`),!0;let u=o.indexOf("--model"),d=u!==-1&&o[u+1]?o[u+1]:null;if(d){let{setActiveModel:g}=je();if(!g(d))return console.log(`${a.red}Unknown model: ${d}. Use /providers to see available models.${a.reset}`),!0;console.log(`${a.cyan}Switched to model: ${d}${a.reset}`)}let f=c[l],p;typeof f.content=="string"?p=f.content:Array.isArray(f.content)?p=f.content.filter(g=>g&&g.type==="text").map(g=>g.text).join(`
|
|
1486
|
-
`):p=String(f.content),r(c.slice(0,l));let{resetSessionTracking:h}=Se();h();let m=d||"current model";return console.log(`${a.cyan}Retrying with ${m}...${a.reset}`),await i(p),!0}case"/context":return await
|
|
1486
|
+
`):p=String(f.content),r(c.slice(0,l));let{resetSessionTracking:h}=Se();h();let m=d||"current model";return console.log(`${a.cyan}Retrying with ${m}...${a.reset}`),await i(p),!0}case"/context":return await Hg(Ht),!0;case"/tree":{let{generateFileTree:s}=Ni(),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=!
|
|
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}=Se(),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}=Se(),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}=Se(),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}=Se(),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}=Se(),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}=Se();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}=Se();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}=
|
|
1489
|
+
`),!0}case"/autoconfirm":{let s=!Vl();return tT(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}=Se(),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}=Se(),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
|
+
${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}=Se(),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}=Se(),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}=Se(),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}=Se(),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}=Se(),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}=Se();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}=Se();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}=cn(),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}=cn(),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}=cn(),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
|
|
|
1493
1493
|
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${a.green}Created .nex/brain/${h}.md${a.reset}`),console.log(`${a.dim}Edit it directly at: ${g}${a.reset}`)}else{let g=h.substring(0,m),y=h.substring(m+1);i(g,y),console.log(`${a.green}Added to brain: ${g}${a.reset}`)}return!0}case"list":{let m=s();if(m.length===0)return console.log(`${a.dim}No brain documents yet. Use /brain add <name> to create one.${a.reset}`),!0;console.log(`
|
|
@@ -1504,13 +1504,13 @@ ${a.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \
|
|
|
1504
1504
|
`);else{console.log(`
|
|
1505
1505
|
${a.bold}${a.cyan}Brain: ${m.length} document(s)${a.reset}`);for(let g of m){let{frontmatter:y}=r(g.name),w=Array.isArray(y.tags)?` [${y.tags.join(", ")}]`:"";console.log(` ${a.cyan}${g.name}${a.reset}${a.dim}${w}${a.reset}`)}console.log(`
|
|
1506
1506
|
${a.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${a.reset}
|
|
1507
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:s,learnBrainFromSession:r}=
|
|
1507
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:s,learnBrainFromSession:r}=Dl(),{getConversationMessages:i}=Se(),c=i(),l=c.filter(u=>u.role==="user").length;if(l<4)return console.log(`${a.yellow}Session too short to learn from (need 4+ user messages, have ${l})${a.reset}`),!0;console.log(`${a.dim}Analyzing session for learnings...${a.reset}`);try{let[u,d]=await Promise.all([s(c),r(c)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${a.dim}Session too short${a.reset}`),!0;u.error&&console.log(`${a.red}Reflection error: ${u.error}${a.reset}`),console.log(""),u.summary&&(console.log(`${a.bold}Session:${a.reset} ${a.dim}${u.summary}${a.reset}`),console.log(""));let f=u.applied&&u.applied.length>0,p=u.nexAdded&&u.nexAdded.length>0,h=d.written&&d.written.length>0;if(!f&&!p&&!h)console.log(`${a.dim}No new learnings extracted from this session${a.reset}`);else{if(f){console.log(`${a.bold}${a.cyan}Memory updates:${a.reset}`);for(let{key:m,value:g,action:y}of u.applied){let w=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${w} ${a.bold}${m}${a.reset} = ${g}`)}}if(p){console.log(`${a.bold}${a.cyan}Added to NEX.md:${a.reset}`);for(let m of u.nexAdded)console.log(` ${a.green}+${a.reset} ${m}`)}if(h){console.log(`${a.bold}${a.cyan}Brain documents:${a.reset}`);for(let{name:m,reason:g,action:y}of d.written){let w=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${w} ${a.bold}${m}.md${a.reset}${g?a.dim+" \u2014 "+g+a.reset:""}`)}}}console.log("")}catch(u){console.log(`${a.red}Learn failed: ${u.message}${a.reset}`)}return!0}case"/optimize":{let{getConversationMessages:s}=Se(),{getUsage:r}=Rt(),{TOOL_DEFINITIONS:i}=Gt(),{listMemories:c}=cn(),l=s(),u=r(l,i),d=En(),f=ks(),p=c();console.log(`
|
|
1508
1508
|
${a.bold}${a.cyan}Optimization Report${a.reset}
|
|
1509
1509
|
`);let h=u.percentage>80?a.red:u.percentage>50?a.yellow:a.green;if(console.log(`${a.bold}Context Window:${a.reset} ${h}${u.percentage}%${a.reset} used (${u.used.toLocaleString()} / ${u.limit.toLocaleString()} tokens)`),u.percentage>75?console.log(` ${a.yellow}\u2192 Tip: Use /clear to free context (auto-learns first)${a.reset}`):u.percentage>50?console.log(` ${a.dim}\u2192 Context is filling up, consider /clear soon${a.reset}`):console.log(` ${a.green}\u2192 Context healthy${a.reset}`),console.log(`
|
|
1510
1510
|
${a.bold}Memory:${a.reset} ${p.length} entries`),p.length===0)console.log(` ${a.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${a.reset}`);else{let M=[...p].sort((O,D)=>new Date(D.updatedAt)-new Date(O.updatedAt))[0],C=M?Math.round((Date.now()-new Date(M.updatedAt))/6e4):null,S=C!==null?C<60?`${C}m ago`:`${Math.round(C/60)}h ago`:"?";console.log(` ${a.dim}Latest update: ${S}${a.reset}`),p.length>30&&console.log(` ${a.yellow}\u2192 Many memories (${p.length}) \u2014 consider pruning with /forget${a.reset}`)}console.log(`
|
|
1511
1511
|
${a.bold}Active Model:${a.reset} ${f}:${d.id}`);let m=d.contextWindow||d.maxTokens||0;m>0&&m<32e3&&l.length>10?console.log(` ${a.yellow}\u2192 Small context window (${(m/1e3).toFixed(0)}k). Consider /model for larger context${a.reset}`):m>=128e3&&console.log(` ${a.green}\u2192 Large context window (${(m/1e3).toFixed(0)}k) \u2014 good for long sessions${a.reset}`);let g=l.filter(v=>v.role==="user").length;console.log(`
|
|
1512
1512
|
${a.bold}Session:${a.reset} ${g} turns, ${l.length} messages total`),g>=4&&g%10===0&&console.log(` ${a.cyan}\u2192 Good time to /learn and capture session insights${a.reset}`);let y=[],w=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync(w)||y.push("Create NEX.md in project root to give nex-code project-specific instructions"),y.length>0){console.log(`
|
|
1513
|
-
${a.bold}Quick Wins:${a.reset}`);for(let v of y)console.log(` ${a.cyan}\u2192${a.reset} ${v}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:s,approvePlan:r,startExecution:i,setPlanMode:c,getPlanContent:l,getPlanContent:u,formatPlan:d,extractStepsFromText:f,createPlan:p}=
|
|
1513
|
+
${a.bold}Quick Wins:${a.reset}`);for(let v of y)console.log(` ${a.cyan}\u2192${a.reset} ${v}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:s,approvePlan:r,startExecution:i,setPlanMode:c,getPlanContent:l,getPlanContent:u,formatPlan:d,extractStepsFromText:f,createPlan:p}=ln(),{invalidateSystemPromptCache:h}=Se(),m=o.join(" ").trim();if(m==="status"){let g=s();return console.log(d(g)),!0}if(m==="edit"){let g=l();if(!g)return console.log(`${a.yellow}No plan to edit. Generate a plan first with /plan${a.reset}`),!0;let y=require("os"),w=require("path").join(y.tmpdir(),`nex-plan-${Date.now()}.md`);require("fs").writeFileSync(w,g,"utf-8");let v=process.env.EDITOR||process.env.VISUAL||"nano",{spawnSync:M}=require("child_process");if(console.log(`${a.dim}Opening plan in ${v}... (save and close to update)${a.reset}`),M(v,[w],{stdio:"inherit"}).status===0){let{setPlanContent:S}=ln(),O=require("fs").readFileSync(w,"utf-8");S(O);let D=f(O);if(D.length>0){let V=s()?.task||"Task";p(V,D),console.log(`${a.green}Plan updated \u2014 ${D.length} steps extracted.${a.reset}`)}else console.log(`${a.green}Plan updated.${a.reset}`)}else console.log(`${a.yellow}Editor exited with error \u2014 plan unchanged.${a.reset}`);try{require("fs").unlinkSync(w)}catch{}return!0}if(m==="approve"){let g=l();if(r()){i(),c(!1),xr(),h();let w=s()?.steps?.length||0,v=w>0?` (${w} steps)`:"";if(console.log(`${a.green}${a.bold}Plan approved!${a.reset}${v} Executing...`),console.log(`${a.dim}Plan mode disabled \u2014 all tools now available.${a.reset}`),g){let{processInput:M}=Se(),C=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1514
1514
|
|
|
1515
1515
|
Implement the following plan step by step. All tools are now available.
|
|
1516
1516
|
|
|
@@ -1519,11 +1519,11 @@ ${g}`;try{await M(C)}catch(S){console.log(`${a.red}Error: ${S.message?.split(`
|
|
|
1519
1519
|
${a.cyan}${a.bold}\u250C\u2500 PLAN MODE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510${a.reset}
|
|
1520
1520
|
${a.cyan}${a.bold}\u2502${a.reset} Analysis only \u2014 no file changes until approved ${a.cyan}${a.bold}\u2502${a.reset}
|
|
1521
1521
|
${a.cyan}${a.bold}\u2502${a.reset} ${a.dim}Read-only tools only \xB7 /plan approve to execute${a.reset} ${a.cyan}${a.bold}\u2502${a.reset}
|
|
1522
|
-
${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),m&&console.log(`${a.dim}Task: ${m}${a.reset}`),!0}case"/plans":{let{listPlans:s}=
|
|
1523
|
-
${a.bold}${a.cyan}Plans:${a.reset}`);for(let i of r){let c=i.status==="completed"?`${a.green}\u2713`:i.status==="executing"?`${a.blue}\u2192`:`${a.dim}\u25CB`;console.log(` ${c} ${a.reset}${a.bold}${i.name}${a.reset} \u2014 ${i.task||"?"} (${i.steps} steps, ${i.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:s,setAutonomyLevel:r,AUTONOMY_LEVELS:i}=
|
|
1522
|
+
${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),m&&console.log(`${a.dim}Task: ${m}${a.reset}`),!0}case"/plans":{let{listPlans:s}=ln(),r=s();if(r.length===0)return console.log(`${a.dim}No saved plans${a.reset}`),!0;console.log(`
|
|
1523
|
+
${a.bold}${a.cyan}Plans:${a.reset}`);for(let i of r){let c=i.status==="completed"?`${a.green}\u2713`:i.status==="executing"?`${a.blue}\u2192`:`${a.dim}\u25CB`;console.log(` ${c} ${a.reset}${a.bold}${i.name}${a.reset} \u2014 ${i.task||"?"} (${i.steps} steps, ${i.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:s,setAutonomyLevel:r,AUTONOMY_LEVELS:i}=ln(),c=o.join(" ").trim();return c?(r(c)?(console.log(`${a.green}Autonomy: ${c}${a.reset}`),xr()):console.log(`${a.red}Unknown level: ${c}. Use: ${i.join(", ")}${a.reset}`),!0):(console.log(`${a.bold}${a.cyan}Autonomy:${a.reset} ${s()}`),console.log(`${a.dim}Levels: ${i.join(", ")}${a.reset}`),!0)}case"/permissions":{let{listPermissions:s}=tr(),r=s();console.log(`
|
|
1524
1524
|
${a.bold}${a.cyan}Tool Permissions:${a.reset}`);for(let i of r){let c=i.mode==="allow"?`${a.green}\u2713`:i.mode==="deny"?`${a.red}\u2717`:`${a.yellow}?`;console.log(` ${c} ${a.reset}${a.bold}${i.tool}${a.reset} ${a.dim}(${i.mode})${a.reset}`)}return console.log(`
|
|
1525
1525
|
${a.dim}Use /allow <tool> or /deny <tool> to change${a.reset}
|
|
1526
|
-
`),!0}case"/allow":{let{setPermission:s,savePermissions:r}=tr(),i=o.join(" ").trim();return i?(s(i,"allow"),r(),console.log(`${a.green}${i}: allow${a.reset}`),!0):(console.log(`${a.red}Usage: /allow <tool>${a.reset}`),!0)}case"/deny":{let{setPermission:s,savePermissions:r}=tr(),i=o.join(" ").trim();return i?(s(i,"deny"),r(),console.log(`${a.red}${i}: deny${a.reset}`),!0):(console.log(`${a.red}Usage: /deny <tool>${a.reset}`),!0)}case"/audit":{let{getAuditSummary:s,isAuditEnabled:r}=
|
|
1526
|
+
`),!0}case"/allow":{let{setPermission:s,savePermissions:r}=tr(),i=o.join(" ").trim();return i?(s(i,"allow"),r(),console.log(`${a.green}${i}: allow${a.reset}`),!0):(console.log(`${a.red}Usage: /allow <tool>${a.reset}`),!0)}case"/deny":{let{setPermission:s,savePermissions:r}=tr(),i=o.join(" ").trim();return i?(s(i,"deny"),r(),console.log(`${a.red}${i}: deny${a.reset}`),!0):(console.log(`${a.red}Usage: /deny <tool>${a.reset}`),!0)}case"/audit":{let{getAuditSummary:s,isAuditEnabled:r}=Lc();if(!r())return console.log(`${a.yellow}Audit logging is disabled (set NEX_AUDIT=true to enable)${a.reset}`),!0;let i=parseInt(o.join(" ").trim())||1,c=s(i);if(console.log(`
|
|
1527
1527
|
${a.bold}${a.cyan}Audit Summary (${i} day${i>1?"s":""})${a.reset}
|
|
1528
1528
|
`),console.log(` Total tool calls: ${a.bold}${c.totalCalls}${a.reset}`),console.log(` Avg duration: ${a.dim}${c.avgDuration}ms${a.reset}`),console.log(` Success rate: ${c.successRate>=.95?a.green:a.yellow}${Math.round(c.successRate*100)}%${a.reset}`),Object.keys(c.byTool).length>0){console.log(`
|
|
1529
1529
|
${a.dim}Tool${" ".repeat(25)}Count${a.reset}`),console.log(` ${a.dim}${"\u2500".repeat(35)}${a.reset}`);let l=Object.entries(c.byTool).sort((u,d)=>d[1]-u[1]);for(let[u,d]of l.slice(0,15))console.log(` ${u.padEnd(30)}${d}`)}return console.log(),!0}case"/commit":{let{isGitRepo:s,commit:r,analyzeDiff:i,formatDiffSummary:c}=Nn(),{confirm:l}=ft();if(!s())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let u=o.join(" ").trim();if(u){let m=await r(u);return console.log(m?`${a.green}Committed: ${m} \u2014 ${u}${a.reset}`:`${a.red}Commit failed${a.reset}`),!0}if(!i())return console.log(`${a.yellow}No changes to commit${a.reset}`),!0;let f=await c();if(console.log(f),!await l(" Commit changes?"))return!0;let h=await r("nex-code update");return h&&console.log(`${a.green} \u2713 Committed: ${h}${a.reset}`),!0}case"/diff":{let{isGitRepo:s,formatDiffSummary:r}=Nn();return s()?(console.log(r()),!0):(console.log(`${a.red}Not a git repository${a.reset}`),!0)}case"/review":{let{isGitRepo:s,getDiff:r}=Nn(),{processInput:i}=Se(),c=o.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),f=`## Review Protocol
|
|
@@ -1569,26 +1569,26 @@ ${f}
|
|
|
1569
1569
|
|
|
1570
1570
|
\`\`\`diff
|
|
1571
1571
|
${g.substring(0,2e4)}
|
|
1572
|
-
\`\`\``}return await i(p),!0}case"/branch":{let{isGitRepo:s,getCurrentBranch:r,createBranch:i}=Nn();if(!s())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let c=o.join(" ").trim();if(!c){let u=r();return console.log(`${a.bold}${a.cyan}Branch:${a.reset} ${u||"(detached)"}`),!0}let l=i(c);return console.log(l?`${a.green}Created and switched to: ${l}${a.reset}`:`${a.red}Failed to create branch${a.reset}`),!0}case"/mcp":{let{listServers:s,connectAll:r,disconnectAll:i}=
|
|
1572
|
+
\`\`\``}return await i(p),!0}case"/branch":{let{isGitRepo:s,getCurrentBranch:r,createBranch:i}=Nn();if(!s())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let c=o.join(" ").trim();if(!c){let u=r();return console.log(`${a.bold}${a.cyan}Branch:${a.reset} ${u||"(detached)"}`),!0}let l=i(c);return console.log(l?`${a.green}Created and switched to: ${l}${a.reset}`:`${a.red}Failed to create branch${a.reset}`),!0}case"/mcp":{let{listServers:s,connectAll:r,disconnectAll:i}=ti(),{getMcpTools:c,listMcpServers:l}=fg(),u=o.join(" ").trim();if(u==="list"){let f=l(),p=s();if(f.length===0&&p.length===0)return console.log(`${a.dim}No MCP servers connected${a.reset}`),console.log(`${a.dim}Configure servers in .nex/mcp.json then run /mcp connect${a.reset}`),!0;console.log(`
|
|
1573
1573
|
${a.bold}${a.cyan}Connected MCP Servers:${a.reset}`),f.length===0&&console.log(` ${a.dim}(none connected \u2014 run /mcp connect)${a.reset}`);for(let h of f){console.log(` ${a.green}\u2713${a.reset} ${a.bold}${h.name}${a.reset} \u2014 ${h.toolCount} tool(s)`);let m=c().filter(g=>g.function.name.startsWith(`mcp_${h.name}_`));for(let g of m)console.log(` ${a.cyan}${g.function.name}${a.reset} ${a.dim}${g.function.description}${a.reset}`)}return console.log(),!0}if(u==="status"){let f=s(),p=l(),h=new Set(p.map(m=>m.name));if(f.length===0&&p.length===0)return console.log(`${a.dim}No MCP servers configured${a.reset}`),console.log(`${a.dim}Add a .nex/mcp.json file with a "servers" block${a.reset}`),!0;console.log(`
|
|
1574
1574
|
${a.bold}${a.cyan}MCP Server Status:${a.reset}`);for(let m of f){let g=m.connected?`${a.green}\u2713 connected${a.reset}`:`${a.dim}\u25CB disconnected${a.reset}`;console.log(` ${g} ${a.bold}${m.name}${a.reset} (${m.command}) \u2014 ${m.toolCount} tools`)}for(let m of p)f.find(g=>g.name===m.name)||console.log(` ${a.green}\u2713 connected${a.reset} ${a.bold}${m.name}${a.reset} \u2014 ${m.toolCount} tools`);return console.log(),!0}if(u==="connect")return console.log(`${a.dim}Connecting MCP servers...${a.reset}`),r().then(f=>{for(let p of f)p.error?console.log(` ${a.red}\u2717${a.reset} ${p.name}: ${p.error}`):console.log(` ${a.green}\u2713${a.reset} ${p.name}: ${p.tools} tools`);f.length===0&&console.log(`${a.dim}No MCP servers configured in .nex/config.json${a.reset}`)}).catch(f=>{console.log(`${a.red}MCP connection error: ${f.message}${a.reset}`)}),!0;if(u==="disconnect")return i(),console.log(`${a.green}All MCP servers disconnected${a.reset}`),!0;let d=s();if(d.length===0)return console.log(`${a.dim}No MCP servers configured${a.reset}`),console.log(`${a.dim}Add servers to .nex/config.json under "mcpServers"${a.reset}`),!0;console.log(`
|
|
1575
1575
|
${a.bold}${a.cyan}MCP Servers:${a.reset}`);for(let f of d){let p=f.connected?`${a.green}\u2713 connected${a.reset}`:`${a.dim}\u25CB disconnected${a.reset}`;console.log(` ${p} ${a.bold}${f.name}${a.reset} (${f.command}) \u2014 ${f.toolCount} tools`)}return console.log(`
|
|
1576
1576
|
${a.dim}Use /mcp connect to connect all servers${a.reset}
|
|
1577
|
-
`),!0}case"/hooks":{let{listHooks:s}=
|
|
1577
|
+
`),!0}case"/hooks":{let{listHooks:s}=nl(),r=s();if(r.length===0)return console.log(`${a.dim}No hooks configured${a.reset}`),console.log(`${a.dim}Add hooks to .nex/config.json or .nex/hooks/${a.reset}`),!0;console.log(`
|
|
1578
1578
|
${a.bold}${a.cyan}Hooks:${a.reset}`);for(let i of r){console.log(` ${a.cyan}${i.event}${a.reset}`);for(let c of i.commands)console.log(` ${a.dim}\u2192 ${c}${a.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:s,enableSkill:r,disableSkill:i}=Mn(),c=o.join(" ").trim();if(c.startsWith("enable ")){let u=c.substring(7).trim();return r(u)?console.log(`${a.green}Skill enabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}if(c.startsWith("disable ")){let u=c.substring(8).trim();return i(u)?console.log(`${a.yellow}Skill disabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}let l=s();if(l.length===0)return console.log(`${a.dim}No skills loaded${a.reset}`),console.log(`${a.dim}Add .md or .js files to .nex/skills/${a.reset}`),!0;console.log(`
|
|
1579
1579
|
${a.bold}${a.cyan}Skills:${a.reset}`);for(let u of l){let d=u.enabled?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,f=u.type==="prompt"?`${a.dim}(prompt)${a.reset}`:`${a.dim}(script)${a.reset}`,p=[];u.commands>0&&p.push(`${u.commands} cmd`),u.tools>0&&p.push(`${u.tools} tools`);let h=p.length>0?` \u2014 ${p.join(", ")}`:"";console.log(` ${d} ${a.bold}${u.name}${a.reset} ${f}${h}`)}return console.log(`
|
|
1580
1580
|
${a.dim}Use /skills enable <name> or /skills disable <name>${a.reset}
|
|
1581
1581
|
`),!0}case"/install-skill":{let s=o.join(" ").trim();if(!s)return console.log(`${a.yellow}Usage: /install-skill <git-url-or-user/repo>${a.reset}`),!0;let{installSkill:r}=Mn();console.log(`${a.dim}Installing skill from ${s}...${a.reset}`);let i=await r(s);return i.ok?(console.log(`${a.green}Skill "${i.name}" installed successfully${a.reset}`),console.log(`${a.dim}Reload with /skills to see it${a.reset}`)):console.log(`${a.red}Failed: ${i.error}${a.reset}`),!0}case"/search-skill":{let s=o.join(" ").trim();if(!s)return console.log(`${a.yellow}Usage: /search-skill <query>${a.reset}`),!0;let{searchSkills:r}=Mn();console.log(`${a.dim}Searching for "${s}"...${a.reset}`);let i=await r(s);if(i.length===0)console.log(`${a.yellow}No skills found matching "${s}"${a.reset}`);else{console.log(`
|
|
1582
1582
|
${a.bold}Skills matching "${s}":${a.reset}
|
|
1583
1583
|
`);for(let c of i)c.name==="error"?console.log(` ${a.red}${c.description}${a.reset}`):(console.log(` ${a.cyan}${c.owner}/${c.name}${a.reset} ${a.dim}\u2605${c.stars}${a.reset}`),console.log(` ${c.description}`),console.log(` ${a.dim}/install-skill ${c.url}${a.reset}
|
|
1584
|
-
`))}return!0}case"/remove-skill":{let s=o.join(" ").trim();if(!s)return console.log(`${a.yellow}Usage: /remove-skill <name>${a.reset}`),!0;let{removeSkill:r}=Mn(),i=r(s);return i.ok?console.log(`${a.green}Skill "${s}" removed${a.reset}`):console.log(`${a.red}${i.error}${a.reset}`),!0}case"/tasks":{let{renderTaskList:s,clearTasks:r}=
|
|
1584
|
+
`))}return!0}case"/remove-skill":{let s=o.join(" ").trim();if(!s)return console.log(`${a.yellow}Usage: /remove-skill <name>${a.reset}`),!0;let{removeSkill:r}=Mn(),i=r(s);return i.ok?console.log(`${a.green}Skill "${s}" removed${a.reset}`):console.log(`${a.red}${i.error}${a.reset}`),!0}case"/tasks":{let{renderTaskList:s,clearTasks:r}=mi();return o.join(" ").trim()==="clear"?(r(),console.log(`${a.green}Tasks cleared${a.reset}`),!0):(console.log(`
|
|
1585
1585
|
`+s()+`
|
|
1586
|
-
`),!0)}case"/undo":{let{undo:s,getUndoCount:r}
|
|
1586
|
+
`),!0)}case"/undo":{let{undo:s,getUndoCount:r}=yn(),i=s();if(!i)return console.log(`${a.yellow}Nothing to undo${a.reset}`),!0;i.wasCreated?console.log(`${a.green}Undone: deleted ${i.filePath} (was created by ${i.tool})${a.reset}`):console.log(`${a.green}Undone: restored ${i.filePath} (${i.tool})${a.reset}`);let c=r();return c>0&&console.log(`${a.dim}${c} more change(s) to undo${a.reset}`),!0}case"/redo":{let{redo:s,getRedoCount:r}=yn(),i=s();if(!i)return console.log(`${a.yellow}Nothing to redo${a.reset}`),!0;console.log(`${a.green}Redone: ${i.filePath} (${i.tool})${a.reset}`);let c=r();return c>0&&console.log(`${a.dim}${c} more change(s) to redo${a.reset}`),!0}case"/history":{let{getHistory:s,getUndoCount:r,getRedoCount:i}=yn(),c=s(20);if(c.length===0)return console.log(`${a.dim}No file changes in this session${a.reset}`),!0;console.log(`
|
|
1587
1587
|
${a.bold}File Change History${a.reset}
|
|
1588
1588
|
`);for(let l of c){let u=new Date(l.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${a.dim}${u}${a.reset} ${a.yellow}${l.tool}${a.reset} ${l.filePath}`)}return console.log(`
|
|
1589
1589
|
${a.dim}${r()} undo / ${i()} redo available${a.reset}
|
|
1590
|
-
`),!0}case"/snapshot":{let{createSnapshot:s,listSnapshots:r}
|
|
1591
|
-
${a.bold}${a.cyan}Snapshots:${a.reset}`);for(let u of l)console.log(` ${a.cyan}#${u.index}${a.reset} ${a.bold}${u.shortName}${a.reset}`);console.log()}return!0}let c=s(i,Ht);return c.ok?(console.log(`${a.green}Snapshot created:${a.reset} ${c.label}`),console.log(`${a.dim}Use /restore to apply it later${a.reset}`)):console.log(`${a.yellow}${c.error}${a.reset}`),!0}case"/restore":{let{restoreSnapshot:s,listSnapshots:r}
|
|
1590
|
+
`),!0}case"/snapshot":{let{createSnapshot:s,listSnapshots:r}=yn(),i=o.join(" ").trim()||void 0;if(i==="list"){let l=r(Ht);if(l.length===0)console.log(`${a.dim}No snapshots found${a.reset}`);else{console.log(`
|
|
1591
|
+
${a.bold}${a.cyan}Snapshots:${a.reset}`);for(let u of l)console.log(` ${a.cyan}#${u.index}${a.reset} ${a.bold}${u.shortName}${a.reset}`);console.log()}return!0}let c=s(i,Ht);return c.ok?(console.log(`${a.green}Snapshot created:${a.reset} ${c.label}`),console.log(`${a.dim}Use /restore to apply it later${a.reset}`)):console.log(`${a.yellow}${c.error}${a.reset}`),!0}case"/restore":{let{restoreSnapshot:s,listSnapshots:r}=yn(),i=o.join(" ").trim()||"last";if(i==="list"){let l=r(Ht);if(l.length===0)console.log(`${a.dim}No snapshots available${a.reset}`);else{console.log(`
|
|
1592
1592
|
${a.bold}${a.cyan}Available snapshots:${a.reset}`);for(let u of l)console.log(` ${a.cyan}#${u.index}${a.reset} ${a.bold}${u.shortName}${a.reset}`);console.log(`
|
|
1593
1593
|
${a.dim}Usage: /restore <name|last>${a.reset}
|
|
1594
1594
|
`)}return!0}let c=s(i,Ht);return c.ok?(console.log(`${a.green}Restored snapshot:${a.reset} ${c.label}`),console.log(`${a.dim}Working tree updated. Use /undo for in-session file undos.${a.reset}`)):(console.log(`${a.red}Restore failed:${a.reset} ${c.error}`),console.log(`${a.dim}Use /snapshot list to see available snapshots${a.reset}`)),!0}case"/k8s":{let s=o.join(" ").trim(),{exec:r}=require("child_process"),{promisify:i}=require("util"),c=i(r),l=s||null,u=l?`ssh -o ConnectTimeout=10 -o BatchMode=yes ${l.replace(/[^a-zA-Z0-9@._-]/g,"")} `:"",d=f=>l?`${u}"${f.replace(/"/g,'\\"')}"`:f;console.log(`
|
|
@@ -1607,20 +1607,20 @@ ${a.bold}${a.cyan}Configured servers (${l.length}):${a.reset}`);for(let f of l)c
|
|
|
1607
1607
|
${a.dim}/servers ping \u2014 check SSH connectivity for all servers${a.reset}`),console.log(`${a.dim}/servers ping <name> \u2014 check a specific server${a.reset}
|
|
1608
1608
|
`),!0}case"/docker":{let{loadServerProfiles:s,sshExec:r}=Ks(),{exec:i}=require("child_process"),{promisify:c}=require("util"),l=c(i),u=o[0]==="-a"||o[0]==="--all"?'docker ps -a --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"':'docker ps --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"',d=s(),f=[["local",null],...Object.entries(d)];console.log(`
|
|
1609
1609
|
${a.bold}${a.cyan}Docker Containers:${a.reset}`);for(let[p,h]of f){let m=p==="local"?`${a.dim}local${a.reset}`:`${a.cyan}${p}${a.reset}`;try{let g;if(p==="local"){let{stdout:y}=await l(u,{timeout:8e3});g=(y||"").trim()}else{let y=await r(h,u,{timeout:1e4});if(g=[y.stdout,y.stderr].filter(Boolean).join("").trim(),y.exitCode!==0){console.log(` ${m}: ${a.red}SSH error (${y.exitCode})${a.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${m}: ${a.dim}(no containers)${a.reset}`):(console.log(` ${m}:`),g.split(`
|
|
1610
|
-
`).forEach(y=>console.log(` ${a.dim}${y}${a.reset}`)))}catch(g){console.log(` ${m}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:s}
|
|
1610
|
+
`).forEach(y=>console.log(` ${a.dim}${y}${a.reset}`)))}catch(g){console.log(` ${m}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:s}=$c(),r=s(),i=Object.keys(r),c=o[0];if(c&&i.includes(c)){let l=o.includes("--dry-run")||o.includes("-n"),u=r[c],{executeTool:d}=Gt();console.log(`
|
|
1611
1611
|
${a.bold}Running deploy: ${c}${l?" (dry run)":""}${a.reset}`);let f=await d("deploy",{...u,dry_run:l});return console.log(f),!0}if(i.length===0)return console.log(`
|
|
1612
1612
|
${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}=
|
|
1616
|
+
`),!0}case"/init":{let{runServerWizard:s,runDeployWizard:r,setWizardRL:i}=gg();return i(e),o[0]==="deploy"?await r():await s(),!0}case"/setup":{let{runSetupWizard:s}=Ll();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(at.existsSync(y)){let w=(Date.now()-at.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
1617
|
`)}}catch{}if(o.includes("--history")){let y=require("os"),w=et.join(y.homedir(),"Coding","nex-code-benchmarks","results");if(!at.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=at.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
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(at.readFileSync(et.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)),$e=56,be=Math.ceil($e*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}${$e} tasks \xB7 ${V} parallel \xB7 ~${be}min estimated${a.reset}
|
|
1622
|
-
`);let fe=new Map,pe=await S({models:B,quick:!1,parallelModels:V,onProgress:({model:E,task:A,done:T,score:L,error:
|
|
1623
|
-
${a.cyan}${E.padEnd(30)}${a.reset} `));return}let
|
|
1622
|
+
`);let fe=new Map,pe=await S({models:B,quick:!1,parallelModels:V,onProgress:({model:E,task:A,done:T,score:L,error:ae})=>{if(!T){fe.has(E)||(fe.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
1624
|
`);let xe=require("os"),me=require("path").join(xe.homedir(),".nex-code","benchmark-results.json");try{require("fs").writeFileSync(me,JSON.stringify(pe,null,2))}catch{}w(B);let he=O(pe),Re=C(he),k=require("path").join(process.cwd(),"README.md"),j=v(pe,k),x=M(pe);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}
|
|
@@ -1635,43 +1635,44 @@ ${a.bold}Starting benchmark${a.reset} ${a.dim}${d} tasks \xB7 ${f.length} model
|
|
|
1635
1635
|
${a.bold}Per-category routing saved:${a.reset}`);for(let V of S.changes)console.log(` ${a.dim}${V}${a.reset}`)}let O=et.join(process.cwd(),"README.md");v(g,O)&&console.log(`${a.green}README.md updated${a.reset}`),M(g);let D=require("os"),K=et.join(D.homedir(),".nex-code","benchmark-results.json");try{at.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
|
-
`)}}}),!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}=
|
|
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}=Dg(),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:
|
|
1641
|
-
`).filter(Boolean).slice(-
|
|
1642
|
-
`)}catch{}}function Lt(){return`${a.bold}${a.cyan}\u203A${a.reset} `}function xr(){if(!global._nexFooter)return;let{isPlanMode:t,getAutonomyLevel:e}=
|
|
1643
|
-
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:x}=
|
|
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=QE(t);if(s)return s.agentPrompt&&(kr._pendingAgentPrompt=s.agentPrompt),!0;{let r=[...Sr,...ya()].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 tu=1e3;function nu(){return et.join(process.cwd(),".nex","repl_history")}function Vg(){try{let t=nu();if(at.existsSync(t))return at.readFileSync(t,"utf-8").split(`
|
|
1641
|
+
`).filter(Boolean).slice(-tu)}catch{}return[]}function $a(t){try{let e=nu(),n=et.dirname(e);at.existsSync(n)||at.mkdirSync(n,{recursive:!0}),at.appendFileSync(e,t+`
|
|
1642
|
+
`)}catch{}}function Lt(){return`${a.bold}${a.cyan}\u203A${a.reset} `}function xr(){if(!global._nexFooter)return;let{isPlanMode:t,getAutonomyLevel:e}=ln(),{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 su="\x1B[200~",ou="\x1B[201~";function oT(t){return typeof t=="string"&&t.includes(su)}function rT(t){return typeof t=="string"&&t.includes(ou)}function vr(t){return typeof t!="string"?t:t.split(su).join("").split(ou).join("")}async function iT(){if(!VE("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"),eu("local:llama3"),!0}catch{return!1}}async function aT(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:n}=Se();t(Kg);let s=Ql().some(x=>x.configured),r=(async()=>{ZE();let x=En(),E=ks();return{model:x,providerName:E}})(),i=(async()=>s?!0:await iT()?(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
|
+
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:x}=Ug();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}
|
|
1645
|
+
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:p}=yn();f().then(x=>{}),p().catch(()=>{});let h=Vg(),m=GE.createInterface({input:process.stdin,output:process.stdout,prompt:Lt(),completer:zg,history:h,historySize:tu});eT(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((we,Ce)=>{process.stdout.write(` ${
|
|
1648
|
+
`),E.forEach((we,Ce)=>{process.stdout.write(` ${ae}${Ce+1}${A} ${we}
|
|
1649
1649
|
`)}),process.stdout.write(` ${L}${E.length+1}${A} ${L}Eigene Antwort\u2026${A}
|
|
1650
1650
|
`),process.stdout.write(`
|
|
1651
|
-
${
|
|
1652
|
-
`),we(E[nt-1])):nt===E.length+1||tt===""?(process.stdout.write(` ${
|
|
1651
|
+
${ae}[1-${E.length+1}]${A} \u203A `),new Promise(we=>{m.resume(),m.once("line",Ce=>{let tt=Ce.trim(),nt=parseInt(tt);nt>=1&&nt<=E.length?(process.stdout.write(`
|
|
1652
|
+
`),we(E[nt-1])):nt===E.length+1||tt===""?(process.stdout.write(` ${ae}\u203A${A} `),m.once("line",Tn=>{process.stdout.write(`
|
|
1653
1653
|
`),we(Tn.trim()||"")})):(process.stdout.write(`
|
|
1654
|
-
`),we(tt))})})});let y=new sT;y.activate(m),global._nexFooter=y,global._nexRawWrite=x=>y.rawWrite(x),nT(()=>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}`;YE(w,Ht,{yolo:
|
|
1655
|
-
`),await
|
|
1654
|
+
`),we(tt))})})});let y=new sT;y.activate(m),global._nexFooter=y,global._nexRawWrite=x=>y.rawWrite(x),nT(()=>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}`;YE(w,Ht,{yolo:Vl()});{y.setStatusInfo({model:w,branch:"",project:et.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:et.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
|
+
`),await Hg(Ht);let v=!1,M=0,C=!1,S=null;function O(){Wg(),y.deactivate(),Bg(),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",()=>{Wg()}),m.on("SIGINT",()=>{if(Bg(),M++,M>=2){O();return}if(v){tn&&tn.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(Lt()),m.prompt()}else console.log(`${a.dim} (Press Ctrl+C again to exit)${a.reset}`),m.setPrompt(Lt()),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||"",
|
|
1659
|
-
`)),R()}if(L){D=!0,K=[];let
|
|
1660
|
-
`)),!0}if(
|
|
1661
|
-
`)),R()}if(D){let
|
|
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(Lt()),m.prompt(),m.line=se,m.cursor=se.length,m._refreshLine(),!0}function $e(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(su),ae=T.includes(ou);if(L&&ae){let se=vr(T);return se&&K.push(...se.split(`
|
|
1659
|
+
`)),R()}if(L){D=!0,K=[];let se=vr(T);return se&&K.push(...se.split(`
|
|
1660
|
+
`)),!0}if(ae){let se=vr(T);return se&&K.push(...se.split(`
|
|
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 fe=0;function pe(){if(fe>0){let x=y._scrollEnd,E="\x1B7";for(let A=0;A<fe;A++)E+=`\x1B[${x-fe+1+A};1H\x1B[2K`;E+="\x1B8",y.rawWrite(E),fe=0}}function xe(x){let E=[...
|
|
1665
|
-
${L}. `).trim()}let{loadSession:k}=Jt(),{setConversationMessages:j}=Se();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
|
|
1664
|
+
`)),R()):x.call(process.stdin,E,...A)}}let fe=0;function pe(){if(fe>0){let x=y._scrollEnd,E="\x1B7";for(let A=0;A<fe;A++)E+=`\x1B[${x-fe+1+A};1H\x1B[2K`;E+="\x1B8",y.rawWrite(E),fe=0}}function xe(x){let E=[...Sr,...ya()].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));fe=L.length,E.length>T&&fe++;let se=A-fe+1,we="\x1B7";for(let Ce=0;Ce<L.length;Ce++){let{cmd:tt,desc:nt}=L[Ce],Tn=tt.substring(0,x.length),wa=tt.substring(x.length),ba=" ".repeat(Math.max(0,ae-tt.length+2));we+=`\x1B[${se+Ce};1H\x1B[2K ${a.cyan}${Tn}${a.reset}${a.dim}${wa}${ba}${nt}${a.reset}`}E.length>T&&(we+=`\x1B[${se+L.length};1H\x1B[2K ${a.dim}\u2026 +${E.length-T} more${a.reset}`),we+="\x1B8",y.rawWrite(we)}process.stdin.isTTY&&process.stdin.on("keypress",(x,E)=>{pe(),!(E&&(E.name==="tab"||E.name==="return"))&&setImmediate(()=>{m.line&&m.line.startsWith("/")&&xe(m.line)})});let me=null,he=`${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}=Se();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:we,forceCompress:Ce}=Rt();if(we(se,[]).percentage>=30){let{messages:nt}=Ce(se,[]);j(nt)}}}}m.setPrompt(Lt()),m.prompt(),m.on("line",async x=>{if(pe(),Object.keys(X).length>0&&(x=$e(x),be(),m.setPrompt(Lt())),v){let L=x.trim();if(L){let{injectMidRunNote:ae}=Se();ae(L),process.stdout.write(`${a.cyan} \u270E Queued \u2014 will be applied in the next step${a.reset}
|
|
1666
1666
|
`),m.prompt()}return}if(me!==null){if(me._mode==="triple"){if(x.trim()==='"""'){let L=me.join(`
|
|
1667
|
-
`).trim();if(me=null,L){
|
|
1668
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${we}${a.reset}`)}}v=!1;let
|
|
1669
|
-
`).trim();if(me=null,L){
|
|
1670
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${Ce}${a.reset}`)}}let{getConversationLength:
|
|
1671
|
-
`)
|
|
1672
|
-
`)[0
|
|
1667
|
+
`).trim();if(me=null,L){$a(L.replace(/\n/g,"\\n")),v=!0,m.prompt(),M=0,C=!1,S&&(clearTimeout(S),S=null),tn=new AbortController;try{await n(L)}catch(se){if(!tn?.signal?.aborted){let we=se.message?.split(`
|
|
1668
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${we}${a.reset}`)}}v=!1;let ae=A();ae>0&&process.stdout.write(`${a.gray}[${ae} messages] ${a.reset}`)}m.setPrompt(Lt()),m.prompt();return}me.push(x),m.setPrompt(he),m.prompt();return}if(x.endsWith("\\"))me.push(x.slice(0,-1));else{me.push(x);let L=me.join(`
|
|
1669
|
+
`).trim();if(me=null,L){$a(L.replace(/\n/g,"\\n")),v=!0,m.prompt(),M=0,C=!1,S&&(clearTimeout(S),S=null),tn=new AbortController;try{await n(L)}catch(we){if(!tn?.signal?.aborted){let Ce=we.message?.split(`
|
|
1670
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${Ce}${a.reset}`)}}let{getConversationLength:ae}=Se();v=!1;let se=ae();se>0&&process.stdout.write(`${a.gray}[${se} messages] ${a.reset}`)}m.setPrompt(Lt()),m.prompt();return}m.setPrompt(he),m.prompt();return}if(x.trim()==='"""'||x.trim().startsWith('"""')){let L=x.trim().substring(3);me=L?[L]:[],me._mode="triple",m.setPrompt(he),m.prompt();return}if(x.endsWith("\\")){me=[x.slice(0,-1)],me._mode="backslash",m.setPrompt(he),m.prompt();return}let E=Re(x.trim());if(!E){m.setPrompt(Lt()),m.prompt();return}if($a(E),E==="/"){Gg(),m.setPrompt(Lt()),m.prompt();return}if(E.startsWith("/")){await kr(E,m);let L=kr._pendingAgentPrompt;if(L){kr._pendingAgentPrompt=null,v=!0,m.prompt(),M=0,C=!1,S&&(clearTimeout(S),S=null),tn=new AbortController;try{await n(L)}catch(ae){if(!tn?.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(Lt()),m.prompt();return}{let L=zE?"\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((we,Ce)=>{let tt=Ce===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",nt=2+we.length,Tn=" ".repeat(Math.max(0,ae-nt));console.log(`\x1B[2K${L}${tt} ${we}${Tn}\x1B[0m`)}),console.log()}if(process.env.NEX_AUTO_PLAN!=="0"&&!Vl()){let{isPlanMode:L,setPlanMode:ae}=ln(),{invalidateSystemPromptCache:se}=Se(),we=/\b(implement|refactor|migrate|redesign)\b/i,Ce=/\b(create|build|add|write|introduce|develop|set\s+up)\b/i,tt=/^(how|what|why|when|where|which|explain|show|list|tell|describe|can\s+you|could\s+you|do\s+you)\b/i,nt=/\b(spawn[_\s]?agents?|swarm)\b/i;!tt.test(E)&&!nt.test(E)&&(we.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}=Se();if(L()===0)try{let{detectCategory:ae,getModelForCategory:se}=In(),we=ae(E);if(we&&we.id!=="coding"){let Ce=se(we.id),tt=En();if(Ce&&Ce!==tt?.id&&eu(Ce)){let nt=En();console.log(`${a.dim}\u21B3 ${we.icon} ${we.label} task \u2014 routing to ${nt?.name||Ce}${a.reset}`),global._nexFooter&&global._nexFooter.setStatusInfo({model:nt?.name||Ce})}}}catch{}}v=!0,m.prompt(),M=0,C=!1,S&&(clearTimeout(S),S=null),tn=new AbortController;try{await n(E)}catch(L){if(!tn?.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}=Se(),T=A();T>0&&process.stdout.write(`${a.gray}[${T} messages] ${a.reset}`),m.setPrompt(Lt()),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)})}Zg.exports={startREPL:aT,getPrompt:Lt,loadHistory:Vg,appendHistory:$a,getHistoryPath:nu,HISTORY_MAX:tu,showCommandList:Gg,completer:zg,completeFilePath:Yg,handleSlashCommand:kr,showProviders:Zl,showHelp:Xg,renderBar:Jg,hasPasteStart:oT,hasPasteEnd:rT,stripPasteSequences:vr,getAbortSignal:Kg}});var e$=Q((GR,Qg)=>{"use strict";var cT=require("readline");function Ss(t){process.stdout.write(JSON.stringify(t)+`
|
|
1673
1674
|
`)}function lT(){process.env.NEX_SERVER="1";let t=(...c)=>process.stderr.write(c.map(String).join(" ")+`
|
|
1674
|
-
`);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=cT.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}=Se();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}=Se();d();for(let[f,p]of n)n.delete(f),p(!1);break}default:break}}),i.on("close",()=>{process.exit(0)})}Qg.exports={startServerMode:lT}});var n$=Q((YR,t$)=>{t$.exports=
|
|
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=cT.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}=Se();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}=Se();d();for(let[f,p]of n)n.delete(f),p(!1);break}default:break}}),i.on("close",()=>{process.exit(0)})}Qg.exports={startServerMode:lT}});var n$=Q((YR,t$)=>{t$.exports=ru()});var uu=require("path");require("dotenv").config({path:uu.join(__dirname,"..",".env")});require("dotenv").config();var ve=process.argv.slice(2);(ve.includes("--help")||ve.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
1675
1676
|
|
|
1676
1677
|
Options:
|
|
1677
1678
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -1691,6 +1692,6 @@ Options:
|
|
|
1691
1692
|
--mcp-config <path> Path to MCP server config (default: .nex/mcp.json)
|
|
1692
1693
|
-h, --help Show this help
|
|
1693
1694
|
-v, --version Show version
|
|
1694
|
-
`),process.exit(0));if(ve.includes("-v")||ve.includes("--version")){let t=As();console.log(t.version),process.exit(0)}var r$=ve.includes("--yolo")||ve.includes("-yolo");if(r$){let{setAutoConfirm:t}=ft();t(!0)}if(!r$)try{let t=require("fs"),e=
|
|
1695
|
+
`),process.exit(0));if(ve.includes("-v")||ve.includes("--version")){let t=As();console.log(t.version),process.exit(0)}var r$=ve.includes("--yolo")||ve.includes("-yolo");if(r$){let{setAutoConfirm:t}=ft();t(!0)}if(!r$)try{let t=require("fs"),e=uu.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 iu=ve.indexOf("--model");if(iu!==-1&&ve[iu+1]){let{setActiveModel:t}=je();t(ve[iu+1])}var au=ve.indexOf("--max-turns");if(au!==-1&&ve[au+1]){let t=parseInt(ve[au+1],10);if(t>0){let{setMaxIterations:e}=Se();e(t)}}else try{let t=require("fs"),e=uu.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}=Se();s(o)}}}catch{}var cu=ve.indexOf("--mcp-config");cu!==-1&&ve[cu+1]&&(process.env.NEX_MCP_CONFIG=ve[cu+1]);function lu(){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 uT(){let{runSetupWizard:t}=Ll();await t()}function s$(t){if(ve.includes("--auto")){let{setAutoConfirm:c}=ft();c(!0)}if(!ve.includes("--model")){let{setActiveModel:c}=je(),l=process.env.HEADLESS_MODEL||"devstral-small-2:24b";c(l)}let n=!ve.includes("--no-auto-orchestrate")&&process.env.NEX_AUTO_ORCHESTRATE!=="false",o=ve.indexOf("--orchestrator-model"),s=o!==-1?ve[o+1]:void 0;if(t.startsWith("/")){let{handleSlashCommand:c}=ru();c(t,null).then(()=>process.exit(0)).catch(l=>{console.error(l.message),process.exit(1)});return}let{processInput:r,getConversationMessages:i}=Se();r(t,null,{autoOrchestrate:n,orchestratorModel:s}).then(()=>{if(ve.includes("--json")){let l=i().filter(u=>u.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:l?.content||""}))}process.exit(0)}).catch(c=>{ve.includes("--json")?console.log(JSON.stringify({success:!1,error:c.message})):console.error(c.message),process.exit(1)})}if(ve.includes("--server")){let{setAutoConfirm:t}=ft();t(!0),e$().startServerMode();return}var o$=ve.indexOf("--prompt-file");if(o$!==-1){let t=ve[o$+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)),ve.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}lu(),s$(n)}else{let t=ve.indexOf("--task")!==-1?ve.indexOf("--task"):ve.indexOf("--prompt");if(t!==-1){let e=ve[t+1];if((!e||e.startsWith("--"))&&(console.error("--task/--prompt requires a prompt"),process.exit(1)),lu(),ve.includes("--orchestrate")){let n=ve.indexOf("--orchestrator-model"),o=n!==-1?ve[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 s$(e)}else uT().then(()=>{lu();let{startREPL:e}=n$();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(`
|
|
1695
1696
|
${l.dim}\u{1F4A1} ${c.length} new Ollama Cloud model(s) available \u2014 /benchmark --discover to test them${l.reset}
|
|
1696
1697
|
`)}}catch{}},3e3)})}
|