nex-code 0.3.84 → 0.3.85
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/nex-code.js +186 -186
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var G=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var On=G((ck,_m)=>{_m.exports={name:"nex-code",version:"0.3.
|
|
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),a=parseInt(s[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function _c(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function km(t){try{let n=require("fs").readFileSync(_c(),"utf8"),o=JSON.parse(n);if(o&&typeof o[t]=="boolean")return o[t]}catch{}return null}function vm(t,e){try{let n=require("fs"),o=require("path"),s=_c(),r=o.dirname(s),i={};try{i=JSON.parse(n.readFileSync(s,"utf8"))}catch{}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(l=>delete i[l]),n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(s,JSON.stringify(i),"utf8")}catch{}}function Sm(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let i=e.split(";"),a=parseInt(i[i.length-1],10);if(!isNaN(a))return a<8}let n=process.env.TERM_SESSION_ID||"default",o=km(n);if(o!==null)return o;let s=xm(),r=s!==null?s:!0;return vm(n,r),r}var xc=Sm(),kc={reset:wc,bold:bc,dim:Nn,primary:
|
|
2
|
+
var G=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var On=G((ck,_m)=>{_m.exports={name:"nex-code",version:"0.3.85",description:"The open-source agentic coding CLI. Free with Ollama Cloud \u2014 switch to OpenAI, Anthropic or Gemini anytime. Alternative to Claude Code & Gemini CLI.",bin:{"nex-code":"./dist/nex-code.js"},files:["dist/","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",test:"jest --forceExit","test:orchestrator":"jest tests/orchestrator.test.js --forceExit",coverage:"jest --coverage --forceExit","test:watch":"jest --watch",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",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"},jest:{coverageThreshold:{global:{lines:45,functions:30,branches:35},"./cli/sub-agent.js":{lines:70,functions:60,branches:55}}}}});var fn=G((lk,Sc)=>{"use strict";var wc="\x1B[0m",bc="\x1B[1m",Nn="\x1B[2m";function j(t,e,n){return`\x1B[38;2;${t};${e};${n}m`}function xm(){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),a=parseInt(s[3].slice(0,2),16);return .299*r+.587*i+.114*a<128}}catch{}return null}function _c(){let t=require("os");return require("path").join(t.homedir(),".nex-code",".theme_cache.json")}function km(t){try{let n=require("fs").readFileSync(_c(),"utf8"),o=JSON.parse(n);if(o&&typeof o[t]=="boolean")return o[t]}catch{}return null}function vm(t,e){try{let n=require("fs"),o=require("path"),s=_c(),r=o.dirname(s),i={};try{i=JSON.parse(n.readFileSync(s,"utf8"))}catch{}i[t]=e;let a=Object.keys(i);a.length>50&&a.slice(0,a.length-50).forEach(l=>delete i[l]),n.existsSync(r)||n.mkdirSync(r,{recursive:!0}),n.writeFileSync(s,JSON.stringify(i),"utf8")}catch{}}function Sm(){let t=(process.env.NEX_THEME||"").toLowerCase();if(t==="light")return!1;if(t==="dark")return!0;let e=process.env.COLORFGBG;if(e){let i=e.split(";"),a=parseInt(i[i.length-1],10);if(!isNaN(a))return a<8}let n=process.env.TERM_SESSION_ID||"default",o=km(n);if(o!==null)return o;let s=xm(),r=s!==null?s:!0;return vm(n,r),r}var xc=Sm(),kc={reset:wc,bold:bc,dim:Nn,primary:j(80,190,255),secondary:j(60,170,190),success:j(80,210,120),warning:j(245,175,50),error:j(230,80,80),muted:Nn,subtle:j(130,130,145),tool_read:j(80,190,255),tool_write:j(245,165,55),tool_exec:j(185,100,235),tool_search:j(70,185,190),tool_git:j(90,210,100),tool_web:j(100,215,250),tool_sysadmin:j(225,150,75),tool_default:j(100,205,115),syn_keyword:j(185,100,235),syn_string:j(90,210,120),syn_number:j(245,175,50),syn_comment:Nn,syn_key:j(80,190,255),diff_add:j(80,210,120),diff_rem:j(230,80,80),banner_logo:j(80,200,255),banner_name:j(80,200,255),banner_version:Nn,banner_model:Nn,banner_yolo:j(245,175,50),footer_sep:Nn,footer_model:j(80,175,235),footer_branch:j(80,210,100),footer_project:j(130,130,145),footer_divider:j(80,80,95),footer_mode:j(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"},vc={reset:wc,bold:bc,dim:j(110,110,120),primary:j(0,110,190),secondary:j(0,125,148),success:j(0,148,62),warning:j(168,92,0),error:j(188,32,32),muted:j(110,110,120),subtle:j(155,155,165),tool_read:j(0,110,190),tool_write:j(168,92,0),tool_exec:j(128,42,188),tool_search:j(0,122,148),tool_git:j(0,138,62),tool_web:j(0,112,178),tool_sysadmin:j(168,82,0),tool_default:j(0,138,62),syn_keyword:j(128,42,188),syn_string:j(0,138,62),syn_number:j(168,92,0),syn_comment:j(135,135,148),syn_key:j(0,110,190),diff_add:j(0,148,62),diff_rem:j(188,32,32),banner_logo:j(0,122,205),banner_name:j(0,122,205),banner_version:j(100,100,118),banner_model:j(100,100,118),banner_yolo:j(168,62,0),footer_sep:j(168,168,178),footer_model:j(0,102,175),footer_branch:j(0,138,62),footer_project:j(135,135,148),footer_divider:j(168,168,178),footer_mode:j(148,88,0),white:j(40,40,52),red:j(188,32,32),green:j(0,148,62),yellow:j(168,92,0),blue:j(0,110,190),magenta:j(128,42,188),cyan:j(0,125,148),gray:j(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:j(0,158,182),brightMagenta:j(158,52,208),brightBlue:j(0,112,208)},Em=xc?kc:vc;Sc.exports={T:Em,isDark:xc,DARK:kc,LIGHT:vc}});var Pn=G((uk,Tc)=>{var{T:K}=fn(),fo=5,Mn=(()=>{let t=[];for(let e=0;e<fo;e++)t.push(e);for(let e=fo-2;e>=1;e--)t.push(e);return t})(),Ec=["\u273D","\u2726","\u2727","\u2726"],Gr=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=Mn[this.frame%Mn.length],n="";for(let s=0;s<fo;s++)n+=s===e?`${K.cyan}\u25CF${K.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=` ${K.dim}${r}m ${String(i).padStart(2,"0")}s${K.reset}`}else s>=1&&(o=` ${K.dim}${s}s${K.reset}`)}process.stderr.write(`\x1B[2K\r${n} ${K.dim}${this.text}${K.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}},Kr=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=Mn[this.frame%Mn.length],n=`${K.cyan}\u25CF${K.reset}`,o=`${K.dim}\u25CB${K.reset}`,s=this._formatElapsed(),r=s?` ${K.dim}${s}${K.reset}`:"",i="";for(let a=0;a<this.labels.length;a++){let l,u;switch(this.statuses[a]){case"done":l=`${K.green}\u2713${K.reset}`,u=K.dim;break;case"error":l=`${K.red}\u2717${K.reset}`,u=K.dim;break;default:l=a===e?n:" ",u=""}let d=a===this.labels.length-1?r:"";i+=`\x1B[2K ${l} ${u}${this.labels[a]}${K.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(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),n=e?` ${K.dim}${e}${K.reset}`:"",o="";for(let s=0;s<this.labels.length;s++){let r;switch(this.statuses[s]){case"done":r=`${K.green}\u2713${K.reset}`;break;case"error":r=`${K.red}\u2717${K.reset}`;break;default:r=`${K.yellow}\u25CB${K.reset}`}let i=s===this.labels.length-1?n:"";o+=`\x1B[2K ${r} ${K.dim}${this.labels[s]}${K.reset}${i}
|
|
6
6
|
`}process.stderr.write(o)}},lo={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},uo={done:K.green,in_progress:K.cyan,pending:K.dim,failed:K.red},Jt=null,Yr=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=Ec[this.frame%Ec.length],n=this._formatElapsed(),o=this._formatTokens(),s=[n,o?`\u2193 ${o} tokens`:""].filter(Boolean).join(" \xB7 "),r=s?` ${K.dim}(${s})${K.reset}`:"",i=`\x1B[2K${K.cyan}${e}${K.reset} ${this.name}\u2026${r}
|
|
@@ -24,15 +24,15 @@ ${h}`}else{let h=a.slice(0,m).map(p=>` ${C.muted}${p}${C.reset}`).join(`
|
|
|
24
24
|
${h}
|
|
25
25
|
${C.subtle}\u2026 +${l-m} lines${C.reset}`}break}case"edit_file":{let a=(e.old_text||"").split(`
|
|
26
26
|
`),l=(e.new_text||"").split(`
|
|
27
|
-
`),u=a.length,d=l.length,f=e.path?require("path").basename(e.path):null,m=f?` ${C.muted}${f}${C.reset}`:"",h=a.find(
|
|
27
|
+
`),u=a.length,d=l.length,f=e.path?require("path").basename(e.path):null,m=f?` ${C.muted}${f}${C.reset}`:"",h=a.find(y=>y.trim()),p=l.find(y=>y.trim()),g=[];h&&g.push(` ${C.diff_rem}- ${C.reset}${C.muted}${h.trimEnd().substring(0,72)}${C.reset}`),p&&g.push(` ${C.diff_add}+ ${C.reset}${C.muted}${p.trimEnd().substring(0,72)}${C.reset}`),r=`${C.diff_rem}\u2212${u}${C.reset} ${C.diff_add}+${d}${C.reset}${m}`+(g.length>0?`
|
|
28
28
|
`+g.join(`
|
|
29
29
|
`):"");break}case"patch_file":{let a=e.patches||[],l=a.reduce((d,f)=>d+(f.old_text||"").split(`
|
|
30
30
|
`).length,0),u=a.reduce((d,f)=>d+(f.new_text||"").split(`
|
|
31
31
|
`).length,0);r=`${C.reset}${a.length} patch${a.length!==1?"es":""} ${C.diff_rem}\u2212${l}${C.reset} ${C.diff_add}+${u}${C.reset}`;break}case"bash":{let l=s.match(/^EXIT (\d+)/),u=s.split(`
|
|
32
|
-
`).filter(m=>m&&!m.startsWith("EXIT ")&&!m.startsWith("HINT:")&&m.trim()),d=l?l[1]==="0"?`${C.success}\u2713${C.reset}`:`${C.error}\u2717 Exit ${l[1]}${C.reset}`:`${C.success}\u2713${C.reset}`,f=s.match(/\nHINT: (.+)/);if(f)r=`${d} ${C.muted}\u2014 ${f[1].substring(0,100)}${C.reset}`;else if(u.length===0)r=d;else{let m=l&&l[1]!=="0",h=m?u.slice(-3):u.slice(0,3),p=u.length-3,g=h.map((w
|
|
33
|
-
`)}break}case"grep":case"search_files":{if(s.includes("(no matches)")||s==="no matches")r=`No matches${e.pattern?` ${C.muted}"${String(e.pattern).substring(0,40)}"${C.reset}`:""}`;else{let p=function(
|
|
34
|
-
`).filter(Boolean),u=l.length,f=new Set(l.map(
|
|
35
|
-
${p(
|
|
32
|
+
`).filter(m=>m&&!m.startsWith("EXIT ")&&!m.startsWith("HINT:")&&m.trim()),d=l?l[1]==="0"?`${C.success}\u2713${C.reset}`:`${C.error}\u2717 Exit ${l[1]}${C.reset}`:`${C.success}\u2713${C.reset}`,f=s.match(/\nHINT: (.+)/);if(f)r=`${d} ${C.muted}\u2014 ${f[1].substring(0,100)}${C.reset}`;else if(u.length===0)r=d;else{let m=l&&l[1]!=="0",h=m?u.slice(-3):u.slice(0,3),p=u.length-3,g=h.map((y,w)=>w===0?`${d} ${C.muted}${y.substring(0,120)}${C.reset}`:` ${C.muted}${y.substring(0,120)}${C.reset}`);if(p>0){let y=m?` ${C.subtle}${p} lines above\u2026${C.reset}`:` ${C.subtle}\u2026 +${p} lines${C.reset}`;m?g.unshift(y):g.push(y)}r=g.join(`
|
|
33
|
+
`)}break}case"grep":case"search_files":{if(s.includes("(no matches)")||s==="no matches")r=`No matches${e.pattern?` ${C.muted}"${String(e.pattern).substring(0,40)}"${C.reset}`:""}`;else{let p=function(w){let k=w.indexOf(":");if(k===-1)return`${C.muted}${w.substring(0,90)}${C.reset}`;let R=w.substring(0,k),x=w.substring(k+1),_=x.match(/^(\d+)[:-](.*)/s),b=_?`:${_[1]}`:"",A=(_?_[2]:x).trim(),O=`${C.subtle}${a.basename(R)}${b}${C.reset}`,P=`${C.muted}${A.substring(0,80)}${A.length>80?"\u2026":""}${C.reset}`;return`${O} ${P}`};var i=p;let a=require("path"),l=s.split(`
|
|
34
|
+
`).filter(Boolean),u=l.length,f=new Set(l.map(w=>w.split(":")[0]).filter(Boolean)).size,m=e.pattern?` ${C.muted}"${String(e.pattern).substring(0,40)}"${C.reset}`:"",h=f>1?`${u} match${u!==1?"es":""} in ${f} files${m}`:`${u} match${u!==1?"es":""}${m}`,g=l.slice(0,3).map((w,k)=>k===0?`${h}
|
|
35
|
+
${p(w)}`:` ${p(w)}`),y=l.length-3;y>0&&g.push(` ${C.subtle}\u2026 +${y} lines${C.reset}`),r=g.join(`
|
|
36
36
|
`)}break}case"glob":{let a=e.pattern?` ${C.muted}${String(e.pattern).substring(0,50)}${C.reset}`:"";if(s==="(no matches)")r=`No files found${a}`;else{let l=require("path"),u=s.split(`
|
|
37
37
|
`).filter(Boolean),d=u.length,f=u.slice(0,5).map(p=>l.basename(p)),m=d-f.length,h=f.join(", ")+(m>0?`, +${m} more`:"");r=`${d} file${d!==1?"s":""}${a} \u2014 ${C.muted}${h}${C.reset}`}break}case"list_directory":{if(s==="(empty)")r="0 entries";else{let a=s.split(`
|
|
38
38
|
`).filter(Boolean),l=a.length,u=a.slice(0,6).join(", "),d=l-6;r=d>0?`${l} entries \u2014 ${C.muted}${u}, +${d} more${C.reset}`:`${l} entr${l!==1?"ies":"y"} \u2014 ${C.muted}${u}${C.reset}`}break}case"git_status":{let a=s.match(/Branch:\s*(\S+)/),l=s.split(`
|
|
@@ -42,16 +42,16 @@ ${h}
|
|
|
42
42
|
|
|
43
43
|
`).filter(Boolean),l=a.length,u=a[0]?a[0].split(`
|
|
44
44
|
`)[0].replace(/^\d+\.\s*/,"").trim():null,d=u?` ${C.muted}\u2014 ${u.substring(0,70)}${C.reset}`:"";r=`${l} result${l!==1?"s":""}${d}`;break}case"task_list":r="Done";break;case"spawn_agents":{let a=(s.match(/✓ Agent/g)||[]).length,l=(s.match(/✗ Agent/g)||[]).length;r=l>0?`${a} done, ${l} failed`:`${a} agent${a!==1?"s":""} done`;break}case"switch_model":{let a=s.match(/Switched to (.+)/);r=a?`\u2192 ${a[1]}`:"Done";break}case"ssh_exec":{let l=s.startsWith("EXIT ")||s.startsWith("Command failed"),u=s.split(`
|
|
45
|
-
`).filter(f=>f.trim()&&!f.startsWith("EXIT ")),d=l?`${C.error}\u2717${C.reset}`:`${C.success}\u2713${C.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 m=l?u.slice(-3):u.slice(0,3),h=u.length-3,p=m.map((g,
|
|
45
|
+
`).filter(f=>f.trim()&&!f.startsWith("EXIT ")),d=l?`${C.error}\u2717${C.reset}`:`${C.success}\u2713${C.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 m=l?u.slice(-3):u.slice(0,3),h=u.length-3,p=m.map((g,y)=>y===0?`${d} ${C.muted}${g.substring(0,120)}${C.reset}`:` ${C.muted}${g.substring(0,120)}${C.reset}`);if(h>0){let g=l?` ${C.subtle}${h} lines above\u2026${C.reset}`:` ${C.subtle}\u2026 +${h} lines${C.reset}`;l?p.unshift(g):p.push(g)}r=p.join(`
|
|
46
46
|
`)}break}default:{let a=s.split(`
|
|
47
47
|
`).filter(l=>l.trim()&&!l.startsWith("EXIT ")&&!l.startsWith("HINT:"));if(a.length>0){let l=a[0].trim().substring(0,90),u=a.length>1?` ${C.subtle}\u2026 +${a.length-1} lines${C.reset}`:"";r=`${C.muted}${l}${C.reset}${u}`}else r="Done"}}return` ${C.muted}\u2514 ${r}${C.reset}`}function Lm(t,e,n,o,s,r){let i=[...n.values()].reduce((d,f)=>d+f,0),a=Math.round(o/1e3),l=a>=60?`${Math.floor(a/60)}m ${a%60}s`:`${a}s`,u=`
|
|
48
|
-
${C.success}\u25C6${ot.reset} ${ot.bold}${t}${ot.reset}`;return u+=`${ot.dim} \xB7 ${e} step${e!==1?"s":""}`,u+=` \xB7 ${i} tool${i!==1?"s":""}`,u+=` \xB7 ${l}`,r.size>0&&(u+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),u+=ot.reset,u}Cc.exports={C:ot,formatToolCall:Nm,formatResult:Mm,getToolSpinnerText:Pm,formatToolSummary:Im,formatSectionHeader:Om,formatMilestone:Lm}});var Ce=G((fk,Nc)=>{var{T:pn}=fn(),Jr=pn,Oc=["01100110","01111110","01111110","01011010","01111110","00111100"];function Dm(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",a=o+1<t.length&&t[o+1][r]==="1";i&&a?s+=`${e}\u2588\x1B[0m`:i&&!a?s+=`${e}\u2580\x1B[0m`:!i&&a?s+=`${e}\u2584\x1B[0m`:s+=" "}n.push(s)}return n}function jm(t,e,n={}){let o=Jr.bold,s=Jr.reset,r=Dm(Oc,pn.banner_logo),i=n.yolo?` ${o}${pn.banner_yolo}\u26A1 YOLO${s}`:"",a=On().version,l=[` ${pn.banner_name}${o}nex-code${s} ${pn.banner_version}v${a}${s}`,` ${pn.banner_model}${t}${s} ${pn.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),m=Oc[0].length,h=[];for(let p=0;p<u;p++){let g=r[p-d]??" ".repeat(m),
|
|
48
|
+
${C.success}\u25C6${ot.reset} ${ot.bold}${t}${ot.reset}`;return u+=`${ot.dim} \xB7 ${e} step${e!==1?"s":""}`,u+=` \xB7 ${i} tool${i!==1?"s":""}`,u+=` \xB7 ${l}`,r.size>0&&(u+=` \xB7 ${r.size} file${r.size!==1?"s":""} modified`),u+=ot.reset,u}Cc.exports={C:ot,formatToolCall:Nm,formatResult:Mm,getToolSpinnerText:Pm,formatToolSummary:Im,formatSectionHeader:Om,formatMilestone:Lm}});var Ce=G((fk,Nc)=>{var{T:pn}=fn(),Jr=pn,Oc=["01100110","01111110","01111110","01011010","01111110","00111100"];function Dm(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",a=o+1<t.length&&t[o+1][r]==="1";i&&a?s+=`${e}\u2588\x1B[0m`:i&&!a?s+=`${e}\u2580\x1B[0m`:!i&&a?s+=`${e}\u2584\x1B[0m`:s+=" "}n.push(s)}return n}function jm(t,e,n={}){let o=Jr.bold,s=Jr.reset,r=Dm(Oc,pn.banner_logo),i=n.yolo?` ${o}${pn.banner_yolo}\u26A1 YOLO${s}`:"",a=On().version,l=[` ${pn.banner_name}${o}nex-code${s} ${pn.banner_version}v${a}${s}`,` ${pn.banner_model}${t}${s} ${pn.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),m=Oc[0].length,h=[];for(let p=0;p<u;p++){let g=r[p-d]??" ".repeat(m),y=l[p-f]??"";h.push(g+y)}console.log(`
|
|
49
49
|
`+h.join(`
|
|
50
50
|
`)+`
|
|
51
|
-
`)}var{Spinner:qm,MultiProgress:Fm,TaskProgress:Um,ToolProgress:Wm,setActiveTaskProgress:Bm,getActiveTaskProgress:Hm,cleanupTerminal:Gm}=Pn(),{formatToolCall:Km,formatResult:Ym,getToolSpinnerText:zm,formatToolSummary:Xm,formatSectionHeader:Jm,formatMilestone:Vm}=Ac();Nc.exports={C:Jr,banner:jm,Spinner:qm,MultiProgress:Fm,TaskProgress:Um,ToolProgress:Wm,setActiveTaskProgress:Bm,getActiveTaskProgress:Hm,cleanupTerminal:Gm,formatToolCall:Km,formatResult:Ym,getToolSpinnerText:zm,formatToolSummary:Xm,formatSectionHeader:Jm,formatMilestone:Vm}});var Xe=G((pk,jc)=>{var Qm=require("readline"),{C:Mt}=Ce(),Zr=[/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/],Mc=[...Zr,/\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 Zm(t){for(let e of Mc)if(e.test(t))return e;return null}var Pc=[/\.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)/],eh=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,Vr=[/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 Ic(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 a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>s(u)):Vr.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Vr.some(a=>a.test(i))};return o.every(s)}var ei=[/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)/],Lc=[/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/],Dc=[...ei,...Lc],ti=!1,mn=null,Qr=null;function th(t){ti=t}function nh(t){Qr=t}function sh(){return ti}function oh(t){mn=t}function rh(t){for(let e of Zr)if(e.test(t))return e;return null}function ih(t){if(/ssh\s/.test(t)&&Ic(t))return!1;for(let e of Dc)if(e.test(t))return!0;return!1}function ah(t){for(let e of ei)if(e.test(t))return!0;return!1}function ch(t){if(process.env.NEX_UNPROTECT==="1"||!eh.test(t))return null;for(let e of Pc)if(e.test(t))return e;return null}function lh(t,e={}){if(ti)return Promise.resolve(!0);if(Qr)return Qr(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return uh(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;mn&&mn.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)},a=()=>{let f=i(),m=`\x1B[${f};1H\x1B[2K${Mt.yellow}${t}${Mt.reset}`;for(let h=0;h<n.length;h++){let p=h===s,g=p?`${Mt.yellow}\u276F${Mt.reset}`:" ",
|
|
51
|
+
`)}var{Spinner:qm,MultiProgress:Fm,TaskProgress:Um,ToolProgress:Wm,setActiveTaskProgress:Bm,getActiveTaskProgress:Hm,cleanupTerminal:Gm}=Pn(),{formatToolCall:Km,formatResult:Ym,getToolSpinnerText:zm,formatToolSummary:Xm,formatSectionHeader:Jm,formatMilestone:Vm}=Ac();Nc.exports={C:Jr,banner:jm,Spinner:qm,MultiProgress:Fm,TaskProgress:Um,ToolProgress:Wm,setActiveTaskProgress:Bm,getActiveTaskProgress:Hm,cleanupTerminal:Gm,formatToolCall:Km,formatResult:Ym,getToolSpinnerText:zm,formatToolSummary:Xm,formatSectionHeader:Jm,formatMilestone:Vm}});var Xe=G((pk,jc)=>{var Qm=require("readline"),{C:Mt}=Ce(),Zr=[/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/],Mc=[...Zr,/\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 Zm(t){for(let e of Mc)if(e.test(t))return e;return null}var Pc=[/\.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)/],eh=/\b(?:rm|rmdir|unlink|truncate|shred|mv|cp)\b/,Vr=[/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 Ic(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 a=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return a?a.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>s(u)):Vr.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Vr.some(a=>a.test(i))};return o.every(s)}var ei=[/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)/],Lc=[/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/],Dc=[...ei,...Lc],ti=!1,mn=null,Qr=null;function th(t){ti=t}function nh(t){Qr=t}function sh(){return ti}function oh(t){mn=t}function rh(t){for(let e of Zr)if(e.test(t))return e;return null}function ih(t){if(/ssh\s/.test(t)&&Ic(t))return!1;for(let e of Dc)if(e.test(t))return!0;return!1}function ah(t){for(let e of ei)if(e.test(t))return!0;return!1}function ch(t){if(process.env.NEX_UNPROTECT==="1"||!eh.test(t))return null;for(let e of Pc)if(e.test(t))return e;return null}function lh(t,e={}){if(ti)return Promise.resolve(!0);if(Qr)return Qr(t,e);if(!process.stdout.isTTY||!process.stdin.isTTY)return uh(t,e);let n=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(o=>{let s=0;mn&&mn.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)},a=()=>{let f=i(),m=`\x1B[${f};1H\x1B[2K${Mt.yellow}${t}${Mt.reset}`;for(let h=0;h<n.length;h++){let p=h===s,g=p?`${Mt.yellow}\u276F${Mt.reset}`:" ",y=p?`${Mt.yellow}${n[h]}${Mt.reset}`:n[h];m+=`\x1B[${f+1+h};1H\x1B[2K ${g} ${y}`}r(m)},l=f=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",d);let m=global._nexRawWrite||(g=>process.stdout.write(g)),h=i(),p="";for(let g=0;g<n.length+1;g++)p+=`\x1B[${h+g};1H\x1B[2K`;m(p),global._nexFooter&&global._nexFooter.drawFooter(),mn&&mn.resume(),o(f)},u=f=>{if(f===1){l(!1);return}f===2&&e.toolName&&mo(e.toolName),l(!0)},d=f=>{if(f[0]===3){l(!1);return}let m=f.toString();if(m==="\r"||m===`
|
|
52
52
|
`){u(s);return}if(m==="\x1B[A"){s=(s-1+n.length)%n.length,a();return}if(m==="\x1B[B"){s=(s+1)%n.length,a();return}let h=m.toLowerCase().trim();if(h==="y"){l(!0);return}if(h==="n"){l(!1);return}if(h==="a"&&e.toolName){mo(e.toolName),l(!0);return}};a(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",d)})}function uh(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?(mo(e.toolName),o(!0)):o(i!=="n")};if(mn)mn.question(`${Mt.yellow}${t} ${n}${Mt.reset}`,s);else{let r=Qm.createInterface({input:process.stdin,output:process.stdout});r.question(`${Mt.yellow}${t} ${n}${Mt.reset}`,i=>{r.close(),s(i)})}})}var mo=()=>{};function dh(t){mo=t}jc.exports={FORBIDDEN_PATTERNS:Zr,SSH_FORBIDDEN_PATTERNS:Mc,BASH_PROTECTED_PATHS:Pc,SSH_SAFE_PATTERNS:Vr,isSSHReadOnly:Ic,DANGEROUS_BASH:Dc,CRITICAL_BASH:ei,NOTABLE_BASH:Lc,isForbidden:rh,isSSHForbidden:Zm,isDangerous:ih,isCritical:ah,isBashPathForbidden:ch,confirm:lh,setAutoConfirm:th,getAutoConfirm:sh,setConfirmHook:nh,setReadlineInterface:oh,setAllowAlwaysHandler:dh}});var In=G((mk,qc)=>{async function fh(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 a=[];n.on("data",l=>a.push(l)),n.on("end",()=>r(Buffer.concat(a).toString("utf8"))),n.on("error",i)}),s=JSON.parse(o);return e(s)||o||t.message}catch{return t.message}}var ni=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`)}};qc.exports={BaseProvider:ni,readStreamErrorBody:fh}});var Wc=G((hk,Uc)=>{var ho=require("axios"),ph=require("http"),mh=require("https"),{BaseProvider:hh,readStreamErrorBody:gh}=In(),go=new ph.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),$o=new mh.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Fc={"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:131072},"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},"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":{id:"glm-5",name:"GLM 5",maxTokens:16384,contextWindow:128e3},"glm-4.7":{id:"glm-4.7",name:"GLM 4.7",maxTokens:16384,contextWindow:128e3},"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}},si=class extends hh{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Fc,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){ho.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:go,httpsAgent:$o}).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 ho.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:go,httpsAgent:$o})).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(`
|
|
53
|
-
`)};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,a;try{a=await ho.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:n&&n.length>0?n:void 0,stream:!1,options:{temperature:o.temperature??this.temperature,num_predict:i}},{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:go,httpsAgent:$o})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let u=l.response?.status?` [HTTP ${l.response.status}]`:"",d=l.response?.data?.error||l.message;throw new Error(`API Error${u}: ${d}`)}return this.normalizeResponse(a.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,a=o.onToken||(()=>{}),l=o.onThinkingToken||(()=>{}),u;try{u=await ho.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:n&&n.length>0?n:void 0,stream:!0,options:{temperature:o.temperature??this.temperature,num_predict:i}},{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:go,httpsAgent:$o})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",m=await gh(d,h=>h?.error);throw new Error(`API Error${f}: ${m}`)}return new Promise((d,f)=>{let m="",h=[],p="";o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),f(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{p+=g.toString();let
|
|
54
|
-
`);p=
|
|
53
|
+
`)};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,a;try{a=await ho.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:n&&n.length>0?n:void 0,stream:!1,options:{temperature:o.temperature??this.temperature,num_predict:i}},{timeout:o.timeout||this.timeout,headers:this._getHeaders(),httpAgent:go,httpsAgent:$o})}catch(l){if(l.name==="CanceledError"||l.name==="AbortError"||l.code==="ERR_CANCELED")throw l;let u=l.response?.status?` [HTTP ${l.response.status}]`:"",d=l.response?.data?.error||l.message;throw new Error(`API Error${u}: ${d}`)}return this.normalizeResponse(a.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,a=o.onToken||(()=>{}),l=o.onThinkingToken||(()=>{}),u;try{u=await ho.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:n&&n.length>0?n:void 0,stream:!0,options:{temperature:o.temperature??this.temperature,num_predict:i}},{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal,httpAgent:go,httpsAgent:$o})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.status?` [HTTP ${d.response.status}]`:"",m=await gh(d,h=>h?.error);throw new Error(`API Error${f}: ${m}`)}return new Promise((d,f)=>{let m="",h=[],p="";o.signal&&o.signal.addEventListener("abort",()=>{u.data.destroy(),f(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{p+=g.toString();let y=p.split(`
|
|
54
|
+
`);p=y.pop()||"";for(let w of y){if(!w.trim())continue;let k;try{k=JSON.parse(w)}catch{continue}if(k.message?.thinking&&l(k.message.thinking),k.message?.content&&(a(k.message.content),m+=k.message.content),k.message?.tool_calls&&(h=h.concat(k.message.tool_calls)),k.done){d({content:m,tool_calls:this._normalizeToolCalls(h)});return}}}),u.data.on("error",g=>{o.signal?.aborted||f(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{if(p.trim())try{let g=JSON.parse(p);g.message?.thinking&&l(g.message.thinking),g.message?.content&&(a(g.message.content),m+=g.message.content),g.message?.tool_calls&&(h=h.concat(g.message.tool_calls))}catch{}d({content:m,tool_calls:this._normalizeToolCalls(h)})})})}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:this._normalizeToolCalls(n.tool_calls||[])}}_normalizeToolCalls(e){return e.map((n,o)=>({id:n.id||`ollama-${Date.now()}-${o}`,function:{name:n.function?.name||n.name||"unknown",arguments:n.function?.arguments||n.arguments||{}}}))}};Uc.exports={OllamaProvider:si,OLLAMA_MODELS:Fc}});var zc=G((gk,Yc)=>{var{callChat:$h}=Ae(),{estimateTokens:oi}=Qe(),Bc=process.env.NEX_COMPACTION!=="false",Hc=6,Gc=500,yh=`Summarize this conversation history concisely. Focus on:
|
|
55
55
|
- What files were read, created, or modified
|
|
56
56
|
- Key decisions made and their rationale
|
|
57
57
|
- Current state of the task (what's done, what's pending)
|
|
@@ -61,26 +61,26 @@ ${o}`,_compacted:!0,_originalCount:t.length},tokensRemoved:s-r}}catch{return nul
|
|
|
61
61
|
tools: ${s}`}return`[${n}] ${o}`}).join(`
|
|
62
62
|
|
|
63
63
|
`)}Yc.exports={compactMessages:wh,formatMessagesForSummary:Kc,COMPACTION_ENABLED:Bc,COMPACTION_MIN_MESSAGES:Hc,COMPACTION_SUMMARY_BUDGET:Gc}});var Qe=G(($k,sl)=>{var bh=require("path");function Jc(){return Ae().getActiveModel()}var _h={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},hn=new Map,Xc=1e3,ri=new WeakMap,ls=null;function xh(){if(ls!==null)return ls;try{let e=Jc()?.provider||"ollama";return ls=_h[e]||4,ls}catch{return 4}}function kh(){ls=null}function gn(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=80?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length-20)}`,n=hn.get(e);if(n!==void 0)return hn.delete(e),hn.set(e,n),n;let o=Math.ceil(t.length/xh());if(hn.size>=Xc){let s=Xc>>1,r=hn.keys();for(let i=0;i<s;i++)hn.delete(r.next().value)}return hn.set(e,o),o}function vh(t){if(ri.has(t))return ri.get(t);let e=JSON.stringify(t);return ri.set(t,e),e}function Dn(t){let n=4;if(t.content&&(n+=gn(t.content)),t.tool_calls)for(let o of t.tool_calls){n+=4,n+=gn(o.function?.name||"");let s=o.function?.arguments;typeof s=="string"?n+=gn(s):s&&(n+=gn(JSON.stringify(s)))}return n}function _t(t){let e=0;for(let n of t)e+=Dn(n);return e}function Sh(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+=Dn(e[r]);return s}function yo(t){return!t||t.length===0?0:gn(JSON.stringify(t))}function wo(){return Jc()?.contextWindow||32768}function Eh(t,e){let n=_t(t),o=yo(e),s=n+o,r=wo(),i=r>0?s/r*100:0,a=0,l=0,u=0;for(let d of t){let f=Dn(d);d.role==="system"?a+=f:d.role==="tool"?u+=f:l+=f}return{used:s,limit:r,percentage:Math.round(i*10)/10,breakdown:{system:a,conversation:l,toolResults:u,toolDefinitions:o},messageCount:t.length}}var Vc=parseFloat(process.env.NEX_COMPRESSION_THRESHOLD)||.75,Qc=parseFloat(process.env.NEX_SAFETY_MARGIN)||.1,Zc=parseInt(process.env.NEX_KEEP_RECENT,10)||10,Th=200,Rh=500;function el(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(`
|
|
64
|
-
`);if(s.length<=10){let p=Math.floor(o*.6),g=Math.floor(o*.4),
|
|
64
|
+
`);if(s.length<=10){let p=Math.floor(o*.6),g=Math.floor(o*.4),y=t.substring(0,p),w=t.substring(t.length-g);return y+`
|
|
65
65
|
...(${t.length} chars total)...
|
|
66
|
-
|
|
66
|
+
`+w}let r=Math.floor(s.length*.4),i=Math.floor(s.length*.4),a=[],l=0,u=Math.floor(o*.4);for(let p=0;p<r&&l<u;p++)if(l+s[p].length+1>u&&s[p].trim().startsWith("```")){a.push(s[p]),l+=s[p].length+1;let g=p+1;for(;g<s.length&&l<u*1.5&&!s[g].trim().startsWith("```");)a.push(s[g]),l+=s[g].length+1,g++;g<s.length&&s[g].trim().startsWith("```")&&(a.push(s[g]),l+=s[g].length+1),p=g}else a.push(s[p]),l+=s[p].length+1;let d=[],f=0,m=Math.floor(o*.4);for(let p=s.length-1;p>=s.length-i&&f<m;p--)if(f+s[p].length+1>m&&s[p].trim().startsWith("```")){d.push(s[p]),f+=s[p].length+1;let g=p-1;for(;g>=0&&f<m*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),p=g}else d.push(s[p]),f+=s[p].length+1;d.reverse();let h=s.length-a.length-d.length;return a.join(`
|
|
67
67
|
`)+`
|
|
68
68
|
...(${h} lines omitted, ${s.length} total)...
|
|
69
69
|
`+d.join(`
|
|
70
70
|
`)}function Ln(t,e="light"){let n=e==="aggressive"?100:e==="medium"?200:Rh,o=e==="aggressive"?50:e==="medium"?100:Th;if(t.role==="tool"){let s=typeof t.content=="string"?t.content:JSON.stringify(t.content);return s.length>o?{...t,content:el(s,o)}:t}if(t.role==="assistant"){let s={...t};return s.content&&s.content.length>n&&(s.content=s.content.substring(0,n)+`
|
|
71
|
-
...(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 tl(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||""),a=0;for(let l of o)(i.includes(l)||i.includes(bh.basename(l)))&&a++;s+=Math.min(30,a*10)}return Math.min(100,s)}function nl(t,e=10){let n=new Set,o=t.slice(-e),s=/(?:\/[\w.-]+)+\.\w+/g;for(let r of o){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(s);a&&a.forEach(l=>n.add(l))}return n}async function Ch(t,e,n={}){let o=n.threshold??Vc,s=n.safetyMargin??Qc,r=n.keepRecent??Zc,i=wo(),a=yo(e),l=Math.floor(i*(o-s)),u=l-a,d=_t(t),f=d+a;if(f<=l)return{messages:t,compressed:!1,compacted:!1,tokensRemoved:0};let m=d,h=null,p=0;t.length>0&&t[0].role==="system"&&(h=t[0],p=1);let g=Math.max(p,t.length-r),
|
|
71
|
+
...(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 tl(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||""),a=0;for(let l of o)(i.includes(l)||i.includes(bh.basename(l)))&&a++;s+=Math.min(30,a*10)}return Math.min(100,s)}function nl(t,e=10){let n=new Set,o=t.slice(-e),s=/(?:\/[\w.-]+)+\.\w+/g;for(let r of o){let a=(typeof r.content=="string"?r.content:JSON.stringify(r.content||"")).match(s);a&&a.forEach(l=>n.add(l))}return n}async function Ch(t,e,n={}){let o=n.threshold??Vc,s=n.safetyMargin??Qc,r=n.keepRecent??Zc,i=wo(),a=yo(e),l=Math.floor(i*(o-s)),u=l-a,d=_t(t),f=d+a;if(f<=l)return{messages:t,compressed:!1,compacted:!1,tokensRemoved:0};let m=d,h=null,p=0;t.length>0&&t[0].role==="system"&&(h=t[0],p=1);let g=Math.max(p,t.length-r),y=t.slice(p,g),w=t.slice(g),k=y.filter(P=>!P._compacted);if(k.length>=6)try{let{compactMessages:P}=zc(),D=await P(k);if(D){let xe=[...y.filter(ae=>ae._compacted),D.message],de=Vt(h,xe,w),fe=_t(de);if(fe+a<=l)return{messages:de,compressed:!0,compacted:!0,tokensRemoved:m-fe};y=xe}}catch(P){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",P.message)}let R=(f-l)/l,x=y.map(P=>Ln(P,"light")),_=Vt(h,x,w),b=_t(_);if(b+a<=l)return{messages:_,compressed:!0,compacted:!1,tokensRemoved:m-b};if(x=y.map(P=>Ln(P,"medium")),_=Vt(h,x,w),b=_t(_),b+a<=l)return{messages:_,compressed:!0,compacted:!1,tokensRemoved:m-b};if(x=y.map(P=>Ln(P,"aggressive")),_=Vt(h,x,w),b=_t(_),b+a<=l)return{messages:_,compressed:!0,compacted:!1,tokensRemoved:m-b};let A=nl([...x,...w]),O=x.map((P,D)=>({msg:P,score:tl(P,D,x.length,A),tokens:Dn(P)}));for(;O.length>0&&b>u;){let P=0;for(let D=1;D<O.length;D++)O[D].score<O[P].score&&(P=D);b-=O[P].tokens,O.splice(P,1)}return x=O.map(P=>P.msg),_=Vt(h,x,w),b=_t(_),{messages:_,compressed:!0,compacted:!1,tokensRemoved:m-b}}function Vt(t,e,n){let o=[];return t&&o.push(t),o.push(...e,...n),o}function Ah(t,e){if(!t)return"";if(gn(t)<=e)return t;let o=e*4,s=t.split(`
|
|
72
72
|
`),r=Math.floor(o*.6),i=Math.floor(o*.4),a="",l=0;for(let h of s){if(a.length+h.length+1>r)break;a+=(a?`
|
|
73
73
|
`:"")+h,l++}let u="",d=0;for(let h=s.length-1;h>=l;h--){let p=s[h]+(u?`
|
|
74
74
|
`:"")+u;if(p.length>i)break;u=p,d++}let m=`
|
|
75
75
|
|
|
76
76
|
... (${s.length-l-d} lines omitted, ${s.length} total) ...
|
|
77
77
|
|
|
78
|
-
`;return a+m+u}var Oh=6;function Nh(t,e,n=!1){let o=wo(),s=yo(e),r=Math.floor(o*(n?.35:.5))-s,i=_t(t),a=Math.floor(i*(n?.5:.8));r>a&&(r=a);let l=null,u=0;t.length>0&&t[0].role==="system"&&(l=t[0],u=1);let d=n?2:Oh,f=Math.max(u,t.length-d),m=t.slice(u,f),h=t.slice(f),p=m.map(
|
|
79
|
-
`);g
|
|
78
|
+
`;return a+m+u}var Oh=6;function Nh(t,e,n=!1){let o=wo(),s=yo(e),r=Math.floor(o*(n?.35:.5))-s,i=_t(t),a=Math.floor(i*(n?.5:.8));r>a&&(r=a);let l=null,u=0;t.length>0&&t[0].role==="system"&&(l=t[0],u=1);let d=n?2:Oh,f=Math.max(u,t.length-d),m=t.slice(u,f),h=t.slice(f),p=m.map(_=>Ln(_,"aggressive"));n&&(h=h.map(_=>Ln(_,"aggressive")));let g=Vt(l,p,h),y=_t(g);for(;p.length>0&&y>r;){let _=p.shift();y-=Dn(_)}n&&y>r&&(h=h.filter(b=>b.role==="user").slice(-1),g=Vt(l,[],h),y=_t(g)),g=Vt(l,p,h);let w=t.filter(_=>_.role==="user"),k=_=>{let b=typeof _.content=="string"?_.content:"";return b.startsWith("[SYSTEM WARNING]")||b.startsWith("[SYSTEM:")||b.startsWith("BLOCKED:")},R=w.find(_=>!k(_)),x=[...w].reverse().find(_=>!k(_));if(R&&!g.find(_=>_===R)){let _=g.findIndex(A=>A.role==="system"),b=_>=0?_+1:0;g.splice(b,0,R)}return x&&x!==R&&!g.find(_=>_===x)&&g.push(x),{messages:g,tokensRemoved:i-_t(g)}}sl.exports={estimateTokens:gn,estimateMessageTokens:Dn,estimateMessagesTokens:_t,estimateDeltaTokens:Sh,estimateToolsTokens:yo,serializeMessage:vh,getContextWindow:wo,getUsage:Eh,compressMessage:Ln,compressToolResult:el,scoreMessageRelevance:tl,extractActiveFiles:nl,fitToContext:Ch,forceCompress:Nh,truncateFileContent:Ah,invalidateTokenRatioCache:kh,COMPRESSION_THRESHOLD:Vc,SAFETY_MARGIN:Qc,KEEP_RECENT:Zc}});var al=G((wk,il)=>{var ol=require("axios"),{BaseProvider:Mh,readStreamErrorBody:Ph}=In(),{serializeMessage:yk}=Qe(),rl={"gpt-4o":{id:"gpt-4o",name:"GPT-4o",maxTokens:16384,contextWindow:128e3},"gpt-4o-mini":{id:"gpt-4o-mini",name:"GPT-4o Mini",maxTokens:16384,contextWindow:128e3},"gpt-4.1":{id:"gpt-4.1",name:"GPT-4.1",maxTokens:32768,contextWindow:128e3},"gpt-4.1-mini":{id:"gpt-4.1-mini",name:"GPT-4.1 Mini",maxTokens:32768,contextWindow:128e3},"gpt-4.1-nano":{id:"gpt-4.1-nano",name:"GPT-4.1 Nano",maxTokens:16384,contextWindow:128e3},o1:{id:"o1",name:"o1",maxTokens:1e5,contextWindow:2e5},o3:{id:"o3",name:"o3",maxTokens:1e5,contextWindow:2e5},"o3-mini":{id:"o3-mini",name:"o3 Mini",maxTokens:65536,contextWindow:2e5},"o4-mini":{id:"o4-mini",name:"o4 Mini",maxTokens:1e5,contextWindow:2e5}},ii=class extends Mh{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||rl,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let 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:a}=this.formatMessages(e),l={model:s,messages:a,max_tokens:i,temperature:o.temperature??this.temperature};n&&n.length>0&&(l.tools=n);let u;try{u=await ol.post(`${this.baseUrl}/chat/completions`,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}]`:"",m=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${m}`)}return this.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||16384,a=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:s,messages:l,max_tokens:i,temperature:o.temperature??this.temperature,stream:!0};n&&n.length>0&&(u.tools=n);let d;try{d=await ol.post(`${this.baseUrl}/chat/completions`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await Ph(f,p=>p?.error?.message||p?.error);throw new Error(`API Error${m}: ${h}`)}return new Promise((f,m)=>{let h="",p={},g="";o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let w=g.split(`
|
|
79
|
+
`);g=w.pop()||"";for(let k of w){let R=k.trim();if(!R||!R.startsWith("data: "))continue;let x=R.slice(6);if(x==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let _;try{_=JSON.parse(x)}catch{continue}let b=_.choices?.[0]?.delta;if(b&&(b.content&&(a(b.content),h+=b.content),b.tool_calls))for(let A of b.tool_calls){let O=A.index??0;p[O]||(p[O]={id:A.id||"",name:"",arguments:""}),A.id&&(p[O].id=A.id),A.function?.name&&(p[O].name+=A.function.name),A.function?.arguments&&(p[O].arguments+=A.function.arguments)}}}),d.data.on("error",y=>{o.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}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}}_buildToolCalls(e){return Object.values(e).filter(n=>n.name).map(n=>({id:n.id||`openai-${Date.now()}`,function:{name:n.name,arguments:n.arguments}}))}};il.exports={OpenAIProvider:ii,OPENAI_MODELS:rl}});var dl=G((_k,ul)=>{var cl=require("axios"),{BaseProvider:Ih,readStreamErrorBody:Lh}=In(),{serializeMessage:bk}=Qe(),ll={"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}},Dh="2023-06-01",ai=class extends Ih{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||ll,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Dh}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?`
|
|
80
80
|
|
|
81
|
-
`:"")+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!e||e.length===0?[]:e.map(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}_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),a=o.maxTokens||i?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:r,messages:l,max_tokens:a,temperature:o.temperature??this.temperature};u&&(d.system=u);let f=this.formatTools(n);f.length>0&&(d.tools=f);let m;try{m=await cl.post(`${this.baseUrl}/messages`,d,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let p=h.response?.status?` [HTTP ${h.response.status}]`:"",g=h.response?.data?.error?.message||h.response?.data?.error||h.message;throw new Error(`API Error${p}: ${g}`)}return this.normalizeResponse(m.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,l=o.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f={model:r,messages:u,max_tokens:a,temperature:o.temperature??this.temperature,stream:!0};d&&(f.system=d);let m=this.formatTools(n);m.length>0&&(f.tools=m);let h;try{h=await cl.post(`${this.baseUrl}/messages`,f,{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 g=p.response?.status?` [HTTP ${p.response.status}]`:"",
|
|
82
|
-
`);R=
|
|
83
|
-
`);g
|
|
81
|
+
`:"")+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!e||e.length===0?[]:e.map(n=>({name:n.function.name,description:n.function.description||"",input_schema:n.function.parameters||{type:"object",properties:{}}}))}_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),a=o.maxTokens||i?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:r,messages:l,max_tokens:a,temperature:o.temperature??this.temperature};u&&(d.system=u);let f=this.formatTools(n);f.length>0&&(d.tools=f);let m;try{m=await cl.post(`${this.baseUrl}/messages`,d,{timeout:o.timeout||this.timeout,headers:this._getHeaders()})}catch(h){if(h.name==="CanceledError"||h.name==="AbortError"||h.code==="ERR_CANCELED")throw h;let p=h.response?.status?` [HTTP ${h.response.status}]`:"",g=h.response?.data?.error?.message||h.response?.data?.error||h.message;throw new Error(`API Error${p}: ${g}`)}return this.normalizeResponse(m.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this._resolveModelId(s),i=this.getModel(s),a=o.maxTokens||i?.maxTokens||8192,l=o.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f={model:r,messages:u,max_tokens:a,temperature:o.temperature??this.temperature,stream:!0};d&&(f.system=d);let m=this.formatTools(n);m.length>0&&(f.tools=m);let h;try{h=await cl.post(`${this.baseUrl}/messages`,f,{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 g=p.response?.status?` [HTTP ${p.response.status}]`:"",y=await Lh(p,w=>w?.error?.message||w?.error);throw new Error(`API Error${g}: ${y}`)}return new Promise((p,g)=>{let y="",w=[],k=-1,R="";o.signal&&o.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",x=>{R+=x.toString();let _=R.split(`
|
|
82
|
+
`);R=_.pop()||"";for(let b of _){let A=b.trim();if(A.startsWith("data: ")){let O=A.slice(6),P;try{P=JSON.parse(O)}catch{continue}switch(P.type){case"content_block_start":{let D=P.content_block;D?.type==="tool_use"&&(k=w.length,w.push({id:D.id,name:D.name,inputJson:""}));break}case"content_block_delta":{let D=P.delta;D?.type==="text_delta"&&D.text&&(l(D.text),y+=D.text),D?.type==="input_json_delta"&&D.partial_json!==void 0&&k>=0&&(w[k].inputJson+=D.partial_json);break}case"content_block_stop":k=-1;break;case"message_stop":p({content:y,tool_calls:this._buildToolCalls(w)});return}}}}),h.data.on("error",x=>{o.signal?.aborted||g(new Error(`Stream error: ${x.message}`))}),h.data.on("end",()=>{p({content:y,tool_calls:this._buildToolCalls(w)})})})}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}}_buildToolCalls(e){return e.filter(n=>n.name).map(n=>{let o={};if(n.inputJson)try{o=JSON.parse(n.inputJson)}catch{o=n.inputJson}return{id:n.id||`anthropic-${Date.now()}`,function:{name:n.name,arguments:o}}})}};ul.exports={AnthropicProvider:ai,ANTHROPIC_MODELS:ll}});var hl=G((kk,ml)=>{var fl=require("axios"),{BaseProvider:jh,readStreamErrorBody:qh}=In(),{serializeMessage:xk}=Qe(),pl={"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}},ci=class extends jh{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||pl,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:a}=this.formatMessages(e),l={model:s,messages:a,max_tokens:i,temperature:o.temperature??this.temperature};n&&n.length>0&&(l.tools=n);let u;try{u=await fl.post(`${this.baseUrl}/chat/completions`,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}]`:"",m=d.response?.data?.error?.message||d.response?.data?.error||d.message;throw new Error(`API Error${f}: ${m}`)}return this.normalizeResponse(u.data)}async stream(e,n,o={}){let s=o.model||this.defaultModel,r=this.getModel(s),i=o.maxTokens||r?.maxTokens||8192,a=o.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:s,messages:l,max_tokens:i,temperature:o.temperature??this.temperature,stream:!0};n&&n.length>0&&(u.tools=n);let d;try{d=await fl.post(`${this.baseUrl}/chat/completions`,u,{timeout:o.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:o.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.status?` [HTTP ${f.response.status}]`:"",h=await qh(f,p=>p?.error?.message||p?.error);throw new Error(`API Error${m}: ${h}`)}return new Promise((f,m)=>{let h="",p={},g="";o.signal&&o.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let w=g.split(`
|
|
83
|
+
`);g=w.pop()||"";for(let k of w){let R=k.trim();if(!R||!R.startsWith("data: "))continue;let x=R.slice(6);if(x==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let _;try{_=JSON.parse(x)}catch{continue}let b=_.choices?.[0]?.delta;if(b&&(b.content&&(a(b.content),h+=b.content),b.tool_calls))for(let A of b.tool_calls){let O=A.index??0;p[O]||(p[O]={id:A.id||"",name:"",arguments:""}),A.id&&(p[O].id=A.id),A.function?.name&&(p[O].name+=A.function.name),A.function?.arguments&&(p[O].arguments+=A.function.arguments)}}}),d.data.on("error",y=>{o.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}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}}_buildToolCalls(e){return Object.values(e).filter(n=>n.name).map(n=>({id:n.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:n.name,arguments:n.arguments}}))}};ml.exports={GeminiProvider:ci,GEMINI_MODELS:pl}});var yl=G((vk,$l)=>{var bo=require("axios"),{BaseProvider:Fh,readStreamErrorBody:Uh}=In(),gl="http://localhost:11434",li=class extends Fh{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||gl,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 bo.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 a=await bo.post(`${this.baseUrl}/api/show`,{name:s},{timeout:5e3}),l=a.data?.model_info||a.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(a.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(`
|
|
84
84
|
`)};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;try{r=await bo.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:n&&n.length>0?n:void 0,stream:!1,options:{temperature:o.temperature??this.temperature,num_predict:o.maxTokens||8192}},{timeout:o.timeout||this.timeout})}catch(i){if(i.name==="CanceledError"||i.name==="AbortError"||i.code==="ERR_CANCELED")throw i;let a=i.response?.status?` [HTTP ${i.response.status}]`:"",l=i.response?.data?.error||i.message;throw new Error(`API Error${a}: ${l}`)}return this.normalizeResponse(r.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;try{i=await bo.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:n&&n.length>0?n:void 0,stream:!0,options:{temperature:o.temperature??this.temperature,num_predict:o.maxTokens||8192}},{timeout:o.timeout||this.timeout,responseType:"stream",signal:o.signal})}catch(a){if(a.name==="CanceledError"||a.name==="AbortError"||a.code==="ERR_CANCELED")throw a;let l=a.response?.status?` [HTTP ${a.response.status}]`:"",u=await Uh(a,d=>d?.error);throw new Error(`API Error${l}: ${u}`)}return new Promise((a,l)=>{let u="",d=[],f="";o.signal&&o.signal.addEventListener("abort",()=>{i.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),i.data.on("data",m=>{f+=m.toString();let h=f.split(`
|
|
85
85
|
`);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let g;try{g=JSON.parse(p)}catch{continue}if(g.message?.content&&(r(g.message.content),u+=g.message.content),g.message?.tool_calls&&(d=d.concat(g.message.tool_calls)),g.done){a({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),i.data.on("error",m=>{o.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),i.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(r(m.message.content),u+=m.message.content),m.message?.tool_calls&&(d=d.concat(m.message.tool_calls))}catch{}a({content:u,tool_calls:this._normalizeToolCalls(d)})})})}normalizeResponse(e){let n=e.message||{};return{content:n.content||"",tool_calls:this._normalizeToolCalls(n.tool_calls||[])}}_parseContextFromModelfile(e){if(!e)return null;let n=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return n?parseInt(n[1],10):null}_normalizeToolCalls(e){return e.map((n,o)=>({id:n.id||`local-${Date.now()}-${o}`,function:{name:n.function?.name||n.name||"unknown",arguments:n.function?.arguments||n.arguments||{}}}))}};$l.exports={LocalProvider:li,DEFAULT_LOCAL_URL:gl}});var Qt=G((Sk,bl)=>{"use strict";var mt=require("fs"),wl=require("path");function Wh(t){if(!t||isNaN(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Bh(t){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}catch{let e=Date.now()+t;for(;Date.now()<e;);}}function Hh(t,e){let n=wl.dirname(t),o=wl.join(n,`.nex-tmp.${process.pid}.${Date.now()}`);try{mt.existsSync(n)||mt.mkdirSync(n,{recursive:!0}),mt.writeFileSync(o,e,"utf-8"),mt.renameSync(o,t)}catch(s){try{mt.unlinkSync(o)}catch{}throw s}}function Gh(t,e,{timeout:n=5e3,retryMs:o=50}={}){let s=t+".lock",r=Date.now()+n;for(;;){let i=-1;try{i=mt.openSync(s,"wx"),mt.writeSync(i,Buffer.from(String(process.pid))),mt.closeSync(i),i=-1;try{return e()}finally{try{mt.unlinkSync(s)}catch{}}}catch(a){if(i!==-1)try{mt.closeSync(i)}catch{}if(a.code!=="EEXIST")throw a;try{let l=mt.readFileSync(s,"utf-8").trim(),u=parseInt(l,10);if(!Wh(u)){try{mt.unlinkSync(s)}catch{}continue}}catch(l){if(l.code&&l.code!=="ENOENT")throw l;continue}if(Date.now()>=r){try{mt.unlinkSync(s)}catch{}return e()}Bh(o)}}}bl.exports={atomicWrite:Hh,withFileLockSync:Gh}});var qn=G((Ek,Tl)=>{var jn=require("fs"),ui=require("path"),{atomicWrite:Kh,withFileLockSync:Yh}=Qt(),_l={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:{}},_o=[],Zt={};function zh(t,e,n,o){if(_o.push({provider:t,model:e,input:n,output:o}),Zt[t]!==void 0){let s=Sl(t);s.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${s.spent.toFixed(2)} / $${s.limit.toFixed(2)}\x1B[0m
|
|
86
86
|
`)}}function di(t,e){let n=_l[t];return n?n[e]||{input:0,output:0}:{input:0,output:0}}function xl(t){let e=di(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function kl(){let t={};for(let r of _o){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:xl(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 Xh(){let{totalCost:t,totalInput:e,totalOutput:n,breakdown:o}=kl();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(`
|
|
@@ -92,12 +92,12 @@ ${N.bold}${N.cyan} Diff: ${t}${N.reset}`);let s=ds(e,n),r=[];if(s.forEach((l,u)
|
|
|
92
92
|
${N.bold}${N.cyan} File exists \u2014 showing changes: ${t}${N.reset}`);let o=ds(e,n),s=0;for(let i of o)i.type!=="same"&&s++;if(s===0){console.log(`${N.gray} (identical content)${N.reset}`);return}let r=0;for(let i of o){if(r>=30){console.log(`${N.gray} ...(${s-r} more changes)${N.reset}`);break}switch(i.type){case"remove":console.log(`${N.red} - ${i.line}${N.reset}`),r++;break;case"add":console.log(`${N.green} + ${i.line}${N.reset}`),r++;break;default:r>0&&console.log(`${N.gray} ${i.line}${N.reset}`)}}console.log()}function _g(t,e){console.log(`
|
|
93
93
|
${N.bold}${N.cyan} New file: ${t}${N.reset}`);let n=e.split(`
|
|
94
94
|
`),o=n.slice(0,20);for(let s of o)console.log(`${N.green} + ${s}${N.reset}`);n.length>20&&console.log(`${N.gray} ...+${n.length-20} more lines${N.reset}`),console.log()}async function xg(t){return yg()?!0:$g(` ${t}?`)}function kg(t,e,n,o){let s=o||process.stdout.columns||80,r=Math.floor((s-3)/2);console.log(`
|
|
95
|
-
${N.bold}${N.cyan} Side-by-side: ${t}${N.reset}`),console.log(` ${N.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${N.reset}`);let i=ds(e,n),a=[],l=0;for(;l<i.length;)if(i[l].type==="same")a.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 p=[];for(;l<i.length&&i[l].type==="add";)p.push(i[l].line),l++;let g=Math.max(h.length,p.length);for(let
|
|
95
|
+
${N.bold}${N.cyan} Side-by-side: ${t}${N.reset}`),console.log(` ${N.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${N.reset}`);let i=ds(e,n),a=[],l=0;for(;l<i.length;)if(i[l].type==="same")a.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 p=[];for(;l<i.length&&i[l].type==="add";)p.push(i[l].line),l++;let g=Math.max(h.length,p.length);for(let y=0;y<g;y++)a.push({left:y<h.length?h[y]:"",right:y<p.length?p[y]:"",type:"changed"})}else i[l].type==="add"&&(a.push({left:"",right:i[l].line,type:"changed"}),l++);let u=a.map((h,p)=>h.type!=="same"?p:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${N.gray}(no changes)${N.reset}`);return}let d=Math.max(0,u[0]-2),f=Math.min(a.length,u[u.length-1]+3),m=(h,p)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=p?h.substring(0,p):h+" ".repeat(p-g.length)};d>0&&console.log(` ${N.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${N.reset}`);for(let h=d;h<f;h++){let p=a[h];if(p.type==="same")console.log(` ${N.gray}${m(p.left,r)}${N.reset}\u2502${N.gray}${m(p.right,r)}${N.reset}`);else{let g=p.left?`${N.red}${m(p.left,r)}${N.reset}`:`${m("",r)}`,y=p.right?`${N.green}${m(p.right,r)}${N.reset}`:`${m("",r)}`;console.log(` ${g}\u2502${y}`)}}f<a.length&&console.log(` ${N.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${N.reset}`),console.log(` ${N.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${N.reset}
|
|
96
96
|
`)}function vg(t,e,n,o={}){let s=o.label||"Update",r=o.context||3,i=o.annotations||[],a=xo.isAbsolute(t)?xo.relative(process.cwd(),t):t,l=ds(e,n),u=1,d=1;for(let b of l)b.type==="same"?(b.oldLine=u++,b.newLine=d++):b.type==="remove"?(b.oldLine=u++,b.newLine=null):(b.oldLine=null,b.newLine=d++);let f=0,m=0;for(let b of l)b.type==="add"?f++:b.type==="remove"&&m++;if(console.log(`
|
|
97
97
|
${N.green}\u25CF${N.reset} ${N.bold}${s}(${a})${N.reset}`),f===0&&m===0){console.log(` ${N.dim}\u2514 (no changes)${N.reset}
|
|
98
|
-
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),i.length>0){let b=i.filter(
|
|
98
|
+
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),i.length>0){let b=i.filter(D=>D.severity==="error").length,A=i.filter(D=>D.severity==="warn").length,O=i.filter(D=>D.severity==="info").length,P=[];b>0&&P.push(`${N.red}${b} error${b!==1?"s":""}${N.dim}`),A>0&&P.push(`${N.yellow}${A} warning${A!==1?"s":""}${N.dim}`),O>0&&P.push(`${N.cyan}${O} info${O!==1?"s":""}${N.dim}`),h.push(`found ${P.join(", ")}`)}console.log(` ${N.dim}\u2514 ${h.join(", ")}${N.reset}`);let g=[];l.forEach((b,A)=>{b.type!=="same"&&g.push(A)});let y=[],w=null,k=null;for(let b of g){let A=Math.max(0,b-r),O=Math.min(l.length-1,b+r);w===null?(w=A,k=O):(A<=k+1||(y.push([w,k]),w=A),k=O)}w!==null&&y.push([w,k]);let R=" ",x=process.stdout.columns||120;function _(b,A,O){let P=O.replace(/\x1b\[[0-9;]*m/g,""),D=O+" ".repeat(Math.max(0,x-P.length));return`${b}${A}${D}${N.reset}`}for(let b=0;b<y.length;b++){b>0&&console.log(`${R}${N.dim}\xB7\xB7\xB7${N.reset}`);let[A,O]=y[b];for(let P=A;P<=O;P++){let D=l[P],Me=D.newLine!=null?D.newLine:D.oldLine,xe=String(Me).padStart(4),de=D.type!=="remove"?i.filter(fe=>fe.line===D.newLine):[];D.type==="remove"?console.log(_(hi.diff_rem_bg,N.red,`${R}${xe} - ${D.line}`)):D.type==="add"?console.log(_(hi.diff_add_bg,N.green,`${R}${xe} + ${D.line}`)):console.log(`${R}${N.dim}${xe} ${N.reset}${D.line}`);for(let fe of de){let ae=N.cyan,be="\u2139";fe.severity==="error"?(ae=N.red,be="\u2716"):fe.severity==="warn"&&(ae=N.yellow,be="\u26A0"),console.log(`${R} ${ae}${be} ${fe.message}${N.reset}`)}}}console.log()}function Sg(t,e,n={}){let o=xo.isAbsolute(t)?xo.relative(process.cwd(),t):t,s=e.split(`
|
|
99
99
|
`),r=n.annotations||[];console.log(`
|
|
100
|
-
${N.green}\u25CF${N.reset} ${N.bold}Create(${o})${N.reset}`);let i=[`${s.length} line${s.length!==1?"s":""}`];if(r.length>0){let f=r.filter(g=>g.severity==="error").length,m=r.filter(g=>g.severity==="warn").length,h=r.filter(g=>g.severity==="info").length,p=[];f>0&&p.push(`${N.red}${f} error${f!==1?"s":""}${N.dim}`),m>0&&p.push(`${N.yellow}${m} warning${m!==1?"s":""}${N.dim}`),h>0&&p.push(`${N.cyan}${h} info${h!==1?"s":""}${N.dim}`),i.push(`found ${p.join(", ")}`)}console.log(` ${N.dim}\u2514 ${i.join(", ")}${N.reset}`);let l=" ",u=process.stdout.columns||120,d=Math.min(s.length,20);for(let f=0;f<d;f++){let m=String(f+1).padStart(4),h=f+1,p=r.filter(
|
|
100
|
+
${N.green}\u25CF${N.reset} ${N.bold}Create(${o})${N.reset}`);let i=[`${s.length} line${s.length!==1?"s":""}`];if(r.length>0){let f=r.filter(g=>g.severity==="error").length,m=r.filter(g=>g.severity==="warn").length,h=r.filter(g=>g.severity==="info").length,p=[];f>0&&p.push(`${N.red}${f} error${f!==1?"s":""}${N.dim}`),m>0&&p.push(`${N.yellow}${m} warning${m!==1?"s":""}${N.dim}`),h>0&&p.push(`${N.cyan}${h} info${h!==1?"s":""}${N.dim}`),i.push(`found ${p.join(", ")}`)}console.log(` ${N.dim}\u2514 ${i.join(", ")}${N.reset}`);let l=" ",u=process.stdout.columns||120,d=Math.min(s.length,20);for(let f=0;f<d;f++){let m=String(f+1).padStart(4),h=f+1,p=r.filter(k=>k.line===h),g=`${l}${m} + ${s[f]}`,y=g.replace(/\x1b\[[0-9;]*m/g,""),w=g+" ".repeat(Math.max(0,u-y.length));console.log(`${hi.diff_add_bg}${N.green}${w}${N.reset}`);for(let k of p){let R=N.cyan,x="\u2139";k.severity==="error"?(R=N.red,x="\u2716"):k.severity==="warn"&&(R=N.yellow,x="\u26A0"),console.log(`${l} ${R}${x} ${k.message}${N.reset}`)}}s.length>20&&console.log(`${l}${N.dim} ...+${s.length-20} more lines${N.reset}`),console.log()}Pl.exports={diffLines:ds,showEditDiff:wg,showWriteDiff:bg,showNewFilePreview:_g,confirmFileChange:xg,showSideBySideDiff:kg,showClaudeDiff:vg,showClaudeNewFile:Sg}});var en=G((Nk,jl)=>{var Ll=require("util").promisify(require("child_process").exec),Eg=require("util").promisify(require("child_process").execFile),{C:Ne}=Ce();async function gi(t){try{let{stdout:e}=await Ll(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function ko(...t){try{let{stdout:e}=await Eg("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Tg(){return await gi("git rev-parse --is-inside-work-tree")==="true"}async function Rg(){return await gi("git branch --show-current")}async function $i(){try{let{stdout:t}=await Ll("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
101
101
|
`).filter(Boolean).map(e=>{let n=e.substring(0,2).trim(),o=e.substring(3);return{status:n,file:o}})}catch{return[]}}async function vo(t=!1){return await gi(`git diff ${t?"--cached":""}`)||""}async function yi(){return(await $i()).map(e=>e.file)}async function Dl(){let t=await yi();if(t.length===0)return null;let e=await vo(),o=await vo(!0)||e,s=0,r=0;if(o){let d=o.split(`
|
|
102
102
|
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&s++,f.startsWith("-")&&!f.startsWith("---")&&r++}else s=t.length;let i="chore",a=t.join(" ").toLowerCase();a.includes("test")?i="test":a.includes("readme")||a.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 Cg(t){let n=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await ko("checkout","-b",n)!==null?n:null}async function Ag(t){return await ko("add","-A"),await ko("commit","-m",t)?await ko("rev-parse","--short","HEAD"):null}async function Og(){let t=await Dl();if(!t)return`${Ne.dim}No changes${Ne.reset}`;let e=[];e.push(`
|
|
103
103
|
${Ne.bold}${Ne.cyan}Git Diff Summary:${Ne.reset}`),e.push(` ${Ne.green}+${t.stats.additions}${Ne.reset} ${Ne.red}-${t.stats.deletions}${Ne.reset} in ${t.files.length} file(s)`),e.push(`
|
|
@@ -171,9 +171,9 @@ TOOL STRATEGY:
|
|
|
171
171
|
ERROR RECOVERY:
|
|
172
172
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
173
173
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
174
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];f.push({role:"user",content:t.task});let m=Fi(t),h=m.provider,p=m.model,g=m.tier,{TOOL_DEFINITIONS:
|
|
175
|
-
`)}let
|
|
176
|
-
...(truncated)`:W,tool_call_id:be}}).catch(M=>(te&&(vs(te),l.delete(te)),{role:"tool",content:`ERROR: ${M.message}`,tool_call_id:be}))}),xe=await Promise.all(Me);f.push(...xe);for(let
|
|
174
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];f.push({role:"user",content:t.task});let m=Fi(t),h=m.provider,p=m.model,g=m.tier,{TOOL_DEFINITIONS:y,executeTool:w}=Et(),k=Ku(n),R=Cy(y.filter(_=>!k.has(_.function.name)),g);if(p&&!t._skipLog){let _=g?` (${g})`:"";process.stderr.write(` [sub-agent: ${h}:${p}${_}]
|
|
175
|
+
`)}let x={};h&&(x.provider=h),p&&(x.model=p);try{for(let b=0;b<s;b++){let A=await Gu(f,R,x);if(!A||typeof A!="object")throw new Error("Empty or invalid response from provider");if(A.usage){let de=A.usage.prompt_tokens||0,fe=A.usage.completion_tokens||0;a.input+=de,a.output+=fe;let ae=h||Ho(),be=p||Ty();Ay(ae,be,de,fe)}let O=A.content||"",P=A.tool_calls,D={role:"assistant",content:O||""};if(P&&P.length>0&&(D.tool_calls=P),f.push(D),!P||P.length===0){for(let de of l)vs(de);return{task:t.task,status:"done",result:O||"(no response)",toolsUsed:i,tokensUsed:a,modelSpec:h&&p?`${h}:${p}`:null}}let Me=P.map(de=>{let fe=de.function.name,ae=ju(de.function.arguments),be=de.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!ae)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${fe}`,tool_call_id:be});let te=null;if(Iy.has(fe)&&ae.path){let M=require("path"),W=M.isAbsolute(ae.path)?ae.path:M.resolve(process.cwd(),ae.path);if(l.has(W)||!Py(W,r))return Promise.resolve({role:"tool",content:`ERROR: File '${ae.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:be});l.add(W),te=W}return i.push(fe),(fe==="spawn_agents"?Ju(ae,n+1):w(fe,ae,{autoConfirm:!0,silent:!0})).then(M=>{te&&(vs(te),l.delete(te));let W=String(M??"");return{role:"tool",content:W.length>2e4?W.substring(0,2e4)+`
|
|
176
|
+
...(truncated)`:W,tool_call_id:be}}).catch(M=>(te&&(vs(te),l.delete(te)),{role:"tool",content:`ERROR: ${M.message}`,tool_call_id:be}))}),xe=await Promise.all(Me);f.push(...xe);for(let de=0;de<P.length;de++){let fe=P[de];if(fe.function.name==="bash_exec"){let ae=ju(fe.function.arguments);if((xe[de]?.content||"").startsWith("ERROR")&&ae&&ae.command){let te=ae.command.replace(/\s+/g," ").trim().slice(0,100);u.set(te,(u.get(te)||0)+1)}}}e.onUpdate&&e.onUpdate(`step ${b+1}/${s}`)}for(let b of l)vs(b);let _=[...u.entries()].filter(([,b])=>b>=3).sort((b,A)=>A[1]-b[1]).slice(0,3).map(([b,A])=>`"${b}" (failed ${A}\xD7)`);return{task:t.task,status:"truncated",abortReason:"iteration_limit",repeatedFailures:_,result:f[f.length-1]?.content||"(max iterations reached)",toolsUsed:i,tokensUsed:a,modelSpec:h&&p?`${h}:${p}`:null}}catch(_){for(let b of l)vs(b);return{task:t.task,status:"failed",result:`Error: ${_.message}`,toolsUsed:i,tokensUsed:a,modelSpec:h&&p?`${h}:${p}`:null}}}async function Ju(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?Ny:My,o=e===0?Uu:Wu,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,a=s.map(d=>Fi(d)),l=s.map((d,f)=>{let m=a[f],h=m.model?` [${m.model}]`:"",p=d.task.substring(0,i-h.length);return`${r}Agent ${f+1}${h}: ${p}${d.task.length>p.length?"...":""}`}),u=new Oy(l);u.start();try{let d=s.map((g,y)=>{let w=a[y],k=Math.min(g.max_iterations||o,o),R=w.model?{...g,model:`${w.provider}:${w.model}`,_skipLog:!0,max_iterations:k}:{...g,_skipLog:!0,max_iterations:k};return Xu(R,{onUpdate:()=>{}},e).then(x=>(u.update(y,x.status==="failed"?"error":"done"),x)).catch(x=>(u.update(y,"error"),{task:g.task,status:"failed",result:`Error: ${x.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),f=await Promise.all(d);u.stop(),qi();let m=["Sub-agent results:",""],h=0,p=0;for(let g=0;g<f.length;g++){let y=f[g],w=y.status==="done"?"\u2713":y.status==="truncated"?"\u26A0":"\u2717",k=y.modelSpec?` [${y.modelSpec}]`:"";m.push(`${w} Agent ${g+1}${k}: ${y.task}`),m.push(` Status: ${y.status}`),m.push(` Tools used: ${y.toolsUsed.length>0?y.toolsUsed.join(", "):"none"}`),m.push(` Result: ${y.result}`),y.repeatedFailures&&y.repeatedFailures.length>0&&m.push(` Repeated failures: ${y.repeatedFailures.join("; ")}`),m.push(""),h+=y.tokensUsed.input,p+=y.tokensUsed.output}return m.push(`Total sub-agent tokens: ${h} input + ${p} output`),m.join(`
|
|
177
177
|
`)}catch(d){return u.stop(),qi(),`ERROR: Sub-agent execution failed: ${d.message}`}}Vu.exports={runSubAgent:Xu,executeSpawnAgents:Ju,clearAllLocks:qi,classifyTask:Yu,pickModelForTier:zu,resolveSubAgentModel:Fi,isRetryableError:Hu,callWithRetry:Gu,getExcludedTools:Ku,LOCK_TIMEOUT_MS:Bu}});var Ts=G((Jk,dd)=>{var Le=require("fs"),Bt=require("path"),{atomicWrite:Qu,withFileLockSync:Zu}=Qt(),qy=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 Kn(){let t=Bt.join(process.cwd(),".nex","brain");return Le.existsSync(t)||Le.mkdirSync(t,{recursive:!0}),t}function zo(){return Bt.join(Kn(),".brain-index.json")}function Bi(){return Bt.join(Kn(),".embeddings.json")}function Ss(){let t=Bt.join(process.cwd(),".nex","brain");if(!Le.existsSync(t))return[];try{return Le.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let n=Bt.join(t,e),o=Le.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 Es(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(`
|
|
178
178
|
`);for(let r of s){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let a=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[a]=l.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[a]=l}n=o[2]}return{frontmatter:e,body:n}}function ed(t){let e=Bt.join(Kn(),`${t}.md`);if(!Le.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let n=Le.readFileSync(e,"utf-8"),{frontmatter:o,body:s}=Es(n);return{name:t,content:n,body:s,frontmatter:o}}function Fy(t,e){let n=Bt.join(Kn(),`${t}.md`);Qu(n,e),By(t,e),Uy()}function Uy(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Bi();Le.existsSync(t)&&setImmediate(async()=>{try{await ad()}catch{}})}function Wy(t){let e=Bt.join(Kn(),`${t}.md`);return Le.existsSync(e)?(Le.unlinkSync(e),Hy(t),!0):!1}function Yo(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!qy.has(e))}function Hi(t){let e={},{frontmatter:n,body:o}=Es(t),s=Array.isArray(n.tags)?n.tags:[];for(let i of s){let a=i.toLowerCase().replace(/[^a-z0-9-]/g,"");a.length>1&&(e[a]=(e[a]||0)+5)}let r=(o||t).split(`
|
|
179
179
|
`);for(let i of r)if(i.startsWith("#")){let a=i.replace(/^#+\s*/,"");for(let l of Yo(a))e[l]=(e[l]||0)+3}for(let i of Yo(o||t))e[i]=(e[i]||0)+1;return e}function Gi(){let t=zo();if(!Le.existsSync(t))return{documents:{}};try{return JSON.parse(Le.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function Ki(t){Qu(zo(),JSON.stringify(t,null,2))}function By(t,e){Zu(zo(),()=>{let n=Gi(),{frontmatter:o}=Es(e),s=Array.isArray(o.tags)?o.tags:[];n.documents[t]={keywords:Hi(e),tags:s,modified:new Date().toISOString()},Ki(n)})}function Hy(t){Zu(zo(),()=>{let e=Gi();delete e.documents[t],Ki(e)})}function Wi(){let t=Ss(),e={documents:{}};for(let n of t){let o=Le.readFileSync(n.path,"utf-8"),{frontmatter:s}=Es(o),r=Array.isArray(s.tags)?s.tags:[];e.documents[n.name]={keywords:Hi(o),tags:r,modified:n.modified.toISOString()}}return Ki(e),e}function td(){let t=Gi(),e=Ss();for(let n of e){let o=t.documents[n.name];if(!o||new Date(o.modified)<n.modified)return Wi()}for(let n of Object.keys(t.documents))if(!e.some(o=>o.name===n))return Wi();return t}function nd(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=Yo(t);if(s.length===0)return[];let r=td(),i=[];for(let[a,l]of Object.entries(r.documents)){let u=0;for(let d of s){l.keywords[d]&&(u+=l.keywords[d]);for(let[f,m]of Object.entries(l.keywords))f!==d&&f.length>3&&d.length>3&&(f.includes(d)||d.includes(f))&&(u+=m*.3)}u>=o&&i.push({name:a,score:u})}return i.sort((a,l)=>l.score-a.score),i.slice(0,n)}var sd=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Ui=400,Gy=50;async function od(){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((a,l)=>{let u=s.get(o.toString(),{timeout:2e3},d=>{let f="";d.on("data",m=>f+=m),d.on("end",()=>{try{a(JSON.parse(f))}catch{l(new Error("bad json"))}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("timeout"))})})).models||[]).map(a=>a.name).some(a=>a.startsWith(sd.split(":")[0]))}catch{return!1}}async function Yi(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:sd,prompt:t});return new Promise((a,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",m=>f+=m),d.on("end",()=>{try{a(JSON.parse(f).embedding||[])}catch(m){l(m)}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("embedding timeout"))}),u.write(i),u.end()})}function rd(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 id(t){let e=t.split(/\s+/),n=[],o=0;for(;o<e.length;){let s=e.slice(o,o+Ui).join(" ");if(n.push({text:s,offset:o}),o+Ui>=e.length)break;o+=Ui-Gy}return n}async function ad(){let t=Ss(),e={documents:{}},n=Bi();if(Le.existsSync(n))try{e=JSON.parse(Le.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=Le.readFileSync(o.path,"utf-8"),i=id(r),a=[];for(let l of i){let u=await Yi(l.text);a.push({text:l.text,embedding:u,offset:l.offset})}e.documents[o.name]={chunks:a,modified:o.modified.toISOString()}}for(let o of Object.keys(e.documents))t.some(s=>s.name===o)||delete e.documents[o];return Le.writeFileSync(n,JSON.stringify(e),"utf-8"),e}async function cd(t,e={}){let{topK:n=3,minSimilarity:o=.3}=e,s=Bi();if(!Le.existsSync(s))return[];let r;try{r=JSON.parse(Le.readFileSync(s,"utf-8"))}catch{return[]}let i=await Yi(t),a=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,f="";for(let m of u.chunks||[]){let h=rd(i,m.embedding);h>d&&(d=h,f=m.text)}d>=o&&a.push({name:l,score:d,bestChunk:f})}return a.sort((l,u)=>u.score-l.score),a.slice(0,n)}function ld(t,e,n={}){let{k:o=60,topK:s=3}=n,r={};return t.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),e.forEach((i,a)=>{r[i.name]=(r[i.name]||0)+1/(o+a+1)}),Object.entries(r).map(([i,a])=>({name:i,score:a})).sort((i,a)=>a.score-i.score).slice(0,s)}async function ud(t,e={}){let{topK:n=3,minScore:o=.1}=e,s=nd(t,{topK:n,minScore:o}),r=s;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await od()){let a=await cd(t,{topK:n});r=ld(s,a,{topK:n})}}catch{}return r.map(i=>{let a=ed(i.name),l=(a.body||a.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:a.content,excerpt:l}})}async function Ky(t){if(!t||!t.trim())return"";let e=Bt.join(process.cwd(),".nex","brain");if(!Le.existsSync(e)||Ss().length===0)return"";let o;try{o=await ud(t,{topK:3})}catch{return""}if(!o||o.length===0)return"";let s;try{s=Qe().estimateTokens}catch{s=l=>Math.ceil(l.length/4)}let r=25e3,i=[],a=0;for(let l of o){let u=l.content||"",d=s(u);if(a+d>r){let m=r-a;if(m<100)break;let h=m/d;u=u.slice(0,Math.floor(u.length*h))+`
|
|
@@ -194,43 +194,43 @@ HINT: ${f}`:""}`}let r=nw(o);if(r)return`BLOCKED: Destructive operation on prote
|
|
|
194
194
|
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?yd(o):tw(o)){let f=yd(o)?"\u26D4":"\u26A0";if(!await Tt(` ${f} bash: \`${o}\``,{toolName:"bash"}))return"CANCELLED: User declined to execute this command."}let a;try{a=process.cwd(),$d.accessSync(a)}catch{a=require("os").homedir(),n.silent||console.log(`${ee.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${ee.reset}`)}let l=mw.test(o.trim())&&!hw.test(o.trim());if(pw.test(o.trim())||l){n.silent||console.log(`${ee.dim} \u25B6 interactive: ${o}${ee.reset}`);let f=Qy("sh",["-c",o],{stdio:"inherit",cwd:a});return f.error?`ERROR: ${f.error.message}`:f.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${f.status})`}let{ToolProgress:u}=Pn(),d=n.silent?null:new u("bash",o.substring(0,40));d&&d.start();try{let{stdout:f,stderr:m}=await ve(o,{cwd:a,timeout:9e4,maxBuffer:5242880});return d&&d.stop(),f||m||"(no output)"}catch(f){d&&d.stop();let m=(f.stderr||f.stdout||f.message||"").toString().substring(0,5e3),h=vd(m,o);return`EXIT ${f.code||1}
|
|
195
195
|
${h}`}}case"read_file":{let o=lt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ht(o)){let b=await Vo(e.path);if(b.fixedPath)o=b.fixedPath,console.log(`${ee.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ke.relative(process.cwd(),o)}${ee.reset}`);else return`ERROR: File not found: ${e.path}${b.message?`
|
|
196
196
|
`+b.message:""}`}let r=Buffer.alloc(8192),i=await $d.promises.open(o,"r"),{bytesRead:a}=await i.read(r,0,8192,0);await i.close();for(let b=0;b<a;b++)if(r[b]===0)return`ERROR: ${o} is a binary file (not readable as text)`;let l=await De.readFile(o,"utf-8");if(!l&&(await De.stat(o)).size>0)return`WARNING: ${o} is empty or unreadable`;let u=l.split(`
|
|
197
|
-
`),d=await De.stat(o),f=u.length,m=350,h=!e.line_start&&!e.line_end,p=h&&f>m,g=(e.line_start||1)-1,
|
|
198
|
-
`),
|
|
197
|
+
`),d=await De.stat(o),f=u.length,m=350,h=!e.line_start&&!e.line_end,p=h&&f>m,g=(e.line_start||1)-1,y=p?m:e.line_end||u.length,w=ke.relative(process.cwd(),o),k=p?`showing lines 1-${m} of ${f}`:e.line_start||e.line_end?`lines ${g+1}-${y} of ${f}`:`${f} lines`,R=`File: ${w} (${k}, ${d.size} bytes)`,x=u.slice(g,y).map((b,A)=>`${g+A+1}: ${b}`).join(`
|
|
198
|
+
`),_=p?`
|
|
199
199
|
|
|
200
200
|
[File truncated: showing lines 1-${m} of ${f} total. Use line_start/line_end to read other sections, e.g. line_start=${m+1} line_end=${Math.min(m*2,f)}]`:!h&&f>m?`
|
|
201
201
|
[Large file (${f} lines total) \u2014 use line_start/line_end for other sections]`:"";return`${R}
|
|
202
|
-
${
|
|
202
|
+
${x}${_}`}case"write_file":{await ea();let o=lt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let s=await ht(o),r=null;if(n.autoConfirm)s&&(r=await De.readFile(o,"utf-8"));else if(s){r=await De.readFile(o,"utf-8");let d=await As(o,e.content);if(Xo(o,r,e.content,{annotations:d}),!await Cs("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let d=await As(o,e.content);if(sw(o,e.content,{annotations:d}),!await Cs("Create"))return"CANCELLED: User declined to create file."}let i=ke.dirname(o);await ht(i)||await De.mkdir(i,{recursive:!0}),await De.writeFile(o,e.content,"utf-8");let l=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||e.content.startsWith("#!");l&&await De.chmod(o,493),Jo("write_file",o,r,e.content);let u=l?" [chmod +x applied]":"";return`Written: ${o} (${e.content.length} chars)${u}`}case"edit_file":{await ea();let o=lt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ht(o)){let d=await Vo(e.path);if(d.fixedPath)o=d.fixedPath,console.log(`${ee.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ke.relative(process.cwd(),o)}${ee.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
203
203
|
`+d.message:""}`}let r=await De.readFile(o,"utf-8"),i=e.old_text,a=!1,l=!1;if(!r.includes(e.old_text)){let{getActiveModelId:d,getActiveProviderName:f}=Ae();if(_d(d(),f())==="strict"){let p=Ns(r,e.old_text);return p?`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)
|
|
204
204
|
Most similar text (line ${p.line}, distance ${p.distance}):
|
|
205
|
-
${p.text}`:`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)`}let h=bd(r,e.old_text);if(h)i=h,a=!0,console.log(`${ee.dim} \u2713 fuzzy whitespace match applied${ee.reset}`);else{let p=Sd(r,e.old_text,e.new_text);if(p){if(!n.autoConfirm){let R=await As(o,p.content);if(Xo(o,r,p.content,{annotations:R}),!await Cs(`Apply (auto-fix, line ${p.line}, distance ${p.distance})`))return"CANCELLED: User declined to apply edit."}await De.writeFile(o,p.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||p.content.startsWith("#!"))&&await De.chmod(o,493),Jo("edit_file",o,r,p.content);let
|
|
206
|
-
`),R=Math.max(0,g.line-6),
|
|
207
|
-
`),b=`line_start=${Math.max(1,g.line-5)} line_end=${Math.min(
|
|
205
|
+
${p.text}`:`ERROR: old_text not found in ${o} (strict mode \u2014 exact match required)`}let h=bd(r,e.old_text);if(h)i=h,a=!0,console.log(`${ee.dim} \u2713 fuzzy whitespace match applied${ee.reset}`);else{let p=Sd(r,e.old_text,e.new_text);if(p){if(!n.autoConfirm){let R=await As(o,p.content);if(Xo(o,r,p.content,{annotations:R}),!await Cs(`Apply (auto-fix, line ${p.line}, distance ${p.distance})`))return"CANCELLED: User declined to apply edit."}await De.writeFile(o,p.content,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||p.content.startsWith("#!"))&&await De.chmod(o,493),Jo("edit_file",o,r,p.content);let k=p.matchText.length>80?p.matchText.substring(0,77)+"...":p.matchText;return console.log(`${ee.dim} \u2713 auto-fixed edit: line ${p.line}, distance ${p.distance}${ee.reset}`),`Edited: ${o} (auto-fixed, line ${p.line}, distance ${p.distance}, matched: "${k}")`}let g=Ns(r,e.old_text);if(g){let k=r.split(`
|
|
206
|
+
`),R=Math.max(0,g.line-6),x=Math.min(k.length,g.line+10),_=k.slice(R,x).map((A,O)=>`${R+O+1}: ${A}`).join(`
|
|
207
|
+
`),b=`line_start=${Math.max(1,g.line-5)} line_end=${Math.min(k.length,g.line+15)}`;return`ERROR: old_text not found in ${o} (most similar at line ${g.line}, distance ${g.distance})
|
|
208
208
|
|
|
209
209
|
Actual file content around line ${g.line} \u2014 use this to correct old_text:
|
|
210
|
-
${
|
|
210
|
+
${_}
|
|
211
211
|
|
|
212
|
-
Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${b}`}let
|
|
213
|
-
`)[0].slice(0,60)
|
|
214
|
-
Recovery: grep -n "${
|
|
215
|
-
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}${
|
|
212
|
+
Fix: update old_text to match the exact lines above, then retry. If you need more context: read_file with ${b}`}let y=(e.old_text||"").trim().split(`
|
|
213
|
+
`)[0].slice(0,60),w=y?`
|
|
214
|
+
Recovery: grep -n "${y.replace(/"/g,'\\"')}" <file> to find the line, then re-read that section with line_start/line_end.`:`
|
|
215
|
+
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 As(o,d);if(Xo(o,r,d,{annotations:f}),!await Cs(a?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(i).join(e.new_text);return await De.writeFile(o,u,"utf-8"),(/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||u.startsWith("#!"))&&await De.chmod(o,493),Jo("edit_file",o,r,u),a?`Edited: ${o} (fuzzy match)`:`Edited: ${o}`}case"list_directory":{let o=lt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ht(o)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=lt(u),f=await ht(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 a=[],l=async(u,d,f)=>{if(d>r)return;let m;try{m=await De.readdir(u,{withFileTypes:!0})}catch{return}m=m.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of m){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let p=h.isDirectory()?"/":"";a.push(`${f}${h.name}${p}`),h.isDirectory()&&await l(ke.join(u,h.name),d+1,f+" ")}};return await l(o,1,""),a.join(`
|
|
216
216
|
`)||"(empty)"}case"search_files":{let o=lt(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 Vi("grep",s,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),a=[];for(let l=0;l<i.length;l+=2){let u=i[l],d=i[l+1];if(u&&d){let f=d.split(`
|
|
217
217
|
`).filter(m=>m.trim());for(let m of f)if(a.push(`${u}:${m}`),a.length>=50)break}if(a.length>=50)break}return a.join(`
|
|
218
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?lt(e.path):s,i=e.pattern,a=O=>{let
|
|
218
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let s=process.cwd(),r=e.path?lt(e.path):s,i=e.pattern,a=O=>{let P=O.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${P}$`)},l=a(i),u=i.split("/").pop(),d=a(u),{ToolProgress:f}=Pn(),m=new f("glob","Finding files...");m.start();let{getFileIndex:h,getIndexedCwd:p,refreshIndex:g,isIndexValid:y}=Ni(),w=h(),k=p();y(r)||(await g(r),w=h());let R=w.filter(O=>l.test(O)||d.test(ke.basename(O))).map(O=>ke.join(r,O));if(R.length===0)return m.stop(),"(no matches)";let x=await Promise.all(R.slice(0,210).map(async O=>{try{let P=await De.stat(O);return{path:O,mtime:P.mtimeMs}}catch{return{path:O,mtime:0}}}));x.sort((O,P)=>P.mtime-O.mtime);let _=x.map(O=>O.path),b=R.length>200,A=_.slice(0,200).join(`
|
|
219
219
|
`);return m.update({count:R.length,detail:e.pattern}),m.stop(),b?`${A}
|
|
220
220
|
|
|
221
221
|
\u26A0 Results truncated at 200. Use a more specific pattern.`:A}case"grep":{let o=e.path?lt(e.path):process.cwd();if(e.staged){let{getDiff:l}=en(),u=await l(!0);if(!u.trim())return"(no staged changes)";let d=new Set,f=u.split(`
|
|
222
|
-
`);for(let
|
|
223
|
-
`).filter(
|
|
224
|
-
`).filter(O=>O.trim());for(let O of A)g.push(`${
|
|
222
|
+
`);for(let y of f)if(y.startsWith("diff --git")){let w=y.match(/diff --git a\/(.+) b\/(.+)/);w&&d.add(w[2])}let m=["-rn","-E","--null","-H","--exclude=*.md","--exclude=*.txt","--exclude=*.json","--exclude=*.yaml","--exclude=*.yml"];e.ignore_case&&m.push("-i"),e.include&&m.push(`--include=${e.include}`),e.type&&m.push(`--include=*.${e.type}`),e.context?m.push("-C",String(e.context)):(e.before_context&&m.push("-B",String(e.before_context)),e.after_context&&m.push("-A",String(e.after_context))),e.output_mode==="files_with_matches"?m.push("-l"):e.output_mode==="count"&&m.push("-c"),m.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage");let{ToolProgress:h}=Pn(),p=new h("grep","Searching staged content...");p.start();let g=[];for(let y of d)try{let w=ke.join(process.cwd(),y);if(await ht(w)){let k=[...m];k.push(e.pattern,w);let{stdout:R}=await Vi("grep",k,{cwd:process.cwd(),timeout:3e4,maxBuffer:2*1024*1024});if(e.output_mode==="files_with_matches"||e.output_mode==="count"){let x=R.trim().split(`
|
|
223
|
+
`).filter(_=>_.trim());g=g.concat(x)}else{let x=R.split("\0");for(let _=0;_<x.length;_+=2){let b=x[_+1];if(b){let A=b.split(`
|
|
224
|
+
`).filter(O=>O.trim());for(let O of A)g.push(`${y}:${O}`)}}}}}catch{}return p.update({count:g.length,detail:"in staged files"}),p.stop(),g.join(`
|
|
225
225
|
`).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}=Pn(),a=new i("grep","Searching...");a.start();try{let{stdout:l}=await Vi("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(`
|
|
226
|
-
`).filter(m=>m.trim());else{let m=l.split("\0");u=[];for(let h=0;h<m.length;h+=2){let p=m[h],g=m[h+1];if(p&&g){let
|
|
227
|
-
`).filter(
|
|
228
|
-
`).trim()||"(no matches)"}catch(l){return a.stop(),l.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await ea();let o=lt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ht(o)){let
|
|
229
|
-
|
|
230
|
-
Most similar text (line ${k.line}, distance ${k.distance}):
|
|
231
|
-
${k.text}`:`ERROR: Patch ${$+1} old_text not found in ${o} (strict mode \u2014 exact match required)`}else{let k=bd(i,_);if(k)d.push({old_text:k,new_text:R}),f=!0;else{let x=Ns(i,_);if(x){let b=Math.max(3,Math.ceil(_.length*.05));if(x.distance<=b)d.push({old_text:x.text,new_text:R}),m=!0;else return`ERROR: Patch ${$+1} old_text not found in ${o}
|
|
226
|
+
`).filter(m=>m.trim());else{let m=l.split("\0");u=[];for(let h=0;h<m.length;h+=2){let p=m[h],g=m[h+1];if(p&&g){let y=g.split(`
|
|
227
|
+
`).filter(w=>w.trim());for(let w of y)u.push(`${p}:${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),a.update({count:u.length,detail:`in ${o}`}),a.stop(),u.join(`
|
|
228
|
+
`).trim()||"(no matches)"}catch(l){return a.stop(),l.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await ea();let o=lt(e.path);if(!o)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ht(o)){let w=await Vo(e.path);if(w.fixedPath)o=w.fixedPath,console.log(`${ee.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${ke.relative(process.cwd(),o)}${ee.reset}`);else return`ERROR: File not found: ${e.path}${w.message?`
|
|
229
|
+
`+w.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await De.readFile(o,"utf-8"),{getActiveModelId:a,getActiveProviderName:l}=Ae(),u=_d(a(),l()),d=[],f=!1,m=!1;for(let w=0;w<r.length;w++){let{old_text:k,new_text:R}=r[w];if(i.includes(k))d.push({old_text:k,new_text:R});else if(u==="strict"){let x=Ns(i,k);return x?`ERROR: Patch ${w+1} old_text not found in ${o} (strict mode \u2014 exact match required)
|
|
232
230
|
Most similar text (line ${x.line}, distance ${x.distance}):
|
|
233
|
-
${x.text}
|
|
231
|
+
${x.text}`:`ERROR: Patch ${w+1} old_text not found in ${o} (strict mode \u2014 exact match required)`}else{let x=bd(i,k);if(x)d.push({old_text:x,new_text:R}),f=!0;else{let _=Ns(i,k);if(_){let b=Math.max(3,Math.ceil(k.length*.05));if(_.distance<=b)d.push({old_text:_.text,new_text:R}),m=!0;else return`ERROR: Patch ${w+1} old_text not found in ${o}
|
|
232
|
+
Most similar text (line ${_.line}, distance ${_.distance}):
|
|
233
|
+
${_.text}`}else return`ERROR: Patch ${w+1} old_text not found in ${o}`}}}let h=i;for(let{old_text:w,new_text:k}of d)h=h.split(w).join(k);if(!n.autoConfirm){let w=await As(o,h);if(Xo(o,i,h,{annotations:w}),!await Cs(f?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await De.writeFile(o,h,"utf-8");let p=/[/\\]\.git[/\\]hooks[/\\]/.test(o)||o.endsWith(".sh")||h.startsWith("#!");p&&await De.chmod(o,493),Jo("patch_file",o,i,h);let g=m?" (auto-fixed)":f?" (fuzzy match)":"",y=p?" [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 Qi.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 Qi.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||[],a=`[Perplexity grounded search]
|
|
234
234
|
|
|
235
235
|
${r}`;return i.length>0&&(a+=`
|
|
236
236
|
|
|
@@ -284,16 +284,16 @@ ${ee.yellow} \u26A0 ${a}: deployment/${e.deployment} (ns: ${o})${ee.reset}`),!a
|
|
|
284
284
|
or to read the whole file:
|
|
285
285
|
cat /path/to/file
|
|
286
286
|
NEVER use sed -n again \u2014 it will always be blocked.`:`BLOCKED: Remote command matches SSH secret-exposure pattern: ${a}
|
|
287
|
-
HINT: Do not read .env, credentials, or private key files via ssh_exec \u2014 secrets would appear in tool output. Reference variable names or file paths instead.`;if(s=s.replace(/(-[BAC])\s*(\d+)/g,(b,A,O)=>{let
|
|
287
|
+
HINT: Do not read .env, credentials, or private key files via ssh_exec \u2014 secrets would appear in tool output. Reference variable names or file paths instead.`;if(s=s.replace(/(-[BAC])\s*(\d+)/g,(b,A,O)=>{let P=Math.min(Number(O),20);return`${A} ${P}`}),s=s.replace(/(--(?:before|after|context)=)(\d+)/g,(b,A,O)=>A+Math.min(Number(O),20)),/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(s)){let b=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
288
288
|
${ee.yellow} \u26A0 Remote command on ${b}: ${s}${ee.reset}`),!await Tt(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:u,stderr:d,exitCode:f,error:m}=await ct(o,s,{timeout:i,sudo:r}),h=[u,d].filter(Boolean).join(`
|
|
289
289
|
`).trim();if(f!==0)return`EXIT ${f}
|
|
290
290
|
${m||h||"(no output)"}`;let p=/\bgrep\b/.test(s),g=h;p&&(g=g.split(`
|
|
291
291
|
`).filter(b=>b!=="--").join(`
|
|
292
|
-
`));let
|
|
293
|
-
`)
|
|
294
|
-
|
|
295
|
-
`));let
|
|
296
|
-
`),
|
|
292
|
+
`));let y=p?100:200,w=g.split(`
|
|
293
|
+
`);w.length>y&&(g=`(${w.length-y} earlier lines omitted \u2014 showing last ${y})
|
|
294
|
+
`+w.slice(-y).join(`
|
|
295
|
+
`));let k=4,R=g.split(`
|
|
296
|
+
`),x=[],_=0;for(;_<R.length;){let b=_+1;for(;b<R.length&&R[b]===R[_];)b++;let A=b-_;if(x.push(R[_]),A>k)x.push(`... (${A-1} identical lines omitted)`);else for(let O=1;O<A;O++)x.push(R[_]);_=b}return x.join(`
|
|
297
297
|
`)||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let o;try{o=kt(e.server)}catch(i){return`ERROR: ${i.message}`}let s=o.user?`${o.user}@${o.host}`:o.host;if(console.log(`
|
|
298
298
|
${ee.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${s}:${e.remote_path}${ee.reset}`),!await Tt(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await lw(o,e.local_path,e.remote_path)}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let o;try{o=kt(e.server)}catch(s){return`ERROR: ${s.message}`}try{return await uw(o,e.remote_path,e.local_path)}catch(s){return`ERROR: ${s.message}`}}case"remote_agent":{let o=require("path").join(process.cwd(),".nex","servers.json"),s=null;try{s=JSON.parse(require("fs").readFileSync(o,"utf-8"))[e.server]||null}catch{}let r=s?`${s.user||"root"}@${s.host}`:e.server,i=s?.key?["-i",s.key]:[],a=e.project_path||s?.home||"~",l=e.model||"",d=["TMPFILE=$(mktemp /tmp/nexcode-XXXXXX.txt)",`echo "${Buffer.from(e.task).toString("base64")}" | base64 -d > "$TMPFILE"`,`cd "${a}" 2>/dev/null || true`,l?`nex-code --prompt-file "$TMPFILE" --auto --model "${l}" 2>&1`:'nex-code --prompt-file "$TMPFILE" --auto 2>&1',"EXIT_CODE=$?",'rm -f "$TMPFILE"',"exit $EXIT_CODE"].join(" && "),{spawnSync:f}=require("child_process"),m=f("ssh",[...i,"-o","StrictHostKeyChecking=no","-o","ConnectTimeout=10",r,`bash -c '${d}'`],{encoding:"utf-8",maxBuffer:10*1024*1024,timeout:3e5});if(m.error)return`ERROR: SSH connection failed: ${m.error.message}`;let h=(m.stdout||"")+(m.stderr||"");return m.status!==0?`Remote nex-code exited with code ${m.status}.
|
|
299
299
|
${h.slice(-2e3)}`:h.slice(-5e3)||"Remote nex-code completed (no output)"}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let o=["status","start","stop","restart","reload","enable","disable"];if(!o.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${o.join(", ")}`;let s=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!s)try{i=kt(e.server)}catch(l){return`ERROR: ${l.message}`}if(!r){let l=s?"local machine":i.user?`${i.user}@${i.host}`:i.host;if(console.log(`
|
|
@@ -323,7 +323,7 @@ ${ee.yellow} \u26A0 Deploy [rsync]: ${f} \u2192 ${r}:${e.remote_path}${ee.reset
|
|
|
323
323
|
${d}${e.deploy_script?`
|
|
324
324
|
${e.deploy_script}`:""}`;let{stdout:f,stderr:m,exitCode:h,error:p}=await ct(s,d,{timeout:12e4});if(i=[f,m].filter(Boolean).join(`
|
|
325
325
|
`).trim(),h!==0)return`ERROR (git pull, exit ${h}):
|
|
326
|
-
${p||i}`}else{let d=s.key?`-e "ssh -i ${s.key.replace(/^~/,require("os").homedir())}${s.port&&Number(s.port)!==22?` -p ${s.port}`:""}"`:s.port&&Number(s.port)!==22?`-e "ssh -p ${s.port}"`:"",f=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),m=e.dry_run?"--dry-run":"",h=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,p=`rsync -avz --delete ${m} ${f} ${d} ${h} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:
|
|
326
|
+
${p||i}`}else{let d=s.key?`-e "ssh -i ${s.key.replace(/^~/,require("os").homedir())}${s.port&&Number(s.port)!==22?` -p ${s.port}`:""}"`:s.port&&Number(s.port)!==22?`-e "ssh -p ${s.port}"`:"",f=(e.exclude||[]).map(g=>`--exclude="${g}"`).join(" "),m=e.dry_run?"--dry-run":"",h=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,p=`rsync -avz --delete ${m} ${f} ${d} ${h} ${r}:${e.remote_path}`.trim().replace(/\s+/g," ");try{let{stdout:g,stderr:y}=await ve(p,{timeout:12e4});i=(g||y||"").trim()}catch(g){return`ERROR (rsync): ${(g.stderr||g.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN [rsync]:
|
|
327
327
|
${i||"(nothing to sync)"}`}let a="";if(e.deploy_script){let{stdout:d,stderr:f,exitCode:m,error:h}=await ct(s,e.deploy_script,{timeout:12e4}),p=[d,f].filter(Boolean).join(`
|
|
328
328
|
`).trim();if(m!==0)return`${o==="git"?"git pull":"rsync"} OK
|
|
329
329
|
|
|
@@ -343,37 +343,37 @@ Health check FAILED: ${d} \u2192 ${m.message}`,(o==="git"?"git pull OK":"rsync O
|
|
|
343
343
|
Health check FAILED (exit ${p}): ${g}`,(o==="git"?"git pull OK":"rsync OK")+i+a+l;l=`
|
|
344
344
|
|
|
345
345
|
Health check: \u2713 ${g||"(exit 0)"}`}}let u=o==="git"?`${r}:${e.remote_path}`:`${e.local_path} \u2192 ${r}:${e.remote_path}`;return`Deployed [${o}] ${u}
|
|
346
|
-
${i}${a}${l}`.trim()}case"deployment_status":{let o=fw(),s=e.config?[e.config]:Object.keys(o);if(s.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of s){let a=o[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let l=kt(a.server||i),d=(await ct(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",f="unknown";if(d&&a.deploy_script){let h=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(h)try{f=(await ct(l,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{f="inactive"}}let m="N/A";if(a.health_check){let h=a.health_check.trim();if(/^https?:\/\//.test(h))try{let p=require("node-fetch"),g=await Promise.race([p(h),new Promise((w
|
|
346
|
+
${i}${a}${l}`.trim()}case"deployment_status":{let o=fw(),s=e.config?[e.config]:Object.keys(o);if(s.length===0)return"No deploy configs found. Create .nex/deploy.json to configure deployments.";let r=[];for(let i of s){let a=o[i];if(!a){r.push(`${i}: NOT FOUND`);continue}try{let l=kt(a.server||i),d=(await ct(l,"echo OK",{timeout:1e4})).stdout.trim()==="OK",f="unknown";if(d&&a.deploy_script){let h=a.deploy_script.match(/systemctl\s+\w+\s+(\S+)/);if(h)try{f=(await ct(l,`systemctl is-active ${h[1]}`,{timeout:1e4})).stdout.trim()}catch{f="inactive"}}let m="N/A";if(a.health_check){let h=a.health_check.trim();if(/^https?:\/\//.test(h))try{let p=require("node-fetch"),g=await Promise.race([p(h),new Promise((y,w)=>setTimeout(()=>w(new Error("timeout")),1e4))]);m=g.ok?"healthy":`HTTP ${g.status}`}catch(p){m=`unhealthy: ${p.message.substring(0,50)}`}else try{m=(await ct(l,h,{timeout:1e4})).exitCode===0?"healthy":"unhealthy"}catch{m="unhealthy"}}r.push(`${i}: server=${d?"reachable":"unreachable"} service=${f} health=${m}`)}catch(l){r.push(`${i}: ERROR \u2014 ${l.message}`)}}return`Deployment Status:
|
|
347
347
|
${r.join(`
|
|
348
|
-
`)}`}case"frontend_recon":{let o=process.cwd(),s=(e.type||"").toLowerCase(),r=[],i=async(
|
|
349
|
-
`),
|
|
350
|
-
`);return O.length>
|
|
351
|
-
... (${O.length-
|
|
352
|
-
`).filter(Boolean)}catch{return[]}},d=async(
|
|
348
|
+
`)}`}case"frontend_recon":{let o=process.cwd(),s=(e.type||"").toLowerCase(),r=[],i=async(x,_=120)=>{try{let b=ke.isAbsolute(x)?x:ke.join(o,x),O=(await De.readFile(b,"utf8")).split(`
|
|
349
|
+
`),P=O.slice(0,_).join(`
|
|
350
|
+
`);return O.length>_?P+`
|
|
351
|
+
... (${O.length-_} more lines \u2014 use read_file for full content)`:P}catch{return null}},l=["node_modules",".git","dist","build","vendor",".next","__pycache__","venv",".venv"].map(x=>`-not -path "*/${x}/*"`).join(" "),u=async x=>{try{let{stdout:_}=await ve(`find "${o}" -type f -name "${x}" ${l} 2>/dev/null | head -10`,{timeout:8e3});return _.trim().split(`
|
|
352
|
+
`).filter(Boolean)}catch{return[]}},d=async(x,_)=>{try{let{stdout:b}=await ve(`grep -rl "${x}" "${o}" --include="${_}" --exclude-dir=node_modules --exclude-dir=.git --exclude-dir=dist --exclude-dir=build 2>/dev/null | head -5`,{timeout:8e3});return b.trim().split(`
|
|
353
353
|
`).filter(Boolean)}catch{return[]}};r.push(`## STEP 1: Design Tokens
|
|
354
|
-
`);let f=[...await u("tailwind.config.js"),...await u("tailwind.config.ts"),...await u("tailwind.config.mjs")];if(f.length>0){let
|
|
354
|
+
`);let f=[...await u("tailwind.config.js"),...await u("tailwind.config.ts"),...await u("tailwind.config.mjs")];if(f.length>0){let x=await i(f[0],80);x&&r.push(`### Tailwind config (${ke.relative(o,f[0])})
|
|
355
355
|
\`\`\`js
|
|
356
|
-
${
|
|
357
|
-
\`\`\``)}else r.push("(no tailwind.config found)");let m=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],h=!1;for(let
|
|
356
|
+
${x}
|
|
357
|
+
\`\`\``)}else r.push("(no tailwind.config found)");let m=["variables.css","_variables.scss","tokens.css","base.css","global.css","main.css","index.css","app.css","style.css","styles.css"],h=!1;for(let x of m){let _=await u(x);for(let b of _){let A=await i(b,100);if(A&&A.includes(":root")){r.push(`### CSS Variables (${ke.relative(o,b)})
|
|
358
358
|
\`\`\`css
|
|
359
359
|
${A}
|
|
360
|
-
\`\`\``),h=!0;break}}if(h)break}if(!h){let
|
|
360
|
+
\`\`\``),h=!0;break}}if(h)break}if(!h){let x=await d(":root","*.css");if(x.length>0){let _=await i(x[0],100);_&&r.push(`### CSS Variables (${ke.relative(o,x[0])})
|
|
361
361
|
\`\`\`css
|
|
362
|
-
${
|
|
362
|
+
${_}
|
|
363
363
|
\`\`\``),h=!0}}h||r.push("(no CSS custom properties / :root found)"),r.push(`
|
|
364
364
|
## STEP 2: Main Layout / Index Page
|
|
365
|
-
`);let p=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let
|
|
365
|
+
`);let p=["base.html","_base.html","layout.html","base.jinja","App.vue","App.jsx","App.tsx","_app.jsx","_app.tsx","_app.js","layout.vue","index.html"],g=!1;for(let x of p){let _=await u(x);if(_.length>0){let b=await i(_[0],150);if(b){r.push(`### Main layout: ${ke.relative(o,_[0])}
|
|
366
366
|
\`\`\`html
|
|
367
367
|
${b}
|
|
368
368
|
\`\`\``),g=!0;break}}}g||r.push("(no main layout/index file found \u2014 try read_file on your root template manually)"),r.push(`
|
|
369
369
|
## STEP 3: Reference Component (same type)
|
|
370
|
-
`);let
|
|
371
|
-
`).filter(Boolean)}catch{
|
|
370
|
+
`);let y=[];if(s){for(let x of["*.html","*.vue","*.jsx","*.tsx"])if(y=await d(s,x),y.length>0)break}if(y.length===0)try{let{stdout:x}=await ve(`find "${o}" -type f \\( -name "*.html" -o -name "*.vue" -o -name "*.jsx" -o -name "*.tsx" \\) -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/dist/*" -not -path "*/build/*" -not -name "base.html" -not -name "_base.html" -not -name "layout.html" -not -name "App.vue" -not -name "App.jsx" 2>/dev/null | head -20`,{timeout:8e3});y=x.trim().split(`
|
|
371
|
+
`).filter(Boolean)}catch{y=[]}if(y.length>0){let x=y[0],_=await i(x,150);_?r.push(`### Reference: ${ke.relative(o,x)}
|
|
372
372
|
\`\`\`html
|
|
373
|
-
${
|
|
373
|
+
${_}
|
|
374
374
|
\`\`\``):r.push("(reference file found but could not be read)")}else r.push("(no reference component found \u2014 check manually with glob or list_directory)");r.push(`
|
|
375
375
|
## STEP 4: Framework Stack
|
|
376
|
-
`);let
|
|
376
|
+
`);let w=[],k=await i(ke.join(o,"package.json"),999);if(k){if((k.includes('"react"')||k.includes("'react'"))&&w.push("React"),k.includes('"vue"')||k.includes("'vue'")){let _=k.match(/"vue":\s*"[\^~]?(\d+)/);w.push(_?`Vue.js v${_[1]}`:"Vue.js")}let x=k.match(/"alpinejs":\s*"[\^~]?(\d+)/);x&&w.push(`Alpine.js v${x[1]} (\u26A0 v2 vs v3 API differs!)`),(k.includes('"htmx')||k.includes("'htmx"))&&w.push("HTMX"),k.includes('"tailwindcss"')&&w.push("Tailwind CSS"),k.includes('"bootstrap"')&&w.push("Bootstrap")}if((await ht(ke.join(o,"manage.py"))||(await i(ke.join(o,"requirements.txt"),50)||"").includes("Django"))&&w.push("Django (server-rendered templates)"),!w.some(x=>x.includes("Alpine"))){let x=await d("alpinejs","*.html");if(x.length>0){let b=(await i(x[0],30)||"").match(/alpinejs[@/]v?(\d)/);w.push(b?`Alpine.js v${b[1]} (via CDN \u2014 \u26A0 v2 vs v3 API differs!)`:"Alpine.js (via CDN \u2014 check version!)")}}return w.some(x=>x.includes("HTMX"))||(await d("htmx","*.html")).length>0&&w.push("HTMX (via CDN)"),w.length>0?(r.push(w.map(x=>`- ${x}`).join(`
|
|
377
377
|
`)),r.push(`
|
|
378
378
|
\u26A0 Use ONLY the frameworks listed above. Do NOT mix (e.g. no fetch() when HTMX is used for the same action).`)):r.push("(framework not detected \u2014 check package.json or script tags manually)"),r.push(`
|
|
379
379
|
---
|
|
@@ -442,12 +442,12 @@ ${u}
|
|
|
442
442
|
- \u274C Do NOT \`list_directory\` on server paths \u2014 the local project is the source, not the running instance
|
|
443
443
|
|
|
444
444
|
**When in doubt:** If a path contains \`logs/\`, \`/var/log/\`, or \`/home/<user>/\` \u2014 it is on the server. SSH there.`}Td.exports={getServerContext:xw,getDeploymentContextBlock:Sw,hasServerOS:kw,getProfileNames:vw,OS_HINTS:na}});var tr=G((nv,Ad)=>{var Rt=require("fs").promises,Rd=require("fs"),et=require("path"),Zo=require("util").promisify(require("child_process").exec),{C:Yn}=Ce(),{getMergeConflicts:Cd}=en(),{getServerContext:Ew}=sa(),Tw=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function Rw(t){try{return Rd.readFileSync(t,"utf-8").split(`
|
|
445
|
-
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function Cw(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 Aw(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=et.join(t,".gitignore"),r=[...o,...Rw(s)],i=0,a=[et.basename(t)+"/"];function l(u,d,f){if(f>e||i>=n)return;let m;try{m=Rd.readdirSync(u,{withFileTypes:!0})}catch{return}m.sort((p,g)=>p.isDirectory()!==g.isDirectory()?p.isDirectory()?-1:1:p.name.localeCompare(g.name));let h=m.filter(p=>!(Tw.has(p.name)||p.name.startsWith(".")&&p.name!==".env.example"||Cw(p.name,r)));for(let p=0;p<h.length;p++){if(i>=n){a.push(`${d}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[p],
|
|
446
|
-
`)}var oa=new Map,zn=new Map,er=null,Ow=3e4;async function nn(t){try{return await t()}catch{return null}}async function Nw(){if(!er||Date.now()>er)return!1;let t=[et.join(process.cwd(),"package.json"),et.join(process.cwd(),"README.md"),et.join(process.cwd(),".gitignore")];for(let e of t)try{let n=await Rt.stat(e),o=zn.get(e);if(!o||n.mtimeMs!==o)return!1}catch{if(zn.has(e))return!1}try{let e=et.join(process.cwd(),".git","HEAD"),n=await Rt.stat(e),o=zn.get(e);if(!o||n.mtimeMs!==o)return!1}catch{}return!0}async function Mw(){let t=[et.join(process.cwd(),"package.json"),et.join(process.cwd(),"README.md"),et.join(process.cwd(),".gitignore"),et.join(process.cwd(),".git","HEAD")];for(let e of t)try{let n=await Rt.stat(e);zn.set(e,n.mtimeMs)}catch{zn.delete(e)}}async function Pw(t){let e="fileContext",n=oa.get(e),o=!1;if(n&&await Nw()&&(o=!0),!o){let u=[],d=et.join(t,"package.json");if(await nn(()=>Rt.access(d).then(()=>!0).catch(()=>!1)))try{let
|
|
445
|
+
`).map(n=>n.trim()).filter(n=>n&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/\/$/,""))}catch{return[]}}function Cw(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 Aw(t,{maxDepth:e=3,maxFiles:n=200,giPatterns:o=[]}={}){let s=et.join(t,".gitignore"),r=[...o,...Rw(s)],i=0,a=[et.basename(t)+"/"];function l(u,d,f){if(f>e||i>=n)return;let m;try{m=Rd.readdirSync(u,{withFileTypes:!0})}catch{return}m.sort((p,g)=>p.isDirectory()!==g.isDirectory()?p.isDirectory()?-1:1:p.name.localeCompare(g.name));let h=m.filter(p=>!(Tw.has(p.name)||p.name.startsWith(".")&&p.name!==".env.example"||Cw(p.name,r)));for(let p=0;p<h.length;p++){if(i>=n){a.push(`${d}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[p],y=p===h.length-1,w=y?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",k=d+(y?" ":"\u2502 "),R=g.isDirectory()?g.name+"/":g.name;a.push(`${d}${w}${R}`),i++,g.isDirectory()&&l(et.join(u,g.name),k,f+1)}}return l(t,"",1),a.join(`
|
|
446
|
+
`)}var oa=new Map,zn=new Map,er=null,Ow=3e4;async function nn(t){try{return await t()}catch{return null}}async function Nw(){if(!er||Date.now()>er)return!1;let t=[et.join(process.cwd(),"package.json"),et.join(process.cwd(),"README.md"),et.join(process.cwd(),".gitignore")];for(let e of t)try{let n=await Rt.stat(e),o=zn.get(e);if(!o||n.mtimeMs!==o)return!1}catch{if(zn.has(e))return!1}try{let e=et.join(process.cwd(),".git","HEAD"),n=await Rt.stat(e),o=zn.get(e);if(!o||n.mtimeMs!==o)return!1}catch{}return!0}async function Mw(){let t=[et.join(process.cwd(),"package.json"),et.join(process.cwd(),"README.md"),et.join(process.cwd(),".gitignore"),et.join(process.cwd(),".git","HEAD")];for(let e of t)try{let n=await Rt.stat(e);zn.set(e,n.mtimeMs)}catch{zn.delete(e)}}async function Pw(t){let e="fileContext",n=oa.get(e),o=!1;if(n&&await Nw()&&(o=!0),!o){let u=[],d=et.join(t,"package.json");if(await nn(()=>Rt.access(d).then(()=>!0).catch(()=>!1)))try{let y=await Rt.readFile(d,"utf-8"),w=JSON.parse(y),k={name:w.name,version:w.version};w.scripts&&(k.scripts=Object.keys(w.scripts).slice(0,15)),w.dependencies&&(k.deps=Object.keys(w.dependencies).length),w.devDependencies&&(k.devDeps=Object.keys(w.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(k)}`)}catch{}let m=et.join(t,"README.md");if(await nn(()=>Rt.access(m).then(()=>!0).catch(()=>!1))){let w=(await Rt.readFile(m,"utf-8")).split(`
|
|
447
447
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
448
|
-
${
|
|
449
|
-
`)}`)}let p=et.join(t,".gitignore");if(await nn(()=>Rt.access(p).then(()=>!0).catch(()=>!1))){let
|
|
450
|
-
${
|
|
448
|
+
${w.join(`
|
|
449
|
+
`)}`)}let p=et.join(t,".gitignore");if(await nn(()=>Rt.access(p).then(()=>!0).catch(()=>!1))){let y=await Rt.readFile(p,"utf-8");u.push(`GITIGNORE:
|
|
450
|
+
${y.trim()}`)}n=u.join(`
|
|
451
451
|
|
|
452
452
|
`),oa.set(e,n),er=Date.now()+Ow,await Mw()}let s=[n],[r,i,a,l]=await Promise.all([nn(async()=>{let{stdout:u}=await Zo("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),nn(async()=>{let{stdout:u}=await Zo("git status --short",{cwd:t,timeout:5e3});return u.trim()}),nn(async()=>{let{stdout:u}=await Zo("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),Cd()]);if(r&&s.push(`GIT BRANCH: ${r}`),i&&s.push(`GIT STATUS:
|
|
453
453
|
${i}`),a&&s.push(`RECENT COMMITS:
|
|
@@ -455,7 +455,7 @@ ${a}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
|
455
455
|
`);s.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
456
456
|
${u}`)}try{let u=Ew();u&&s.push(u)}catch{}return s.join(`
|
|
457
457
|
|
|
458
|
-
`)}async function Iw(t){let e=et.join(t,"package.json"),n="";if(await nn(()=>Rt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Rt.readFile(e,"utf-8"),a=JSON.parse(i);n=`${a.name||"?"} v${a.version||"?"}`}catch{}let[s,r]=await Promise.all([nn(async()=>{let{stdout:i}=await Zo("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Cd()]);if(r&&r.length>0){console.log(`${Yn.red} \u26A0 ${r.length} unresolved merge conflict(s):${Yn.reset}`);for(let i of r)console.log(`${Yn.red} ${i.file}${Yn.reset}`);console.log(`${Yn.yellow} \u2192 Resolve conflicts before starting tasks${Yn.reset}`)}console.log()}Ad.exports={gatherProjectContext:Pw,printContext:Iw,generateFileTree:Aw,_clearContextCache:()=>{oa.clear(),zn.clear(),er=null}}});var Ct=G((sv,Pd)=>{var sn=require("fs"),ra=require("path"),{atomicWrite:Lw}=Qt();function nr(){return ra.join(process.cwd(),".nex","sessions")}function Od(){let t=nr();sn.existsSync(t)||sn.mkdirSync(t,{recursive:!0})}function ia(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return ra.join(nr(),`${e}.json`)}function aa(t,e,n={}){Od();let o=ia(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 Lw(o,JSON.stringify(s,null,2)),{path:o,name:t}}function Nd(t){let e=ia(t);if(!sn.existsSync(e))return null;try{return JSON.parse(sn.readFileSync(e,"utf-8"))}catch{return null}}function Md(){Od();let t=nr(),e=sn.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(sn.readFileSync(ra.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 Dw(t){let e=ia(t);return sn.existsSync(e)?(sn.unlinkSync(e),!0):!1}function jw(){let t=Md();return t.length===0?null:Nd(t[0].name)}var _n=null,Ht=null,Ms=null;function qw(t,e={}){t.length!==0&&(_n&&clearTimeout(_n),Ht=t,Ms=e||{},_n=setTimeout(()=>{Ht&&Ht.length>0&&aa("_autosave",Ht,Ms),_n=null,Ht=null,Ms=null},5e3))}function Fw(){_n&&(clearTimeout(_n),_n=null),Ht&&Ht.length>0&&(aa("_autosave",Ht,Ms),Ht=null,Ms=null)}Pd.exports={saveSession:aa,loadSession:Nd,listSessions:Md,deleteSession:Dw,getLastSession:jw,autoSave:qw,flushAutoSave:Fw,_getSessionsDir:nr}});var sr=G((ov,Wd)=>{"use strict";var Ps=require("fs"),Id=require("path");function Ld(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})}),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})}))}),e}function Dd(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 jd(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 qd(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 Fd(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 Ud(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=Ld(t),s=Dd(t),r=o.length;t.some(E=>E.role==="user"&&typeof E.content=="string"&&E.content.startsWith("[SYSTEM WARNING]")&&(E.content.includes("edited")||E.content.includes("bash command")||E.content.includes("grep pattern")||E.content.includes("re-read")||E.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 a=o.find(E=>{let M=E.input?.command||E.input?.cmd||"";return/\bsed\s+-n\b/.test(M)});if(a){let E=(a.input?.command||a.input?.cmd||"").slice(0,80);e-=1.5,n.push(`sed -n anti-pattern used: ${E}`)}o.find(E=>{if(E.name!=="grep"&&E.name!=="bash"&&E.name!=="ssh_exec")return!1;let M=E.input?.command||E.input?.cmd||"",W=E.input?.pattern||"",H=`${M} ${W}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(H)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(H)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let u=t.some(E=>E.role==="assistant"),d=jd(t),m=qd(t,3).some(E=>E.length>100&&!/^[^.!]{0,40}\?$/.test(E));if(u&&!m&&(d.length<50||/^[^.!]{0,40}\?$/.test(d))){e-=2;let E=d.length>0?`"${d.slice(0,60)}..."`:"(no assistant text found)";n.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${E}`)}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(E=>{let M=typeof E.content=="string"?E.content:Array.isArray(E.content)?E.content.map(W=>typeof W=="string"?W:W.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(M)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let g=Fd(o),w=0,$="";for(let[E,M]of g)M>w&&(w=M,$=E);if(w>=3){let[E]=$.split("|");e-=1,n.push(`Same tool call repeated ${w}\xD7 (tool: ${E})`)}let _=!1;for(let E of s)if(E.content&&E.content.includes('"valid":true')&&o.filter(W=>W.index>E.index).length>0){_=!0;break}_&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let R=o.filter(E=>E.name==="ssh_exec");if(R.length>=8){let E=0,M=1;for(let W=1;W<R.length;W++)R[W].index<=R[W-1].index+2?M++:(E=Math.max(E,M),M=1);E=Math.max(E,M),E>=8&&(e-=.5,n.push(`SSH reconnect storm: ${E} consecutive SSH calls`))}let k=new Map;for(let E of o)if(E.name==="read_file"&&E.input?.path){let M=E.input.path;k.has(M)||k.set(M,{count:0,ranges:[]});let W=k.get(M);if(W.count++,E.input.line_start!=null){let H=E.input.line_start||1,ne=E.input.line_end||H+350;W.ranges.push([H,ne])}}function x(E,M,W){for(let[H,ne]of W){let P=Math.max(E,H),F=Math.min(M,ne);if(F>P){let se=F-P,z=M-E||1;if(se/z>=.7)return!0}}return!1}let b=0,A="";for(let[E,M]of k){if(M.count<3)continue;if(M.ranges.length===M.count){let H=!1,ne=[];for(let[P,F]of M.ranges){if(ne.length>0&&x(P,F,ne)){H=!0;break}ne.push([P,F])}if(!H)continue}M.count>b&&(b=M.count,A=E)}if(b>=3){e-=1;let E=A.split("/").slice(-2).join("/");n.push(`read_file loop: "${E}" read ${b}\xD7 (file already in context)`)}let O=0,I="";for(let[E,M]of k){if(M.ranges.length<4)continue;let W=[],H=!1;for(let[ne,P]of M.ranges){if(W.length>0&&x(ne,P,W)){H=!0;break}W.push([ne,P])}!H&&M.ranges.length>O&&(O=M.ranges.length,I=E)}if(O>=4){e-=.5;let E=I.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${E}" read in ${O} sequential sections \u2014 use grep instead`)}let q=new Map;for(let E of o)if(E.name==="grep"&&E.input?.path&&E.input?.pattern){let M=E.input.path;q.has(M)||q.set(M,new Set),q.get(M).add(E.input.pattern)}let Me=0,xe="";for(let[E,M]of q)M.size>Me&&(Me=M.size,xe=E);if(Me>=3){e-=.75;let E=xe.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${E}" searched ${Me}\xD7 with different patterns (file already in context)`)}{let E=new Set,M=new Set,W=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let ne of o){if(ne.name==="write_file"&&ne.input?.path){let P=ne.input.path.split("/").pop(),F=ne.input.path.includes("/tests/");W.test(P)&&!F&&E.add(ne.input.path)}if((ne.name==="bash"||ne.name==="ssh_exec")&&ne.input?.command){let P=ne.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(P)for(let F of P){let se=F.split(/\s+/),z=se[se.length-1];for(let Q of E)(Q.endsWith(z)||z.endsWith(Q.split("/").pop()))&&M.add(Q)}}}let H=M.size;if(H>=1){let ne=Math.min(H*.25,.5);e-=ne;let P=[...M].map(F=>F.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${P} \u2014 write inline logic or use tests/ instead`)}}let ue=s.filter(E=>E.content.startsWith("EXIT")).length;ue>=10?(e-=1,n.push(`Bash exit-error storm: ${ue} tool results started with EXIT (repeated failing commands)`)):ue>=5&&(e-=.5,n.push(`Repeated bash errors: ${ue} tool results with non-zero exit code`));for(let E of t){if(E.role!=="assistant")continue;let M="";if(typeof E.content=="string"?M=E.content:Array.isArray(E.content)&&(M=E.content.filter(z=>z&&(z.type==="text"||typeof z=="string")).map(z=>typeof z=="string"?z:z.text||"").join("")),M.length<=5e3)continue;let W=M.split(/(?<=\. )/).filter(z=>z.trim().length>0);if(W.length<6)continue;let H=new Map;for(let z=0;z<=W.length-3;z++){let Q=W.slice(z,z+3).join("").trim();Q.length>30&&H.set(Q,(H.get(Q)||0)+1)}let ne=0,P="";for(let[z,Q]of H)Q>ne&&(ne=Q,P=z);if(ne<3)continue;let se=P.length*ne/M.length;if(se>=.4||ne>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${ne}\xD7 same paragraph, ${Math.round(se*100)}% repeated)`);break}}{let E=new Set(["read_file","list_directory","search_files","glob","grep"]),M=t.some(H=>Array.isArray(H.tool_calls)?H.tool_calls.some(ne=>E.has(ne.function?.name)):Array.isArray(H.content)?H.content.some(ne=>ne.type==="tool_use"&&E.has(ne.name)):!1);t.some(H=>H.role==="assistant"&&typeof H.content=="string"&&(H.content.includes("## Steps")||H.content.includes("/plan approve")))&&!M&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let fe=s.filter(E=>E.content.startsWith("BLOCKED:"));if(fe.length>0){let E=Math.min(fe.length*.5,1.5);e-=E,n.push(`${fe.length} tool call${fe.length===1?"":"s"} blocked (agent attempted denied actions)`)}let ie=t.filter(E=>{let M=typeof E.content=="string"?E.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(M)}).length;if(ie>0){let E=Math.min(ie*1,2);e-=E,n.push(`Super-nuclear context wipe fired ${ie}\xD7 (context collapse \u2014 task too large or read loops)`)}{let E=!1,M=!1,W=!1;for(let ne of o){if(ne.name!=="bash")continue;let P=(ne.input?.command||ne.input?.cmd||"").trim();!(/cat\s*>/.test(P)||/<</.test(P))&&/\bcat\s+\S/.test(P)&&(E=!0),/^\s*ls(\s|$)/.test(P)&&!/npm|yarn|pnpm|make|git\b/.test(P)&&(M=!0),/\bfind\s+\S/.test(P)&&!/git\b|npm\b|-exec\b/.test(P)&&(W=!0)}let H=[E,M,W].filter(Boolean).length;if(H>0){let ne=Math.min(H*.25,.75);e-=ne;let P=[];E&&P.push("cat (use read_file)"),M&&P.push("ls (use list_directory)"),W&&P.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${P.join(", ")}`)}}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let be=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",te=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:be,issues:n,summary:te}}function Uw(t){try{let{loadSession:e}=Ct(),n=e(t);return n?Ud(n.messages||[]):null}catch{return null}}function Ww(t,e=null){let{score:n,grade:o,issues:s,summary:r}=t,i=e?.dim||"",a=e?.reset||"",l=e?.green||"",u=e?.yellow||"",d=e?.red||"",f=e?.cyan||"",m=e?.bold||"",h=n>=8?l:n>=6?u:d,p=`
|
|
458
|
+
`)}async function Iw(t){let e=et.join(t,"package.json"),n="";if(await nn(()=>Rt.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Rt.readFile(e,"utf-8"),a=JSON.parse(i);n=`${a.name||"?"} v${a.version||"?"}`}catch{}let[s,r]=await Promise.all([nn(async()=>{let{stdout:i}=await Zo("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Cd()]);if(r&&r.length>0){console.log(`${Yn.red} \u26A0 ${r.length} unresolved merge conflict(s):${Yn.reset}`);for(let i of r)console.log(`${Yn.red} ${i.file}${Yn.reset}`);console.log(`${Yn.yellow} \u2192 Resolve conflicts before starting tasks${Yn.reset}`)}console.log()}Ad.exports={gatherProjectContext:Pw,printContext:Iw,generateFileTree:Aw,_clearContextCache:()=>{oa.clear(),zn.clear(),er=null}}});var Ct=G((sv,Pd)=>{var sn=require("fs"),ra=require("path"),{atomicWrite:Lw}=Qt();function nr(){return ra.join(process.cwd(),".nex","sessions")}function Od(){let t=nr();sn.existsSync(t)||sn.mkdirSync(t,{recursive:!0})}function ia(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return ra.join(nr(),`${e}.json`)}function aa(t,e,n={}){Od();let o=ia(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 Lw(o,JSON.stringify(s,null,2)),{path:o,name:t}}function Nd(t){let e=ia(t);if(!sn.existsSync(e))return null;try{return JSON.parse(sn.readFileSync(e,"utf-8"))}catch{return null}}function Md(){Od();let t=nr(),e=sn.readdirSync(t).filter(o=>o.endsWith(".json")),n=[];for(let o of e)try{let s=JSON.parse(sn.readFileSync(ra.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 Dw(t){let e=ia(t);return sn.existsSync(e)?(sn.unlinkSync(e),!0):!1}function jw(){let t=Md();return t.length===0?null:Nd(t[0].name)}var _n=null,Ht=null,Ms=null;function qw(t,e={}){t.length!==0&&(_n&&clearTimeout(_n),Ht=t,Ms=e||{},_n=setTimeout(()=>{Ht&&Ht.length>0&&aa("_autosave",Ht,Ms),_n=null,Ht=null,Ms=null},5e3))}function Fw(){_n&&(clearTimeout(_n),_n=null),Ht&&Ht.length>0&&(aa("_autosave",Ht,Ms),Ht=null,Ms=null)}Pd.exports={saveSession:aa,loadSession:Nd,listSessions:Md,deleteSession:Dw,getLastSession:jw,autoSave:qw,flushAutoSave:Fw,_getSessionsDir:nr}});var sr=G((ov,Wd)=>{"use strict";var Ps=require("fs"),Id=require("path");function Ld(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})}),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})}))}),e}function Dd(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 jd(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 qd(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 Fd(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 Ud(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=Ld(t),s=Dd(t),r=o.length;t.some(E=>E.role==="user"&&typeof E.content=="string"&&E.content.startsWith("[SYSTEM WARNING]")&&(E.content.includes("edited")||E.content.includes("bash command")||E.content.includes("grep pattern")||E.content.includes("re-read")||E.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 a=o.find(E=>{let M=E.input?.command||E.input?.cmd||"";return/\bsed\s+-n\b/.test(M)});if(a){let E=(a.input?.command||a.input?.cmd||"").slice(0,80);e-=1.5,n.push(`sed -n anti-pattern used: ${E}`)}o.find(E=>{if(E.name!=="grep"&&E.name!=="bash"&&E.name!=="ssh_exec")return!1;let M=E.input?.command||E.input?.cmd||"",W=E.input?.pattern||"",H=`${M} ${W}`;return/(?:-[CAB]|--context|--after|--before)\s*[=\s]?([2-9][1-9]|\d{3,})/.test(H)||/grep.*-[CAB]\s*([2-9][1-9]|\d{3,})/.test(H)})&&(e-=1,n.push("grep used with >20 context lines (context flood risk)"));let u=t.some(E=>E.role==="assistant"),d=jd(t),m=qd(t,3).some(E=>E.length>100&&!/^[^.!]{0,40}\?$/.test(E));if(u&&!m&&(d.length<50||/^[^.!]{0,40}\?$/.test(d))){e-=2;let E=d.length>0?`"${d.slice(0,60)}..."`:"(no assistant text found)";n.push(`Session ends without diagnosis \u2014 last response too short or is only a question: ${E}`)}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(E=>{let M=typeof E.content=="string"?E.content:Array.isArray(E.content)?E.content.map(W=>typeof W=="string"?W:W.text||"").join(""):"";return/\[auto-compressed|context compacted|force-compressed/.test(M)})&&(e-=.5,n.push("Auto-compress triggered (context flood indicator)"));let g=Fd(o),y=0,w="";for(let[E,M]of g)M>y&&(y=M,w=E);if(y>=3){let[E]=w.split("|");e-=1,n.push(`Same tool call repeated ${y}\xD7 (tool: ${E})`)}let k=!1;for(let E of s)if(E.content&&E.content.includes('"valid":true')&&o.filter(W=>W.index>E.index).length>0){k=!0;break}k&&(e-=1.5,n.push('Stop-trigger ignored: tool result contained "valid":true but session continued with more tool calls'));let R=o.filter(E=>E.name==="ssh_exec");if(R.length>=8){let E=0,M=1;for(let W=1;W<R.length;W++)R[W].index<=R[W-1].index+2?M++:(E=Math.max(E,M),M=1);E=Math.max(E,M),E>=8&&(e-=.5,n.push(`SSH reconnect storm: ${E} consecutive SSH calls`))}let x=new Map;for(let E of o)if(E.name==="read_file"&&E.input?.path){let M=E.input.path;x.has(M)||x.set(M,{count:0,ranges:[]});let W=x.get(M);if(W.count++,E.input.line_start!=null){let H=E.input.line_start||1,ne=E.input.line_end||H+350;W.ranges.push([H,ne])}}function _(E,M,W){for(let[H,ne]of W){let I=Math.max(E,H),F=Math.min(M,ne);if(F>I){let se=F-I,z=M-E||1;if(se/z>=.7)return!0}}return!1}let b=0,A="";for(let[E,M]of x){if(M.count<3)continue;if(M.ranges.length===M.count){let H=!1,ne=[];for(let[I,F]of M.ranges){if(ne.length>0&&_(I,F,ne)){H=!0;break}ne.push([I,F])}if(!H)continue}M.count>b&&(b=M.count,A=E)}if(b>=3){e-=1;let E=A.split("/").slice(-2).join("/");n.push(`read_file loop: "${E}" read ${b}\xD7 (file already in context)`)}let O=0,P="";for(let[E,M]of x){if(M.ranges.length<4)continue;let W=[],H=!1;for(let[ne,I]of M.ranges){if(W.length>0&&_(ne,I,W)){H=!0;break}W.push([ne,I])}!H&&M.ranges.length>O&&(O=M.ranges.length,P=E)}if(O>=4){e-=.5;let E=P.split("/").slice(-2).join("/");n.push(`File-scroll pattern: "${E}" read in ${O} sequential sections \u2014 use grep instead`)}let D=new Map;for(let E of o)if(E.name==="grep"&&E.input?.path&&E.input?.pattern){let M=E.input.path;D.has(M)||D.set(M,new Set),D.get(M).add(E.input.pattern)}let Me=0,xe="";for(let[E,M]of D)M.size>Me&&(Me=M.size,xe=E);if(Me>=3){e-=.75;let E=xe.split("/").slice(-2).join("/");n.push(`grep flood on single file: "${E}" searched ${Me}\xD7 with different patterns (file already in context)`)}{let E=new Set,M=new Set,W=/^(test_|demo_|temp_|tmp_|scratch_)/;for(let ne of o){if(ne.name==="write_file"&&ne.input?.path){let I=ne.input.path.split("/").pop(),F=ne.input.path.includes("/tests/");W.test(I)&&!F&&E.add(ne.input.path)}if((ne.name==="bash"||ne.name==="ssh_exec")&&ne.input?.command){let I=ne.input.command.match(/\brm\s+(?:-\w+\s+)?(\S+)/g);if(I)for(let F of I){let se=F.split(/\s+/),z=se[se.length-1];for(let Q of E)(Q.endsWith(z)||z.endsWith(Q.split("/").pop()))&&M.add(Q)}}}let H=M.size;if(H>=1){let ne=Math.min(H*.25,.5);e-=ne;let I=[...M].map(F=>F.split("/").pop()).join(", ");n.push(`Temp file write-then-delete: ${I} \u2014 write inline logic or use tests/ instead`)}}let de=s.filter(E=>E.content.startsWith("EXIT")).length;de>=10?(e-=1,n.push(`Bash exit-error storm: ${de} tool results started with EXIT (repeated failing commands)`)):de>=5&&(e-=.5,n.push(`Repeated bash errors: ${de} tool results with non-zero exit code`));for(let E of t){if(E.role!=="assistant")continue;let M="";if(typeof E.content=="string"?M=E.content:Array.isArray(E.content)&&(M=E.content.filter(z=>z&&(z.type==="text"||typeof z=="string")).map(z=>typeof z=="string"?z:z.text||"").join("")),M.length<=5e3)continue;let W=M.split(/(?<=\. )/).filter(z=>z.trim().length>0);if(W.length<6)continue;let H=new Map;for(let z=0;z<=W.length-3;z++){let Q=W.slice(z,z+3).join("").trim();Q.length>30&&H.set(Q,(H.get(Q)||0)+1)}let ne=0,I="";for(let[z,Q]of H)Q>ne&&(ne=Q,I=z);if(ne<3)continue;let se=I.length*ne/M.length;if(se>=.4||ne>=10){e-=1.5,n.push(`llm output loop: assistant message repeated content detected (${ne}\xD7 same paragraph, ${Math.round(se*100)}% repeated)`);break}}{let E=new Set(["read_file","list_directory","search_files","glob","grep"]),M=t.some(H=>Array.isArray(H.tool_calls)?H.tool_calls.some(ne=>E.has(ne.function?.name)):Array.isArray(H.content)?H.content.some(ne=>ne.type==="tool_use"&&E.has(ne.name)):!1);t.some(H=>H.role==="assistant"&&typeof H.content=="string"&&(H.content.includes("## Steps")||H.content.includes("/plan approve")))&&!M&&(e-=2,n.push("plan written without reading any files \u2014 LLM invented data structures from training knowledge (hallucination risk)"))}let fe=s.filter(E=>E.content.startsWith("BLOCKED:"));if(fe.length>0){let E=Math.min(fe.length*.5,1.5);e-=E,n.push(`${fe.length} tool call${fe.length===1?"":"s"} blocked (agent attempted denied actions)`)}let ae=t.filter(E=>{let M=typeof E.content=="string"?E.content:"";return/\[SYSTEM WARNING\] Context wiped \d+×/.test(M)}).length;if(ae>0){let E=Math.min(ae*1,2);e-=E,n.push(`Super-nuclear context wipe fired ${ae}\xD7 (context collapse \u2014 task too large or read loops)`)}{let E=!1,M=!1,W=!1;for(let ne of o){if(ne.name!=="bash")continue;let I=(ne.input?.command||ne.input?.cmd||"").trim();!(/cat\s*>/.test(I)||/<</.test(I))&&/\bcat\s+\S/.test(I)&&(E=!0),/^\s*ls(\s|$)/.test(I)&&!/npm|yarn|pnpm|make|git\b/.test(I)&&(M=!0),/\bfind\s+\S/.test(I)&&!/git\b|npm\b|-exec\b/.test(I)&&(W=!0)}let H=[E,M,W].filter(Boolean).length;if(H>0){let ne=Math.min(H*.25,.75);e-=ne;let I=[];E&&I.push("cat (use read_file)"),M&&I.push("ls (use list_directory)"),W&&I.push("find (use glob)"),n.push(`bash used instead of dedicated tool: ${I.join(", ")}`)}}e=Math.max(0,Math.min(10,e)),e=Math.round(e*10)/10;let be=e>=9?"A":e>=8?"B":e>=7?"C":e>=6?"D":"F",te=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:be,issues:n,summary:te}}function Uw(t){try{let{loadSession:e}=Ct(),n=e(t);return n?Ud(n.messages||[]):null}catch{return null}}function Ww(t,e=null){let{score:n,grade:o,issues:s,summary:r}=t,i=e?.dim||"",a=e?.reset||"",l=e?.green||"",u=e?.yellow||"",d=e?.red||"",f=e?.cyan||"",m=e?.bold||"",h=n>=8?l:n>=6?u:d,p=`
|
|
459
459
|
${i} Session score: ${a}${m}${h}${n}/10 (${o})${a}`;if(r&&(p+=` ${i}${r}${a}`),s.length>0)for(let g of s)p+=`
|
|
460
460
|
${u}\u26A0${a} ${i}${g}${a}`;return p}function Bw(t,e={}){try{let n=Id.join(process.cwd(),".nex");Ps.existsSync(n)||Ps.mkdirSync(n,{recursive:!0});let o=Id.join(n,"benchmark-history.json"),s=[];if(Ps.existsSync(o))try{s=JSON.parse(Ps.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)),Ps.writeFileSync(o,JSON.stringify(s,null,2))}catch{}}Wd.exports={scoreMessages:Ud,scoreSession:Uw,formatScore:Ww,appendScoreHistory:Bw,_extractToolCalls:Ld,_extractToolResults:Dd,_getLastAssistantText:jd,_getLastNAssistantTexts:qd,_countDuplicateToolCalls:Fd}});var rn=G((rv,Xd)=>{var on=require("fs"),or=require("path"),Hw=require("os"),{atomicWrite:Gw,withFileLockSync:Bd}=Qt();function ca(){return or.join(process.cwd(),".nex","memory")}function Is(){return or.join(ca(),"memory.json")}function Kw(){return or.join(process.cwd(),"NEX.md")}function Hd(){return or.join(Hw.homedir(),".nex","NEX.md")}function la(){let t=ca();on.existsSync(t)||on.mkdirSync(t,{recursive:!0})}function rr(){let t=Is();if(!on.existsSync(t))return{};try{return JSON.parse(on.readFileSync(t,"utf-8"))}catch{return{}}}function Gd(t){la(),Gw(Is(),JSON.stringify(t,null,2))}function Yw(t,e){la(),Bd(Is(),()=>{let n=rr();n[t]={value:e,updatedAt:new Date().toISOString()},Gd(n)})}function zw(t){let e=rr();return e[t]?e[t].value:null}function Xw(t){return la(),Bd(Is(),()=>{let e=rr();return t in e?(delete e[t],Gd(e),!0):!1})}function Kd(){let t=rr();return Object.entries(t).map(([e,n])=>({key:e,value:n.value,updatedAt:n.updatedAt}))}function Yd(){let t=Hd();if(!on.existsSync(t))return"";try{return on.readFileSync(t,"utf-8").trim()}catch{return""}}function zd(){let t=Kw();if(!on.existsSync(t))return"";try{return on.readFileSync(t,"utf-8").trim()}catch{return""}}function Jw(){let t=[],e=Yd();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
461
461
|
${e}`);let n=zd();n&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
@@ -530,7 +530,7 @@ Bullet list of potential issues and mitigations.
|
|
|
530
530
|
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],r=e.replace(/^\s*[-*]\s/,""),i=`${s}${v.cyan}\u2022${v.reset} ${Sn(r)}`,a=En(i,n,s+" ");this._safeWrite(`${a}
|
|
531
531
|
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){let r=s[1],i=s[2],a=s[3],l=`${r}${v.cyan}${i}.${v.reset} ${Sn(a)}`,u=r+" ".repeat(i.length+2),d=En(l,n,u);this._safeWrite(`${d}
|
|
532
532
|
`);return}}let o=En(Sn(e),n);this._safeWrite(`${o}
|
|
533
|
-
`)}};gf.exports={renderMarkdown:T0,renderInline:Sn,stripHeadingMarkers:vn,highlightCode:ma,highlightJS:cf,highlightBash:lf,highlightJSON:uf,highlightPython:df,highlightGo:ff,highlightRust:pf,highlightCSS:mf,highlightHTML:hf,renderTable:R0,renderProgress:C0,wrapAnsi:En,StreamRenderer:pa}});var $a=G((dv,_f)=>{var{execSync:A0}=require("child_process"),ha=require("path"),js=require("fs"),ga=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function yf(){return ha.join(process.cwd(),".nex","hooks")}function O0(){return ha.join(process.cwd(),".nex","config.json")}function wf(){let t=O0();if(!js.existsSync(t))return{};try{return JSON.parse(js.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function lr(t){if(!ga.includes(t))return[];let e=[],n=yf(),o=ha.join(n,t);js.existsSync(o)&&e.push(o);let s=wf();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function bf(t,e={},n=3e4){try{return{success:!0,output:A0(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 N0(t,e={}){let n=lr(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=bf(r,o);if(s.push({command:r,...i}),!i.success&&t.startsWith("pre-"))break}return s}function M0(t){return lr(t).length>0}function P0(){let t=[];for(let e of ga){let n=lr(e);n.length>0&&t.push({event:e,commands:n})}return t}function I0(){let t=yf();return js.existsSync(t)||js.mkdirSync(t,{recursive:!0}),t}_f.exports={HOOK_EVENTS:ga,loadHookConfig:wf,getHooksForEvent:lr,executeHook:bf,runHooks:N0,hasHooks:M0,listHooks:P0,initHooksDir:I0}});var qs=G((mv,Nf)=>{"use strict";var{callWithRetry:xf,runSubAgent:L0,clearAllLocks:D0}=Ko(),{parseModelSpec:kf,getActiveProviderName:fv,getActiveModelId:pv}=Ae(),{MultiProgress:j0,C:
|
|
533
|
+
`)}};gf.exports={renderMarkdown:T0,renderInline:Sn,stripHeadingMarkers:vn,highlightCode:ma,highlightJS:cf,highlightBash:lf,highlightJSON:uf,highlightPython:df,highlightGo:ff,highlightRust:pf,highlightCSS:mf,highlightHTML:hf,renderTable:R0,renderProgress:C0,wrapAnsi:En,StreamRenderer:pa}});var $a=G((dv,_f)=>{var{execSync:A0}=require("child_process"),ha=require("path"),js=require("fs"),ga=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function yf(){return ha.join(process.cwd(),".nex","hooks")}function O0(){return ha.join(process.cwd(),".nex","config.json")}function wf(){let t=O0();if(!js.existsSync(t))return{};try{return JSON.parse(js.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function lr(t){if(!ga.includes(t))return[];let e=[],n=yf(),o=ha.join(n,t);js.existsSync(o)&&e.push(o);let s=wf();if(s[t]){let r=Array.isArray(s[t])?s[t]:[s[t]];e.push(...r)}return e}function bf(t,e={},n=3e4){try{return{success:!0,output:A0(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 N0(t,e={}){let n=lr(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=bf(r,o);if(s.push({command:r,...i}),!i.success&&t.startsWith("pre-"))break}return s}function M0(t){return lr(t).length>0}function P0(){let t=[];for(let e of ga){let n=lr(e);n.length>0&&t.push({event:e,commands:n})}return t}function I0(){let t=yf();return js.existsSync(t)||js.mkdirSync(t,{recursive:!0}),t}_f.exports={HOOK_EVENTS:ga,loadHookConfig:wf,getHooksForEvent:lr,executeHook:bf,runHooks:N0,hasHooks:M0,listHooks:P0,initHooksDir:I0}});var qs=G((mv,Nf)=>{"use strict";var{callWithRetry:xf,runSubAgent:L0,clearAllLocks:D0}=Ko(),{parseModelSpec:kf,getActiveProviderName:fv,getActiveModelId:pv}=Ae(),{MultiProgress:j0,C:ie}=Ce(),vf=3,ya=4,Sf="devstral-2:123b",Ef="kimi-k2.5",Tf=`You are a task decomposition engine. Given a complex user request, split it into independent, atomic sub-tasks.
|
|
534
534
|
|
|
535
535
|
RULES:
|
|
536
536
|
- Output ONLY a JSON array, no markdown fences, no explanation.
|
|
@@ -566,9 +566,9 @@ Result: ${d.result}
|
|
|
566
566
|
Tools: ${(d.toolsUsed||[]).join(", ")||"none"}`}).join(`
|
|
567
567
|
|
|
568
568
|
`),r=[{role:"system",content:Rf.replace("{prompt}",e).replace("{results}",o)},{role:"user",content:"Synthesize the sub-agent results above."}],i={};if(n){let d=kf(n);d.provider&&(i.provider=d.provider),d.model&&(i.model=d.model)}let l=(await xf(r,[],i)).content||"",u=wa(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 F0(t,e={}){let n=e.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL||Ef,o=e.workerModel||Sf,s=e.maxParallel||vf,r=e.maxSubTasks||ya,i=e.onProgress||(()=>{}),a={input:0,output:0};console.log(`
|
|
569
|
-
${
|
|
570
|
-
`),i("decomposing"),console.log(`${
|
|
571
|
-
`);let u=Cf(s),
|
|
569
|
+
${ie.bold}Orchestrator${ie.reset} ${ie.dim}model: ${n} | workers: ${o} | max parallel: ${s}${ie.reset}
|
|
570
|
+
`),i("decomposing"),console.log(`${ie.dim}Phase 1: Decomposing prompt into sub-tasks...${ie.reset}`);let l;try{l=await Af(t,n,{maxSubTasks:r})}catch(x){return console.log(`${ie.red}Decompose failed: ${x.message}${ie.reset}`),{results:[],synthesis:{summary:`Decompose failed: ${x.message}`,conflicts:[],commitMessage:"",filesChanged:[]},totalTokens:a}}if(l.length===0)return console.log(`${ie.yellow}No sub-tasks generated. Prompt may be too simple for orchestration.${ie.reset}`),{results:[],synthesis:{summary:"No sub-tasks generated.",conflicts:[],commitMessage:"",filesChanged:[]},totalTokens:a};console.log(`${ie.green}Decomposed into ${l.length} sub-tasks:${ie.reset}`);for(let x of l)console.log(` ${ie.dim}${x.id}:${ie.reset} ${x.task}`),x.scope.length>0&&console.log(` ${ie.dim}scope: ${x.scope.join(", ")}${ie.reset}`);console.log(""),i("executing"),console.log(`${ie.dim}Phase 2: Running ${l.length} sub-agents (max ${s} parallel)...${ie.reset}
|
|
571
|
+
`);let u=Date.now(),d=Cf(s),f=l.map((x,_)=>`Agent ${_+1} [${o}]: ${x.task.substring(0,40)}${x.task.length>40?"...":""}`),m=new j0(f);m.start();let h=`
|
|
572
572
|
You are a focused coding agent executing ONE specific sub-task.
|
|
573
573
|
Your scope is limited to the files listed in your task definition.
|
|
574
574
|
|
|
@@ -586,28 +586,28 @@ RULES:
|
|
|
586
586
|
- If your task says "add X to README" \u2014 add it, don't check if it exists first.
|
|
587
587
|
- Max 10 tool calls. If you need more, you are doing too much \u2014 narrow your scope.
|
|
588
588
|
- When done: stop calling tools and write a one-line summary of what you changed.
|
|
589
|
-
`,
|
|
589
|
+
`,p=l.map(async(x,_)=>{let b=await d();try{let A=await L0({task:x.task,context:x.scope.length>0?`Focus on files: ${x.scope.join(", ")}`:void 0,max_iterations:Math.min(x.estimatedCalls||10,15),model:o,_skipLog:!0,_systemPrompt:h},{onUpdate:()=>{}});return m.update(_,A.status==="failed"?"error":"done"),a.input+=A.tokensUsed?.input||0,a.output+=A.tokensUsed?.output||0,{...A,_scope:x.scope,_idx:_}}catch(A){return m.update(_,"error"),{task:x.task,status:"failed",result:`Error: ${A.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}}finally{b()}}),g;try{g=await Promise.all(p)}finally{m.stop(),D0()}console.log("");let y=Math.round((Date.now()-u)/1e3),w=y>=60?`${Math.floor(y/60)}m ${y%60}s`:`${y}s`;for(let x=0;x<g.length;x++){let _=g[x],A=_.status==="done"||_.status==="truncated"&&_.result&&!_.result.startsWith("Error")?`${ie.green}\u2713${ie.reset}`:`${ie.red}\u2717${ie.reset}`,O=_._scope&&_._scope.length>0?_._scope.map(D=>D.replace(/^.*\//,"")).join(", "):_.task.substring(0,35)+(_.task.length>35?"...":""),P=x===g.length-1;console.log(` ${A} Agent ${x+1} ${ie.dim}${O}${ie.reset}${P?` ${ie.dim}${w}${ie.reset}`:""}`)}console.log(""),i("synthesizing"),console.log(`${ie.dim}Phase 3: Synthesizing results...${ie.reset}`);let k;try{k=await Of(g,t,n)}catch(x){console.log(`${ie.yellow}Synthesize failed: ${x.message} \u2014 using raw results.${ie.reset}`),k={summary:g.map(_=>_.result).join(`
|
|
590
590
|
`),conflicts:[],commitMessage:"",filesChanged:[]}}if(console.log(`
|
|
591
|
-
${
|
|
592
|
-
`),{results:
|
|
591
|
+
${ie.bold}Summary:${ie.reset} ${k.summary}`),k.conflicts.length>0){console.log(`${ie.yellow}Conflicts:${ie.reset}`);for(let x of k.conflicts)console.log(` - ${x}`)}k.commitMessage&&console.log(`${ie.dim}Suggested commit: ${k.commitMessage}${ie.reset}`);let R=a.input===0&&a.output===0?"n/a (provider does not report token counts)":`${a.input} input + ${a.output} output`;return console.log(`${ie.dim}Tokens: ${R}${ie.reset}
|
|
592
|
+
`),{results:g,synthesis:k,totalTokens:a}}Nf.exports={runOrchestrated:F0,decompose:Af,synthesize:Of,detectComplexPrompt:q0,extractJSON:wa,createSemaphore:Cf,DECOMPOSE_PROMPT:Tf,SYNTHESIZE_PROMPT:Rf,DEFAULT_ORCHESTRATOR_MODEL:Ef,DEFAULT_WORKER_MODEL:Sf,DEFAULT_MAX_PARALLEL:vf,DEFAULT_MAX_SUBTASKS:ya}});var Se=G((bv,Jf)=>{var{C:$,Spinner:Qn,TaskProgress:U0,formatToolCall:W0,formatToolSummary:Ff,formatSectionHeader:ba,formatMilestone:B0,setActiveTaskProgress:hv}=Ce(),{debugLog:oe,warnLog:gv}=pi(),{MilestoneTracker:H0}=Ol(),{callStream:G0}=Ae(),{parseToolArgs:K0}=Fn(),{executeTool:Y0}=Et(),{gatherProjectContext:z0}=tr(),{fitToContext:X0,forceCompress:Lt,getUsage:At,estimateTokens:J0}=Qe(),{autoSave:V0,flushAutoSave:Q0}=Ct(),{scoreMessages:Z0,formatScore:eb,appendScoreHistory:tb}=sr();function Ue(t){V0(t),Q0()}function Mf(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=Z0(t);if(!n)return;console.log(eb(n,$));try{let{_getSessionsDir:o}=Ct(),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}=Fn(),s=On();tb(n.score,{version:s.version,model:o?o():null,sessionName:"_autosave",issues:n.issues})}catch{}}catch{}}var{getMemoryContext:nb}=rn(),{getDeploymentContextBlock:sb}=sa(),{checkPermission:ob,setPermission:rb,savePermissions:ib}=Ds(),{confirm:Uf,setAllowAlwaysHandler:ab,getAutoConfirm:cb}=Xe(),{isPlanMode:Hs,getPlanModePrompt:lb,PLAN_MODE_ALLOWED_TOOLS:Wf,setPlanContent:ub,extractStepsFromText:db,createPlan:fb,getActivePlan:$v,startExecution:yv,advancePlanStep:pb,getPlanStepInfo:mb}=It(),{StreamRenderer:hb}=$f(),{runHooks:Pf}=$a(),{routeMCPCall:gb,getMCPToolDefinitions:$b}=Ro(),{getSkillInstructions:yb,getSkillToolDefinitions:wb,routeSkillCall:bb}=tn(),{trackUsage:_b}=qn(),{validateToolArgs:xb}=Ei(),{filterToolsForModel:If,getModelTier:kb,PROVIDER_DEFAULT_TIER:wv}=Fo(),{getConfiguredProviders:vb,getActiveProviderName:Fs,getActiveModelId:Zn,setActiveModel:Lf,MODEL_EQUIVALENTS:$r}=Ae(),Pa=require("fs"),Ia=require("path"),Sb=(()=>{let t=parseInt(process.env.NEX_MILESTONE_STEPS??"5",10);return Number.isFinite(t)&&t>=0?t:5})();function Eb(t){let e=B0(t.phaseName,t.stepCount,t.toolCounts,t.elapsed,t.filesRead,t.filesModified);process.stdout.write(`${e}
|
|
593
593
|
`)}var Df=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function Tb(t){let e=[],n;for(Df.lastIndex=0;(n=Df.exec(t))!==null;){let o=n[1].trim(),s=o.startsWith("~")?o.replace("~",process.env.HOME||""):Ia.resolve(o);Pa.existsSync(s)&&e.push({raw:o,abs:s})}return e}function Rb(t){let e=Pa.readFileSync(t),n=Ia.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 Bf(t){let e=Tb(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}=Rb(o.abs);n.push({type:"image",media_type:r,data:s})}catch{}return n.length>1?n:t}function Cb(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=`
|
|
594
594
|
|
|
595
595
|
[SYSTEM: Output repetition detected \u2014 response truncated (${s}\xD7 repeated paragraph)]`,a;if(t.length>8e3)a=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}a=u>0?t.slice(0,u)+i:t.slice(0,3e3)+i}return{text:a,truncated:!0,repeatCount:s}}function Ta(t,e=5){if(!t||t.length<40)return{text:t,truncated:!1,repeatCount:0};let n=t.split(`
|
|
596
596
|
`),o=new Map;for(let f of n){let m=f.trim();m.length>=20&&o.set(m,(o.get(m)||0)+1)}let s=0,r="";for(let[f,m]of o)m>s&&(s=m,r=f);if(s<=e)return{text:t,truncated:!1,repeatCount:s};let i=`
|
|
597
597
|
|
|
598
|
-
\u26A0 [Response truncated: repeated paragraph detected (${s}\xD7)]`,a=0,l=-1,u=0;for(;a<e;){let f=t.indexOf(r,u);if(f===-1)break;a++,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 _a=null,xa=null,ka=null;function Je(){if(_a===null){let{TOOL_DEFINITIONS:t}=Et();_a=t}return xa===null&&(xa=wb()),ka===null&&(ka=$b()),[..._a,...xa,...ka]}var Ra=50;function Ab(t){Number.isFinite(t)&&t>0&&(Ra=t)}var dr=()=>null;function Ob(t){dr=t}var Us=null,Ca=null,es=null,fr=new Map,Nb=1e4,Mb=6e3,Pb=/\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 Ib(t){return!t||typeof t!="string"?t:t.replace(Pb,(e,n)=>`${n}=***REDACTED***`)}var Lb=7e3,Db=4e3;function jb(t,e=null){let n=Ib(t),o=J0(n),s=e==="read_file"?Lb:Nb,r=e==="read_file"?Db:Mb;if(o>s)try{let{compressToolResult:i}=Qe();return i(n,r)}catch{return n}return n}function Hf(t){try{let{getActiveModel:e}=Ae(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(fr.has(o))return fr.get(o);let s=If(t);return fr.set(o,s),s}catch{return If(t)}}function qb(){fr.clear()}async function Gf(){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(r=>t.stat(r).then(i=>`${r}:${i.mtimeMs}`)))).filter(r=>r.status==="fulfilled").map(r=>r.value);try{let{getMemoryContextHash:r}=rn(),i=r();i&&s.push(`memory:${i}`)}catch{}try{let r=e.join(process.cwd(),".nex","brain");if(Pa.existsSync(r)){let i=await t.stat(r);s.push(`brain:${i.mtimeMs}`)}}catch{}return s.join("|")}catch{return`fallback:${Date.now()}`}}function Aa(){Us=null,Ca=null,es=null}var Fb=new Set(["spawn_agents"]),va=5,Sa=3,ur=2,Ub=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),jf=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10),Wb=process.env.NEX_STALE_AUTO_SWITCH!=="0";function Bb(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{}}ab(t=>{rb(t,"allow"),ib(),console.log(`${
|
|
598
|
+
\u26A0 [Response truncated: repeated paragraph detected (${s}\xD7)]`,a=0,l=-1,u=0;for(;a<e;){let f=t.indexOf(r,u);if(f===-1)break;a++,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 _a=null,xa=null,ka=null;function Je(){if(_a===null){let{TOOL_DEFINITIONS:t}=Et();_a=t}return xa===null&&(xa=wb()),ka===null&&(ka=$b()),[..._a,...xa,...ka]}var Ra=50;function Ab(t){Number.isFinite(t)&&t>0&&(Ra=t)}var dr=()=>null;function Ob(t){dr=t}var Us=null,Ca=null,es=null,fr=new Map,Nb=1e4,Mb=6e3,Pb=/\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 Ib(t){return!t||typeof t!="string"?t:t.replace(Pb,(e,n)=>`${n}=***REDACTED***`)}var Lb=7e3,Db=4e3;function jb(t,e=null){let n=Ib(t),o=J0(n),s=e==="read_file"?Lb:Nb,r=e==="read_file"?Db:Mb;if(o>s)try{let{compressToolResult:i}=Qe();return i(n,r)}catch{return n}return n}function Hf(t){try{let{getActiveModel:e}=Ae(),n=e(),o=n?`${n.provider}:${n.id}`:"default";if(fr.has(o))return fr.get(o);let s=If(t);return fr.set(o,s),s}catch{return If(t)}}function qb(){fr.clear()}async function Gf(){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(r=>t.stat(r).then(i=>`${r}:${i.mtimeMs}`)))).filter(r=>r.status==="fulfilled").map(r=>r.value);try{let{getMemoryContextHash:r}=rn(),i=r();i&&s.push(`memory:${i}`)}catch{}try{let r=e.join(process.cwd(),".nex","brain");if(Pa.existsSync(r)){let i=await t.stat(r);s.push(`brain:${i.mtimeMs}`)}}catch{}return s.join("|")}catch{return`fallback:${Date.now()}`}}function Aa(){Us=null,Ca=null,es=null}var Fb=new Set(["spawn_agents"]),va=5,Sa=3,ur=2,Ub=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),jf=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10),Wb=process.env.NEX_STALE_AUTO_SWITCH!=="0";function Bb(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{}}ab(t=>{rb(t,"allow"),ib(),console.log(`${$.green} \u2713 ${t}: always allow${$.reset}`)});async function Hb(t){let e=t.function.name,n=K0(t.function.arguments),o=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!n){let l=Je().find(d=>d.function.name===e),u=l?JSON.stringify(l.function.parameters,null,2):"unknown";return oe(`${$.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.
|
|
599
599
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
600
600
|
|
|
601
601
|
Expected JSON schema for "${e}":
|
|
602
602
|
${u}
|
|
603
603
|
|
|
604
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}let s=xb(e,n);if(!s.valid)return oe(`${
|
|
605
|
-
`)[0]}${
|
|
604
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:o}}}let s=xb(e,n);if(!s.valid)return oe(`${$.yellow} \u26A0 ${e}: ${s.error.split(`
|
|
605
|
+
`)[0]}${$.reset}`),{callId:o,fnName:e,args:n,canExecute:!1,errorResult:{role:"tool",content:s.error,tool_call_id:o}};let r=s.corrected||n;if(s.corrected){let a=Object.keys(n),l=Object.keys(s.corrected),u=a.filter(d=>!l.includes(d));u.length&&console.log(`${$.dim} \u2713 ${e}: corrected args (${u.join(", ")})${$.reset}`)}if(Hs()&&!Wf.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=ob(e);if(i==="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(i==="ask"){let a=` Allow ${e}?`;return e==="bash"&&r.command&&(a=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await Uf(a,{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 Gb(t,e,n={}){let o=await bb(t,e);if(o!==null)return o;let s=await gb(t,e);return s!==null?s:Y0(t,e,n)}function Kb(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 Ea(t,e=!1){e||console.log(W0(t.fnName,t.args));let n=Pf("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}`);Dt?.onToolStart&&Dt.onToolStart(t.fnName,t.args);let o=await Gb(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),s=String(o??""),r=s.length>5e4?s.substring(0,5e4)+`
|
|
606
606
|
...(truncated ${s.length-5e4} chars)`:s,i=r.split(`
|
|
607
|
-
`)[0],a=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),l=Ff(t.fnName,t.args,r,a);e||console.log(l),Dt?.onToolEnd&&Dt.onToolEnd(t.fnName,l,!a);let u=Pf("post-tool",{tool_name:t.fnName});if(!e&&u.length>0)for(let h of u)h.success?console.log(`${
|
|
607
|
+
`)[0],a=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),l=Ff(t.fnName,t.args,r,a);e||console.log(l),Dt?.onToolEnd&&Dt.onToolEnd(t.fnName,l,!a);let u=Pf("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=jb(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+=`
|
|
608
608
|
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+=`
|
|
609
|
-
HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`)}return{msg:{role:"tool",content:f,tool_call_id:t.callId},summary:l}}async function Yb(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=Kb(d.fnName,d.args);u=`\u25CF ${d.fnName}${f?`(${f})`:""}`}else{let d=l.map(f=>f.fnName).join(", ");u=`\u25CF ${l.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}i=new Qn(u),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await Ea(t[l],e);o[l]=u,s.push(d)}else{let l=r.map(d=>Ea(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 a(),o[l]=u.errorResult,s.push(Ff(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(Fb.has(u.fnName)){await a(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await Ea(u,e);o[l]=d,s.push(f)}else r.push(l)}if(await a(),i&&i.stop(),e&&s.length>0&&!n.skipSummaries)for(let l of s)console.log(l);return{results:o,summaries:s}}var X=[],qf=300,Kf=new Map,Yf=new Map,Oa=new Map,Na=new Map,Ws=new Map,zf=new Map,ts=new Map,ns=new Map,Ot=0,Bs=0,pr=0,Ma="",mr=0,ss=!1,hr=0;function Vn(t,e){t===Ma?(mr++,pi().DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${mr})${
|
|
610
|
-
`)):(Ma=t,mr=1,oe(`${e} \u26A0 ${t}${
|
|
609
|
+
HINT: use list_directory instead of bash ls \u2014 it is the preferred tool for listing directory contents.`)}return{msg:{role:"tool",content:f,tool_call_id:t.callId},summary:l}}async function Yb(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=Kb(d.fnName,d.args);u=`\u25CF ${d.fnName}${f?`(${f})`:""}`}else{let d=l.map(f=>f.fnName).join(", ");u=`\u25CF ${l.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}i=new Qn(u),i.start()}}async function a(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await Ea(t[l],e);o[l]=u,s.push(d)}else{let l=r.map(d=>Ea(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 a(),o[l]=u.errorResult,s.push(Ff(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(Fb.has(u.fnName)){await a(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await Ea(u,e);o[l]=d,s.push(f)}else r.push(l)}if(await a(),i&&i.stop(),e&&s.length>0&&!n.skipSummaries)for(let l of s)console.log(l);return{results:o,summaries:s}}var X=[],qf=300,Kf=new Map,Yf=new Map,Oa=new Map,Na=new Map,Ws=new Map,zf=new Map,ts=new Map,ns=new Map,Ot=0,Bs=0,pr=0,Ma="",mr=0,ss=!1,hr=0;function Vn(t,e){t===Ma?(mr++,pi().DEBUG&&process.stdout.write(`\x1B[1A\x1B[2K${e} \u26A0 ${t} (\xD7${mr})${$.reset}
|
|
610
|
+
`)):(Ma=t,mr=1,oe(`${e} \u26A0 ${t}${$.reset}`))}var gr=[];function zb(t){gr.push(t.trim())}function Xb(){return gr.length===0?null:gr.splice(0,gr.length).join(`
|
|
611
611
|
`)}function Jb(){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)
|
|
612
612
|
`];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(`
|
|
613
613
|
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(`
|
|
@@ -910,42 +910,42 @@ You have access to a persistent knowledge base in .nex/brain/.
|
|
|
910
910
|
`,Ca=t,Us}function Qb(){X=[],Kf.clear(),Yf.clear(),Oa.clear(),Na.clear(),Ws.clear(),zf.clear(),ts.clear(),ns.clear(),Ot=0,Bs=0,pr=0,ss=!1,hr=0,Ma="",mr=0}function Zb(){X.length>qf&&X.splice(0,X.length-qf)}function e_(){return X.length}function t_(){return X}function n_(t){X=t}async function s_(){let{execFile:t}=require("child_process"),e=require("fs"),n=process.cwd(),o=(f,m)=>new Promise(h=>{t(f,m,{cwd:n,timeout:3e3},(p,g)=>{h(p?"":(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(`
|
|
911
911
|
`):[]).filter(f=>{let m=f.split(".").pop();return r.has(m)});if(i.length<3)return null;let a={};for(let f of i){let m=f.split(".").pop();a[m]=(a[m]||0)+1}let u=` \u{1F4C1} ${Object.entries(a).sort((f,m)=>m[1]-f[1]).slice(0,4).map(([f,m])=>`${m} .${f}`).join(" \xB7 ")}`,d=Ia.join(n,"package.json");if(e.existsSync(d))try{let f=JSON.parse(e.readFileSync(d,"utf-8")),m=Object.keys({...f.dependencies||{},...f.devDependencies||{}});if(m.length>0){let h=m.slice(0,5).join(" \xB7 "),p=m.length>5?` +${m.length-5}`:"";u+=`
|
|
912
912
|
\u{1F4E6} ${h}${p}`}}catch{}return u}function o_(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 We(t,e,n,o,s,{suppressHint:r=!1}={}){if(t<1)return;let i=[...e.values()].reduce((u,d)=>u+d,0),a=`\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),a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}if(n.size>0&&(a+=` \xB7 ${n.size} ${n.size===1?"file":"files"} modified`),a+=" \u2500\u2500",console.log(`
|
|
913
|
-
${
|
|
914
|
-
`),m==="")return a({action:"quit"});let p=i.find(g=>g.key===h);!p||p.key==="q"||!p.model&&p.key!=="r"?a({action:"quit"}):p.key==="r"?a({action:"retry"}):a({action:"switch",model:p.model,provider:t})};l.on("data",f)})}var Dt=null;async function i_(t,e=null,n={}){Dt=e;let o=Bf(t);X.push({role:"user",content:o}),Zb();let s=n.autoOrchestrate||process.env.NEX_AUTO_ORCHESTRATE==="true",r=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:qe,runOrchestrated:Oe}=qs(),Fe=qe(typeof t=="string"?t:"");if(s&&Fe.isComplex&&Fe.estimatedGoals>=r)return console.log(`${
|
|
913
|
+
${$.dim} ${a}${$.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`;o_(u)}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 r_(){if(!process.stdout.isTTY)return{action:"quit"};let t=Fs(),e=Zn(),n=$r.fast?.[t],o=$r.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 a of i)console.log(` ${$.cyan}[${a.key}]${$.reset} ${a.label}`);return process.stdout.write(` ${$.yellow}> ${$.reset}`),new Promise(a=>{let l=process.stdin,u=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let d=!1,f=m=>{if(d)return;d=!0,l.removeListener("data",f),l.setRawMode(u||!1),l.pause();let h=m.toLowerCase().trim();if(process.stdout.write(`${h}
|
|
914
|
+
`),m==="")return a({action:"quit"});let p=i.find(g=>g.key===h);!p||p.key==="q"||!p.model&&p.key!=="r"?a({action:"quit"}):p.key==="r"?a({action:"retry"}):a({action:"switch",model:p.model,provider:t})};l.on("data",f)})}var Dt=null;async function i_(t,e=null,n={}){Dt=e;let o=Bf(t);X.push({role:"user",content:o}),Zb();let s=n.autoOrchestrate||process.env.NEX_AUTO_ORCHESTRATE==="true",r=parseInt(process.env.NEX_ORCHESTRATE_THRESHOLD||"3",10);try{let{detectComplexPrompt:qe,runOrchestrated:Oe}=qs(),Fe=qe(typeof t=="string"?t:"");if(s&&Fe.isComplex&&Fe.estimatedGoals>=r)return console.log(`${$.yellow}\u26A1 Auto-orchestrate: ${Fe.estimatedGoals} goals \u2192 parallel agents${$.reset}`),await Oe(t,{orchestratorModel:n.orchestratorModel||process.env.NEX_ORCHESTRATOR_MODEL,workerModel:n.model});Fe.isComplex&&console.log(`${$.dim}Hint: ~${Fe.estimatedGoals} goals. Try --auto-orchestrate for parallel execution.${$.reset}`)}catch{}let{setOnChange:i}=Wo(),a=null,l=0;i((qe,Oe)=>{qe==="create"?(a&&a.stop(),a=new U0(Oe.name,Oe.tasks),a.setStats({tokens:l}),a.start()):qe==="update"&&a?a.updateTask(Oe.id,Oe.status):qe==="clear"&&a&&(a.stop(),a=null)});let u=await Xf(),d=u;try{let{getBrainContext:qe}=Ts(),Oe=await qe(t);Oe&&(d=u+`
|
|
915
915
|
`+Oe+`
|
|
916
|
-
`)}catch(qe){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",qe.message)}let f=[{role:"system",content:d},...X],m=new Qn("Thinking...");m.start();let p=X.length===1?s_().catch(()=>null):Promise.resolve(null),g=Je(),[{messages:w,
|
|
917
|
-
`+me.map(
|
|
918
|
-
`));let Ie=X.filter(
|
|
916
|
+
`)}catch(qe){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",qe.message)}let f=[{role:"system",content:d},...X],m=new Qn("Thinking...");m.start();let p=X.length===1?s_().catch(()=>null):Promise.resolve(null),g=Je(),[{messages:y,compressed:w,compacted:k,tokensRemoved:R},x]=await Promise.all([X0(f,g),p]),_=At(f,g);if(m.stop(),x&&console.log(`${$.dim}${x}${$.reset}`),k)console.log(`${$.dim} [context compacted \u2014 summary (~${R} tokens freed)]${$.reset}`);else if(w){let qe=_.limit>0?Math.round(R/_.limit*100):0;oe(`${$.dim} [context compressed \u2014 ~${R} tokens freed (${qe}%)]${$.reset}`)}_.percentage>85&&oe(`${$.yellow} \u26A0 Context ${Math.round(_.percentage)}% used (${Math.round(100-_.percentage)}% remaining) \u2014 consider /clear or /save + start fresh${$.reset}`);let b=y;if(At(b,Je()).percentage>=65){let{messages:Oe,tokensRemoved:Fe}=Lt(b,Je());Fe>0&&(b=Oe,console.log(`${$.dim} [pre-flight compress \u2014 ${Fe} tokens freed, now ${Math.round(At(b,Je()).percentage)}% used]${$.reset}`))}let A=0,O=0,P=0,D=0,Me=0,xe=9,de=0,fe=(()=>{let qe=X.find(Oe=>Oe.role==="user");return typeof qe?.content=="string"?qe.content:""})(),ae=/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).{0,30}jarvis/i.test(fe),be=0,te=0,E=new Map,M=new Set,W=new Set,H=Date.now(),ne=new H0(Sb),I=zf,F=2,se=4,z=Kf,Q=5,pe=8,ue=Yf,$e=4,ye=7,je=Oa,Ge=3,zt=4,An=Na,Mr=2,pm=3,cn=0,mm=6,hm=10,ln=0,uc=5,un=0,gm=2,$m=3,Pr=0,Ir=8,ym=12,dt,so=Ra,Lr=0,dc=3,Dr=!1;e:for(;;){for(Dr=!1,dt=0;dt<so&&!dr()?.aborted;dt++){{let T=Je(),S=At(b,T),J=te===0?65:78;if(S.percentage>=J){let{messages:U,tokensRemoved:V}=Lt(b,T,te===0);V>0&&(b=U,V>50&&console.log(`${$.dim} [auto-compressed \u2014 ~${V} tokens freed, now ${Math.round(At(b,T).percentage)}%]${$.reset}`))}}let Oe=!0;te>0&&pb();let Fe=null;if(a&&a.isActive())a._paused&&a.resume();else if(!a){let T,S=mb();if(S&&S.total>1){let J=S.description.length>40?S.description.slice(0,37)+"\u2026":S.description;T=`Plan step ${S.current}/${S.total}: ${J}`}else T=te>0?`Thinking... (step ${te+1})`:"Thinking...";Fe=new Qn(T),Fe.start()}let jr=!0,Xt="",qr=!1,ft=new hb,jt,Fr=Date.now(),oo=!1,Ur=new AbortController,fc=setInterval(()=>{let T=Date.now()-Fr;if(T>=jf)ft._clearCursorLine(),oe(`${$.yellow} \u26A0 Stream stale for ${Math.round(T/1e3)}s \u2014 aborting and retrying${$.reset}`),Ur.abort();else if(T>=Ub&&!oo){oo=!0,ft._clearCursorLine();let S=$r.fast?.[Fs()],J=P>0?` (retry ${P+1}/${ur})`:"",U=Math.round((jf-T)/1e3);oe(`${$.yellow} \u26A0 No tokens received for ${Math.round(T/1e3)}s \u2014 waiting...${J}${$.reset}`),S&&S!==Zn()?console.log(`${$.dim} \u{1F4A1} Will auto-switch to ${S} in ~${U}s if no tokens arrive${$.reset}`):console.log(`${$.dim} \u{1F4A1} Ctrl+C to abort \xB7 auto-abort in ~${U}s${$.reset}`)}},5e3),bt="",qt=null;try{let T=Hf(Je()),S=Hs()?T.filter(V=>Wf.has(V.function.name)):T,J=dr(),U=new AbortController;J&&J.addEventListener("abort",()=>U.abort(),{once:!0}),Ur.signal.addEventListener("abort",()=>U.abort(),{once:!0}),jt=await G0(b,S,{signal:U.signal,onThinkingToken:()=>{Fr=Date.now(),oo=!1,Dt?.onThinkingToken&&Dt.onThinkingToken()},onToken:V=>{if(Fr=Date.now(),oo=!1,Dt?.onToken){Dt.onToken(V),Xt+=V;return}if(Xt+=V,!qr&&Xt.length>400&&Xt.length%250<V.length+1){let re=Ta(Xt,3);re.truncated&&(qr=!0,ft._clearCursorLine?.(),oe(`${$.yellow} \u26A0 LLM stream loop detected (${re.repeatCount}\xD7 repeated) \u2014 suppressing display${$.reset}`))}qr||(bt+=V,process.stdout.isTTY?qt||(qt=setTimeout(()=>{bt&&ft&&ft.push(bt),bt="",qt=null},50)):(ft.push(bt),bt=""),jr&&(a&&!a._paused?a.pause():Fe&&Fe.stop(),Oe||(Oe=!0),ft.startCursor(),jr=!1))}})}catch(T){if(clearInterval(fc),qt&&(clearTimeout(qt),qt=null),bt&&ft&&(ft.push(bt),bt=""),a&&!a._paused&&a.pause(),Fe&&Fe.stop(),ft.stopCursor(),Ur.signal.aborted&&!dr()?.aborted){if(P++,P>ur){if(D<1){D++,Vn("Stale retries exhausted \u2014 last-resort force-compress...",$.yellow);let L=Je(),{messages:B,tokensRemoved:Z}=Lt(b,L);b=B,Z>50&&oe(`${$.dim} [force-compressed \u2014 ~${Z} tokens freed]${$.reset}`),P=0,dt--;continue}a&&(a.stop(),a=null);let re=await r_();if(re.action==="quit"){i(null),We(te,E,M,W,H),Ue(X);break}re.action==="switch"&&(Lf(`${re.provider}:${re.model}`),console.log(`${$.green} \u2713 Switched to ${re.provider}:${re.model}${$.reset}`)),P=0,dt--;continue}let U=P===1?3e3:5e3;if(P>=1&&de<1){de++,Vn(`Stale retry ${P}/${ur} \u2014 force-compressing before retry...`,$.yellow);let re=Je(),{messages:L,tokensRemoved:B}=Lt(b,re,!0);if(b=L,B>0&&B>50&&oe(`${$.dim} [force-compressed \u2014 ~${B} tokens freed]${$.reset}`),Wb){let Z=$r.fast?.[Fs()];Z&&Z!==Zn()&&(Lf(`${Fs()}:${Z}`),console.log(`${$.cyan} \u26A1 Auto-switched to ${Z} to avoid further stale timeouts${$.reset}`),console.log(`${$.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${$.reset}`))}}else oe(`${$.yellow} \u26A0 Stale retry ${P}/${ur} \u2014 retrying in ${U/1e3}s...${$.reset}`);let V=new Qn(`Waiting ${U/1e3}s before retry...`);V.start(),await new Promise(re=>setTimeout(re,U)),V.stop(),dt--;continue}if(T.name==="AbortError"||T.name==="CanceledError"||T.message?.includes("canceled")||T.message?.includes("aborted")){a&&(a.stop(),a=null),i(null),We(te,E,M,W,H),Ue(X);break}let S=T.message;if(T.code==="ECONNREFUSED"||T.message.includes("ECONNREFUSED"))S="Connection refused \u2014 please check your internet connection or API endpoint";else if(T.code==="ENOTFOUND"||T.message.includes("ENOTFOUND"))S="Network error \u2014 could not reach the API server. Please check your connection";else if(T.code==="ETIMEDOUT"||T.message.includes("timeout"))S="Request timed out \u2014 the API server took too long to respond. Please try again";else if(T.message.includes("401")||T.message.includes("Unauthorized"))S="Authentication failed \u2014 please check your API key in the .env file";else if(T.message.includes("403")||T.message.includes("Forbidden"))S="Access denied \u2014 your API key may not have permission for this model";else if(T.message.includes("404")){S=`Model not found (404): ${Zn?Zn():"unknown"} \u2014 check your .env MODEL setting or run /models to list available models`,console.log(`${$.red} \u2717 ${S}${$.reset}`),a&&(a.stop(),a=null),i(null),We(te,E,M,W,H),Ue(X);break}else if(T.message.includes("400")){if(D<3&&Me<xe){D++,Me++;let U=te===0&&D===1,V=U||D===3||de>0;if(U){D=3;let Z=T.message.replace(/^API Error(\s*\[HTTP \d+\])?:\s*/i,"").slice(0,150);Vn(`Bad request (400) \u2014 ${Z||"system prompt too large"}, compressing...`,$.yellow)}else Vn(V?`Bad request (400) \u2014 nuclear compression (attempt ${D}/3, dropping history)...`:`Bad request (400) \u2014 force-compressing and retrying... (attempt ${D}/3)`,$.yellow);let re=Je(),{messages:L,tokensRemoved:B}=Lt(b,re,V);b=L,B>50&&oe(`${$.dim} [force-compressed \u2014 ~${B} tokens freed]${$.reset}`),dt--;continue}{let U=b.find(ce=>ce.role==="system"),V=b.find(ce=>ce.role==="user"&&!String(ce.content).startsWith("[SYSTEM")&&!String(ce.content).startsWith("BLOCKED:")),re=[U,V].filter(Boolean),{getUsage:L}=Qe(),B=Qe().estimateMessagesTokens(re),Z=Qe().estimateMessagesTokens(b);if(B<Z){let ce=[],me=X.filter(le=>le.role==="assistant"&&typeof le.content=="string"&&le.content.trim().length>30).slice(-3).map(le=>le.content.trim().slice(0,120).replace(/\n+/g," "));me.length>0&&ce.push(`Key findings:
|
|
917
|
+
`+me.map(le=>`- ${le}`).join(`
|
|
918
|
+
`));let Ie=X.filter(le=>le.role==="tool"&&typeof le.content=="string"&&!le.content.startsWith("BLOCKED:")&&le.content.trim().length>10).slice(-3).map(le=>le.content.trim().split(`
|
|
919
919
|
`).slice(0,3).join(`
|
|
920
|
-
`).slice(0,200));if(Ie.length>0&&
|
|
921
|
-
`+Ie.map(
|
|
922
|
-
`)),M.size>0){let
|
|
923
|
-
${
|
|
920
|
+
`).slice(0,200));if(Ie.length>0&&ce.push(`Tool results summary:
|
|
921
|
+
`+Ie.map(le=>`- ${le}`).join(`
|
|
922
|
+
`)),M.size>0){let le=[...M].map(pt=>pt.split("/").slice(-2).join("/")).join(", ");ce.unshift(`Already modified: ${le} \u2014 use edit_file to add missing pieces only, DO NOT use write_file on these files.`)}if(ce.length>0){let le={role:"user",content:`[SYSTEM: Findings from investigation before context wipe]
|
|
923
|
+
${ce.join(`
|
|
924
924
|
`)}
|
|
925
|
-
Continue implementing the fixes based on these findings.`};re.push(
|
|
926
|
-
Files modified so far: ${[...M].map(pt=>pt.split("/").slice(-1)[0]).join(", ")}`:"";oe(`${
|
|
925
|
+
Continue implementing the fixes based on these findings.`};re.push(le)}if(Bs>=3){let le=M.size>0?`
|
|
926
|
+
Files modified so far: ${[...M].map(pt=>pt.split("/").slice(-1)[0]).join(", ")}`:"";oe(`${$.red} \u2717 Super-nuclear limit reached (3\xD7) \u2014 aborting to prevent runaway context loop${$.reset}`),console.log(`${$.yellow} \u{1F4A1} Task may exceed model context. Try /clear and break it into smaller steps.${le?$.dim+le:""}${$.reset}`),a&&(a.stop(),a=null),i(null),We(te,E,M,W,H,{suppressHint:!0}),Ue(X);break}if(b=re,Bs++,Ot=0,be=0,Na.clear(),ts.clear(),ns.clear(),Oa.clear(),Vn(`Super-nuclear compression \u2014 dropped all history, keeping original task only (${Z-B} tokens freed)`,$.yellow),Bs>=1){let le={role:"user",content:`[SYSTEM WARNING] Context wiped ${Bs}\xD7. SKIP investigation \u2014 implement directly using findings above. Max 5 tool calls total, then finish.
|
|
927
927
|
|
|
928
|
-
CRITICAL: If you must re-read a file, use line_start/line_end to read ONLY the section you need (e.g. last 50 lines). Never read a full large file again \u2014 that is what caused the context overflow.`};X.push(
|
|
928
|
+
CRITICAL: If you must re-read a file, use line_start/line_end to read ONLY the section you need (e.g. last 50 lines). Never read a full large file again \u2014 that is what caused the context overflow.`};X.push(le),b.push(le)}D=0,dt--;continue}}S="Context too large to compress \u2014 use /clear to start fresh"}else T.message.includes("500")||T.message.includes("502")||T.message.includes("503")||T.message.includes("504")?S="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(T.message.includes("fetch failed")||T.message.includes("fetch"))&&(S="Network request failed \u2014 please check your internet connection");if(console.log(`${$.red} \u2717 ${S}${$.reset}`),T.message.includes("429")){if(A++,A>va){console.log(`${$.red} Rate limit: max retries (${va}) exceeded. Try again later or use /budget to check your limits.${$.reset}`),a&&(a.stop(),a=null),i(null),We(te,E,M,W,H),Ue(X);break}let U=Math.min(1e4*Math.pow(2,A-1),12e4),V=new Qn(`Rate limit \u2014 waiting ${Math.round(U/1e3)}s (retry ${A}/${va})`);V.start(),await new Promise(re=>setTimeout(re,U)),V.stop();continue}if(T.message.includes("socket disconnected")||T.message.includes("TLS")||T.message.includes("ECONNRESET")||T.message.includes("ECONNABORTED")||T.message.includes("ETIMEDOUT")||T.code==="ECONNRESET"||T.code==="ECONNABORTED"){if(O++,O>Sa){console.log(`${$.red} Network error: max retries (${Sa}) exceeded. Check your connection and try again.${$.reset}`),a&&(a.stop(),a=null),i(null),We(te,E,M,W,H),Ue(X);break}let U=Math.min(2e3*Math.pow(2,O-1),3e4),V=new Qn(`Network error \u2014 retrying in ${Math.round(U/1e3)}s (${O}/${Sa})`);V.start(),await new Promise(re=>setTimeout(re,U)),V.stop(),dt--;continue}a&&(a.stop(),a=null),i(null),We(te,E,M,W,H),Ue(X);break}clearInterval(fc),A=0,O=0,jr&&(a&&!a._paused&&a.pause(),Fe&&Fe.stop()),qt&&(clearTimeout(qt),qt=null),bt&&ft&&(ft.push(bt),bt=""),Xt&&ft.flush(),O=0,P=0,jt&&jt.usage&&(_b(Fs(),Zn(),jt.usage.prompt_tokens||0,jt.usage.completion_tokens||0),l+=(jt.usage.prompt_tokens||0)+(jt.usage.completion_tokens||0),a&&a.setStats({tokens:l}));let{content:pc,tool_calls:dn}=jt,ro=Ta(pc||""),mc=ro.truncated?ro.text:pc;ro.truncated&&oe(`${$.yellow} \u26A0 LLM output loop detected (${ro.repeatCount}\xD7 repeated paragraph) \u2014 response truncated${$.reset}`);let io=Cb(mc||""),ao=io.truncated?io.text:mc;io.truncated&&oe(`${$.yellow} \u26A0 LLM output loop detected (${io.repeatCount}\xD7 repeated window) \u2014 response truncated${$.reset}`);let Wr={role:"assistant",content:ao||""};if(dn&&dn.length>0&&(Wr.tool_calls=dn),X.push(Wr),b.push(Wr),!dn||dn.length===0){let T=(ao||"").trim().length>0||Xt.trim().length>0,S=!1;if(ss&&T&&(ss=!1,Ot=0,S=!0),S&&T){let J=(ao||"").trim();if(J.endsWith("?")||/\b(Wo |Bitte |Kannst du|Soll ich)\b/.test(J.slice(-200))){let V={role:"user",content:"[SYSTEM] Continue. Do not ask questions \u2014 implement the fix yourself using SSH. The server is at 94.130.37.43."};b.push(V),X.push(V);continue}}if(!T&&te>0&&dt<Ra-1){let J={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."};b.push(J),X.push(J);continue}if(Hs()&&T&&te===0)if(pr++,pr>2)oe(`${$.yellow} \u26A0 Plan accepted despite no file reads (rejection loop cap reached)${$.reset}`);else{let J={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.).
|
|
929
929
|
|
|
930
|
-
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.`};X.push(J),b.push(J),oe(`${
|
|
931
|
-
${
|
|
932
|
-
`),
|
|
930
|
+
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.`};X.push(J),b.push(J),oe(`${$.yellow} \u26A0 Plan rejected (${pr}/2): no files read \u2014 forcing investigation${$.reset}`);continue}if(Hs()&&T){let J=(ao||Xt||"").trim();ub(J),Bb(J);let U=db(J);if(U.length>0){let V=X.find(Z=>Z.role==="user"),re=typeof V?.content=="string"?V.content.slice(0,120):"Task";fb(re,U);let L=U.length===1?"step":"steps",B=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:Z,startExecution:ce,setPlanMode:me}=It();process.stdout.write(`
|
|
931
|
+
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${U.length} ${L})${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${$.reset} ${$.yellow}[E]${$.reset}${$.dim}dit${$.reset} ${$.red}[R]${$.reset}${$.dim}eject${$.reset} ${$.dim}[\u21B5 = approve]:${$.reset} `);let Ie=process.stdin.isRaw,le=await new Promise(pt=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",co=>{try{process.stdin.setRawMode(Ie||!1)}catch{}let Hr=co.toString().toLowerCase()[0]||"\r";pt(Hr)})});if(process.stdout.write(`
|
|
932
|
+
`),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(Z()){ce(),me(!1),Aa(),console.log(`${$.green}${$.bold}Approved!${$.reset} Executing ${U.length} ${L}...`);let pt=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
933
933
|
|
|
934
934
|
Implement the following plan step by step. All tools are now available.
|
|
935
935
|
|
|
936
936
|
${J}`;X.push({role:"user",content:pt}),b.push({role:"user",content:pt}),B=!0}}else console.log(`
|
|
937
|
-
${
|
|
938
|
-
${
|
|
939
|
-
`),
|
|
937
|
+
${$.cyan}${$.bold}Plan ready${$.reset} ${$.dim}(${U.length} ${L} extracted).${$.reset} Type ${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ${$.reset}${$.cyan}/plan edit${$.reset}${$.dim} to review.${$.reset}`);if(B){a&&(a.stop(),a=null),dt--;continue}}else{let V=!1;if(process.stdout.isTTY&&process.stdin.isTTY){let{approvePlan:re,startExecution:L,setPlanMode:B}=It();process.stdout.write(`
|
|
938
|
+
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.green}[A]${$.reset}${$.dim}pprove${$.reset} ${$.red}[R]${$.reset}${$.dim}eject${$.reset} ${$.dim}[\u21B5 = approve]:${$.reset} `);let Z=process.stdin.isRaw,ce=await new Promise(me=>{try{process.stdin.setRawMode(!0)}catch{}process.stdin.resume(),process.stdin.once("data",Ie=>{try{process.stdin.setRawMode(Z||!1)}catch{}me(Ie.toString().toLowerCase()[0]||"\r")})});if(process.stdout.write(`
|
|
939
|
+
`),ce==="r")console.log(`${$.red}Plan rejected.${$.reset} Ask follow-up questions to refine.`);else if(re()){L(),B(!1),Aa(),console.log(`${$.green}${$.bold}Approved!${$.reset} Executing...`);let Ie=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
940
940
|
|
|
941
941
|
Implement the following plan step by step. All tools are now available.
|
|
942
942
|
|
|
943
943
|
${getPlanContent()||jt.content}`;X.push({role:"user",content:Ie}),b.push({role:"user",content:Ie}),V=!0}}else console.log(`
|
|
944
|
-
${
|
|
944
|
+
${$.cyan}${$.bold}Plan ready.${$.reset} ${$.dim}Type ${$.reset}${$.cyan}/plan approve${$.reset}${$.dim} to execute, or ask follow-up questions to refine.${$.reset}`);if(V){a&&(a.stop(),a=null),dt--;continue}}}a&&(a.stop(),a=null),i(null),We(te,E,M,W,H),Ue(X),Mf(X);return}te++,te>=1&&(Oe=!1);for(let T of dn){let S=T.function.name;E.set(S,(E.get(S)||0)+1)}let Pe=await Promise.all(dn.map(T=>Hb(T)));{let T=At(b,Je()),S=T.percentage,J=Pe.some(L=>L.canExecute&&L.fnName==="read_file"&&!L.args?.line_end),U=Pe.filter(L=>L.canExecute&&L.fnName==="read_file"&&L.args?.path&&An.get(L.args.path)>=1&&!L.args?.line_start).map(L=>L.args.path.split("/").slice(-2).join("/")),V=U.length>0;if(S>=70&&J&&Pr<70||S>=85&&Pr<85||V){Pr=S;let L=S>=85?"URGENT":"WARNING",B;V?(L="WARNING",B=`Unbounded re-read of ${U.join(", ")} \u2014 already in context. Use line_start/line_end to read specific sections instead.`):J?B=`Unbounded read at ${Math.round(S)}% context \u2014 use line_start/line_end to avoid overflow.`:B=`Context ${Math.round(S)}% used. Avoid large reads, wrap up with what you have.`;let Z={role:"user",content:`[SYSTEM ${L}] Context ${Math.round(S)}% used (${T.used}/${T.limit} tokens). ${B}`};if(X.push(Z),b.push(Z),S>=85){let ce=V?` (re-read of: ${U.join(", ")})`:"";oe(`${$.yellow} \u26A0 Context ${Math.round(S)}% used \u2014 agent warned to use targeted reads${ce}${$.reset}`)}}}for(let T of Pe){if(!T.canExecute||T.fnName!=="read_file")continue;let S=T.args?.path;if(!S)continue;let J=An.get(S)||0,U=T.args?.line_start!=null,V=ts.get(S)===!0,re=6;if(J>=re){let L=S.split("/").slice(-2).join("/"),B=(ns.get(S)||0)+1;ns.set(S,B),B===1&&oe(`${$.red} \u2716 Blocked: "${L}" read ${J}\xD7 \u2014 hard cap (${re}) reached${$.reset}`),T.canExecute=!1,T.errorResult={role:"tool",content:`BLOCKED: read_file("${S}") denied \u2014 file already read ${J}\xD7 (hard cap: ${re}). You have seen enough of this file. Use grep to find specific content or proceed with what you know.`,tool_call_id:T.callId}}else if(J>=1&&U)if(V){let L=S.split("/").slice(-2).join("/");console.log(`${$.cyan} \u21A9 Targeted re-read: "${L}" (line_start=${T.args.line_start}) \u2014 edit recovery${$.reset}`),ts.delete(S)}else{let L=T.args.line_start||1,B=T.args.line_end||L+350,Z=Ws.get(S)||[],ce=!1;for(let[me,Ie]of Z){let le=Math.max(L,me),pt=Math.min(B,Ie);if(pt>le){let co=pt-le,Hr=B-L||1;if(co/Hr>=.7){let yc=S.split("/").slice(-2).join("/");oe(`${$.red} \u2716 Blocked duplicate read: "${yc}" lines ${L}-${B} (\u226570% overlap with lines ${me}-${Ie} already in context)${$.reset}`),T.canExecute=!1,T.errorResult={role:"tool",content:`BLOCKED: read_file("${S}", lines ${L}-${B}) is a duplicate \u2014 lines ${me}-${Ie} are already in your context (\u226570% overlap). Use grep to find specific content instead of re-reading.`,tool_call_id:T.callId},ce=!0;break}}}if(!ce){let me=Z.length,Ie=2;if(me>=3){let pt=S.split("/").slice(-2).join("/");oe(`${$.red} \u2716 Blocked file-scroll: "${pt}" \u2014 ${me} sections already read. Use grep to find specific content.${$.reset}`),T.canExecute=!1,T.errorResult={role:"tool",content:`BLOCKED: read_file("${S}") denied \u2014 you have already read ${me} 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:T.callId}}else me>=Ie&&(T._scrollWarn={sectionCount:me+1,path:S})}}else if(J>=1){let L=S.split("/").slice(-2).join("/"),B=(ns.get(S)||0)+1;ns.set(S,B),B===1&&oe(`${$.red} \u2716 Blocked unbounded re-read: "${L}" \u2014 already in context. Use line_start/line_end for specific sections.${$.reset}`),T.canExecute=!1,T.errorResult={role:"tool",content:`BLOCKED: read_file("${S}") denied \u2014 file already in context (read ${J}\xD7). Use line_start/line_end to read a specific section instead of the full file.`,tool_call_id:T.callId}}}for(let T of Pe)T.canExecute&&(T.fnName!=="ssh_exec"&&T.fnName!=="bash"||/\bsed\s+-n\b/.test(T.args?.command||"")&&(oe(`${$.red} \u2716 Blocked sed -n: use grep -n "pattern" <file> | head -30 instead${$.reset}`),T.canExecute=!1,T.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:T.callId}));for(let T of Pe){if(!T.canExecute||T.fnName!=="write_file")continue;let S=T.args?.path,J=T.args?.content||"";if(S)try{let U=require("fs"),V=require("path").resolve(process.cwd(),S);if(U.existsSync(V)){let re=U.statSync(V).size,L=Buffer.byteLength(J,"utf8"),B=re>0?L/re:1;if(B<.6&&re>200){let Z=S.split("/").slice(-2).join("/");console.log(`${$.red} \u2716 write_file shrink guard: "${Z}" would shrink to ${Math.round(B*100)}% of original \u2014 likely context loss${$.reset}`),T.canExecute=!1,T.errorResult={role:"tool",content:`BLOCKED: write_file("${S}") denied \u2014 new content is only ${Math.round(B*100)}% of current file size (${re} \u2192 ${L} 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:T.callId}}}}catch{}}for(let T of Pe){if(!T.canExecute||T.fnName!=="grep")continue;let S=T.args?.path;if(!S)continue;let J=je.get(S)||0;if(J>=zt){let U=S.split("/").slice(-2).join("/");oe(`${$.red} \u2716 Blocked grep: "${U}" grepped ${J}\xD7 with different patterns \u2014 flood threshold exceeded${$.reset}`),T.canExecute=!1,T.errorResult={role:"tool",content:`BLOCKED: grep("${S}") denied \u2014 ${J} patterns already tried. Use existing results.`,tool_call_id:T.callId}}}if(ss){let T=Pe.filter(U=>U.canExecute&&U.fnName==="ssh_exec"),S=Pe.some(U=>U.canExecute&&U.fnName!=="ssh_exec"),J=ae&&be<3;if(T.length>0&&!S&&J&&hr<1)ss=!1,hr++,Ot=Math.max(0,Ir-2),oe(`${$.dim} [dual-block deadlock: SSH storm relaxed \u2014 allowing 1 SSH call (relax ${hr}/1)]${$.reset}`);else for(let U of T)U.canExecute=!1,U.errorResult={role:"tool",content:`BLOCKED: ssh_exec denied \u2014 SSH storm (${Ir}+ calls). Synthesize findings now.`,tool_call_id:U.callId}}if(ae&&be<3){for(let T of Pe)if(T.canExecute&&["bash","read_file","find_files"].includes(T.fnName)){be++;{let S=Je(),{messages:J}=Lt(b,S);b=J}oe(`${$.yellow} \u26A0 Jarvis-local guard: blocking local ${T.fnName} \u2014 use ssh_exec on 94.130.37.43${$.reset}`),T.canExecute=!1,T.errorResult={role:"tool",content:`BLOCKED: ${T.fnName} denied \u2014 this is a server issue. Use ssh_exec on 94.130.37.43 instead.`,tool_call_id:T.callId};break}}let cs=a?{skipSpinner:!0,skipSummaries:!0}:{},wm=Pe.some(T=>T.fnName==="ask_user"),hc=!cs.skipSummaries&&!Oe,Br=null;hc&&!wm?(Oe=!0,cs.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(ba(Pe,te,!1,"blink")),Br=!0):Dt||process.stdout.write(ba(Pe,te,!1)+`
|
|
945
945
|
`)):hc&&(Oe=!0,cs.skipSpinner=!0),a&&a._paused&&a.resume();let{results:gc,summaries:bm}=await Yb(Pe,!0,{...cs,skipSummaries:!0});if(Br&&(Br=null,process.stdout.write(`\r\x1B[2K${ba(Pe,te,!1)}
|
|
946
|
-
`)),!cs.skipSummaries){let T=bm.filter((U,V)=>!(Pe[V]&&Pe[V].fnName==="ask_user"));for(let U of T)console.log(U);console.log("");let S=Pe.filter(U=>U&&U.fnName!=="ask_user").map(U=>U.fnName),J=ne.record(0,S,W,M);J&&Eb(J)}for(let T of Pe){if(T.canExecute||!T.errorResult)continue;let S=typeof T.errorResult.content=="string"?T.errorResult.content:"";if((S.startsWith("BLOCKED:")||S.startsWith("PLAN MODE:"))&&(ln++,ln>=uc)){oe(`${
|
|
947
|
-
`)[0],V=!U.startsWith("ERROR")&&!U.startsWith("CANCELLED")&&!U.startsWith("Command failed")&&!U.startsWith("EXIT");if(!V&&(S.fnName==="edit_file"||S.fnName==="patch_file")&&S.args?.path&&U.includes("old_text not found")&&ts.set(S.args.path,!0),V&&S.fnName==="write_file"&&S.args?.path){let L=S.args.path.split("/").pop(),B=S.args.path.includes("/tests/")||S.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(L)&&!B){oe(`${
|
|
948
|
-
${
|
|
946
|
+
`)),!cs.skipSummaries){let T=bm.filter((U,V)=>!(Pe[V]&&Pe[V].fnName==="ask_user"));for(let U of T)console.log(U);console.log("");let S=Pe.filter(U=>U&&U.fnName!=="ask_user").map(U=>U.fnName),J=ne.record(0,S,W,M);J&&Eb(J)}for(let T of Pe){if(T.canExecute||!T.errorResult)continue;let S=typeof T.errorResult.content=="string"?T.errorResult.content:"";if((S.startsWith("BLOCKED:")||S.startsWith("PLAN MODE:"))&&(ln++,ln>=uc)){oe(`${$.red} \u2716 Loop abort: ${ln} consecutive blocked calls (pre-execution) \u2014 model not heeding BLOCKED messages${$.reset}`),a&&(a.stop(),a=null),i(null),We(te,E,M,W,H,{suppressHint:!0}),Ue(X);return}}for(let T=0;T<Pe.length;T++){let S=Pe[T];if(!S.canExecute)continue;let J=gc[T].content,U=J.split(`
|
|
947
|
+
`)[0],V=!U.startsWith("ERROR")&&!U.startsWith("CANCELLED")&&!U.startsWith("Command failed")&&!U.startsWith("EXIT");if(!V&&(S.fnName==="edit_file"||S.fnName==="patch_file")&&S.args?.path&&U.includes("old_text not found")&&ts.set(S.args.path,!0),V&&S.fnName==="write_file"&&S.args?.path){let L=S.args.path.split("/").pop(),B=S.args.path.includes("/tests/")||S.args.path.includes("\\tests\\");if(/^(test_|demo_|temp_|tmp_|scratch_)/.test(L)&&!B){oe(`${$.yellow} \u26A0 Temp file: "${L}" \u2014 delete with bash rm when done to keep the workspace clean${$.reset}`);let ce={role:"user",content:`[HINT] "${S.args.path}" looks like a temporary test/demo file. Delete it with bash("rm ${S.args.path}") as soon as you're done \u2014 orphaned temp files count against session quality.`};X.push(ce),b.push(ce)}}if(V&&["write_file","edit_file","patch_file"].includes(S.fnName)&&S.args&&S.args.path){ts.delete(S.args.path),M.add(S.args.path);let L=(I.get(S.args.path)||0)+1;I.set(S.args.path,L);let B=S.args.path.split("/").slice(-2).join("/");if(L===F){oe(`${$.yellow} \u26A0 Loop warning: "${B}" edited ${L}\xD7 \u2014 possible edit loop${$.reset}`);let Z={role:"user",content:`[SYSTEM WARNING] "${S.args.path}" edited ${L}\xD7. One more edit max, then move on.`};X.push(Z),b.push(Z)}else if(L>=se){oe(`${$.red} \u2716 Loop abort: "${B}" edited ${L}\xD7 \u2014 aborting to prevent runaway loop${$.reset}`),a&&(a.stop(),a=null),i(null),We(te,E,M,W,H,{suppressHint:!0}),Ue(X);return}}if((S.fnName==="bash"||S.fnName==="ssh_exec")&&S.args&&S.args.command){let L=S.args.command.replace(/\d+/g,"N").replace(/\s+/g," ").trim().slice(0,100),B=(z.get(L)||0)+1;if(z.set(L,B),B===Q){oe(`${$.yellow} \u26A0 Loop warning: same bash command run ${B}\xD7 \u2014 possible debug loop${$.reset}`);let Z={role:"user",content:`[SYSTEM WARNING] Same bash command ${B}\xD7. Debug loop detected \u2014 try a different approach.`};X.push(Z),b.push(Z)}else if(B>=pe){oe(`${$.red} \u2716 Loop abort: same bash command run ${B}\xD7 \u2014 aborting runaway debug loop${$.reset}`),a&&(a.stop(),a=null),i(null),We(te,E,M,W,H,{suppressHint:!0}),Ue(X);return}}if(S.fnName==="ssh_exec"){if(Ot++,Ot>=ym){oe(`${$.red} \u2716 SSH storm abort: ${Ot} consecutive ssh_exec calls \u2014 aborting${$.reset}`),a&&(a.stop(),a=null),i(null),We(te,E,M,W,H,{suppressHint:!0}),Ue(X);return}else if(Ot===Ir){{let B=Je(),{messages:Z}=Lt(b,B);b=Z}ss=!0,oe(`${$.yellow} \u26A0 SSH storm warning: ${Ot} consecutive ssh_exec calls \u2014 blocking further SSH${$.reset}`);let L={role:"user",content:`[SYSTEM WARNING] ${Ot} consecutive SSH calls. Synthesize findings now \u2014 no more SSH.`};X.push(L),b.push(L)}}else S.canExecute&&(Ot=0);if(V&&S.fnName==="grep"&&S.args&&S.args.pattern){let L=`${S.args.pattern}|${S.args.path||""}`,B=(ue.get(L)||0)+1;if(ue.set(L,B),B===$e){oe(`${$.yellow} \u26A0 Loop warning: grep pattern "${S.args.pattern.slice(0,40)}" run ${B}\xD7 \u2014 possible search loop${$.reset}`);let Z={role:"user",content:`[SYSTEM WARNING] Same grep pattern ${B}\xD7. Results unchanged \u2014 use existing data or try different pattern.`};X.push(Z),b.push(Z)}else if(B>=ye){oe(`${$.red} \u2716 Loop abort: grep pattern run ${B}\xD7 \u2014 aborting runaway search loop${$.reset}`),a&&(a.stop(),a=null),i(null),We(te,E,M,W,H,{suppressHint:!0}),Ue(X);return}if(S.args.path){let Z=(je.get(S.args.path)||0)+1;if(je.set(S.args.path,Z),Z===Ge){let ce=S.args.path.split("/").slice(-2).join("/");oe(`${$.yellow} \u26A0 Loop warning: "${ce}" grepped ${Z}\xD7 with different patterns \u2014 context flood risk${$.reset}`);let me={role:"user",content:`[SYSTEM WARNING] "${S.args.path}" grepped ${Z}\xD7 \u2014 file already in context. Use existing data, stop searching.`};X.push(me),b.push(me)}}}if(V&&(S.fnName==="bash"||S.fnName==="ssh_exec")&&J.includes('"valid":true')){{let B=Je();if(At(b,B).percentage>=60){let{messages:ce,tokensRemoved:me}=Lt(b,B);me>0&&(b=ce,console.log(`${$.dim} [pre-stop-compress \u2014 ~${me} tokens freed before STOP injection, now ${Math.round(At(b,B).percentage)}%]${$.reset}`))}}let L={role:"user",content:'[SYSTEM STOP] Tool result contains {"valid":true}. The token/service is valid and reachable. STOP all further investigation immediately. Report to the user that the token is valid, the service is healthy, and no fix is needed. Do NOT read any more log files.'};X.push(L),b.push(L),console.log(`${$.cyan} \u2713 Health-check stop signal detected \u2014 injecting STOP instruction${$.reset}`)}if(J.startsWith("BLOCKED:")){if(ln++,ln>=uc){oe(`${$.red} \u2716 Loop abort: ${ln} consecutive blocked calls \u2014 model not heeding BLOCKED messages${$.reset}`),a&&(a.stop(),a=null),i(null),We(te,E,M,W,H,{suppressHint:!0}),Ue(X);return}}else ln=0;if(V)cn=0,Dr=!0;else if(cn++,cn===mm){oe(`${$.yellow} \u26A0 Loop warning: ${cn} consecutive tool errors \u2014 possible stuck loop${$.reset}`);let L={role:"user",content:`[SYSTEM WARNING] ${cn} consecutive errors. Stuck loop \u2014 try fundamentally different approach or declare done.`};X.push(L),b.push(L)}else if(cn>=hm){oe(`${$.red} \u2716 Loop abort: ${cn} consecutive errors \u2014 aborting stuck loop${$.reset}`),a&&(a.stop(),a=null),i(null),We(te,E,M,W,H,{suppressHint:!0}),Ue(X);return}if(V&&S.fnName==="read_file"&&S.args&&S.args.path){W.add(S.args.path);let L=(An.get(S.args.path)||0)+1;if(An.set(S.args.path,L),S.args.line_start!=null){let ce=S.args.line_start||1,me=S.args.line_end||ce+350;Ws.has(S.args.path)||Ws.set(S.args.path,[]),Ws.get(S.args.path).push([ce,me])}if(S._scrollWarn){let{sectionCount:ce,path:me}=S._scrollWarn,Ie={role:"user",content:`[SYSTEM WARNING] "${me}" \u2014 you have now read ${ce} 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.`};X.push(Ie),b.push(Ie),oe(`${$.yellow} \u26A0 Scroll warning: "${me.split("/").slice(-2).join("/")}" \u2014 ${ce} sections read \u2014 use grep instead${$.reset}`)}let B=S.args.path.split("/").slice(-2).join("/"),Z=!S.args?.line_start&&!S.args?.line_end;if(Z&&L===Mr){{let me=Je();if(At(b,me).percentage>=60){let{messages:le}=Lt(b,me);b=le}}oe(`${$.yellow} \u26A0 Loop warning: "${B}" read unbounded ${L}\xD7 \u2014 use line_start/line_end${$.reset}`);let ce={role:"user",content:`[SYSTEM WARNING] "${S.args.path}" read ${L}\xD7 without line ranges. Use line_start/line_end to read specific sections \u2014 do not re-read the full file.`};X.push(ce),b.push(ce)}else if(Z&&L>=pm){oe(`${$.red} \u2716 Loop abort: "${B}" read unbounded ${L}\xD7 \u2014 aborting runaway read loop${$.reset}`),a&&(a.stop(),a=null),i(null),We(te,E,M,W,H,{suppressHint:!0}),Ue(X);return}}if(S.fnName==="spawn_agents"){let L=(J.match(/\bStatus: done\b/g)||[]).length;if((J.match(/\bStatus: truncated\b/g)||[]).length>0&&L===0){if(un++,un===gm){oe(`${$.yellow} \u26A0 Swarm warning: all sub-agents hit iteration limit ${un}\xD7 in a row${$.reset}`);let Z={role:"user",content:`[SYSTEM WARNING] Sub-agents truncated ${un}\xD7 in a row. Stop spawning \u2014 try different approach or report findings.`};X.push(Z),b.push(Z)}else if(un>=$m){console.log(`${$.red} \u2716 Swarm abort: all sub-agents hit iteration limit ${un}\xD7 \u2014 aborting stuck swarm${$.reset}`),a&&(a.stop(),a=null),i(null),We(te,E,M,W,H,{suppressHint:!0}),Ue(X);return}}else L>0&&(un=0)}}for(let T of gc)X.push(T),b.push(T);{let T=Je();if(At(b,T).percentage>=78){let{messages:J,tokensRemoved:U}=Lt(b,T);U>0&&(b=J,console.log(`${$.dim} [auto-compressed \u2014 ~${U} tokens freed, now ${Math.round(At(b,T).percentage)}%]${$.reset}`))}}let $c=Xb();if($c){let T={role:"user",content:`[User note mid-run]: ${$c}`};X.push(T),b.push(T),console.log(`${$.cyan} \u270E Context added${$.reset}`)}}if(dt>=so){a&&(a.stop(),a=null),i(null),We(te,E,M,W,H),Ue(X),Mf(X);let{getActiveProviderName:qe}=Ae();if(qe()==="ollama"&&Lr<dc){if(M.size===0&&!Dr){console.log(`${$.yellow} \u26A0 Max iterations reached with no progress. Stopping.${$.reset}`);break e}Lr++,so=20,console.log(`${$.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Lr}/${dc}) \u2500\u2500${$.reset}`);continue e}if(console.log(`
|
|
948
|
+
${$.yellow}\u26A0 Max iterations reached.${$.reset}`),await Uf(" Continue for 20 more turns?")){so=20;continue e}console.log(`${$.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${$.reset}`)}break e}}Jf.exports={processInput:i_,clearConversation:Qb,getConversationLength:e_,getConversationMessages:t_,setConversationMessages:n_,setAbortSignalGetter:Ob,setMaxIterations:Ab,invalidateSystemPromptCache:Aa,clearToolFilterCache:qb,getCachedFilteredTools:Hf,buildSystemPrompt:Xf,getProjectContextHash:Gf,buildUserContent:Bf,detectAndTruncateLoop:Ta,injectMidRunNote:zb}});var Ae=G((_v,tp)=>{var{OllamaProvider:a_}=Wc(),{OpenAIProvider:c_}=al(),{AnthropicProvider:l_}=dl(),{GeminiProvider:u_}=hl(),{LocalProvider:d_}=yl(),{checkBudget:f_}=qn(),La={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"}},Vf={};for(let[t,e]of Object.entries(La))for(let n of Object.values(e))Vf[n]=t;function Qf(t,e){let n=Vf[t];return n&&La[n][e]||t}var Ye={},ut=null,Be=null,Gs=[];function vt(){if(Object.keys(Ye).length>0)return;os("ollama",new a_),os("openai",new c_),os("anthropic",new l_),os("gemini",new u_),os("local",new d_);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;Ye[t]?(ut=t,Be=e||Ye[t].defaultModel):(ut="ollama",Be="kimi-k2.5");let n=process.env.FALLBACK_CHAIN;n&&(Gs=n.split(",").map(o=>o.trim()).filter(Boolean))}function os(t,e){Ye[t]=e}function p_(t){return vt(),Ye[t]||null}function Da(){return vt(),Ye[ut]||null}function m_(){return vt(),ut}function h_(){return vt(),Be}function g_(){vt();let t=Da();if(!t)return{id:Be,name:Be,provider:ut};let e=t.getModel(Be);return e?{...e,provider:ut}:{id:Be,name:Be,provider:ut}}function Zf(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let n=t.slice(0,e);if(Ye[n]||["ollama","openai","anthropic","gemini","local"].includes(n))return{provider:n,model:t.slice(e+1)}}return{provider:null,model:t}}function $_(t){vt();let{provider:e,model:n}=Zf(t);if(e){let s=Ye[e];return s&&(s.getModel(n)||e==="local"||e==="ollama")?(ut=e,Be=n,yr(),!0):!1}let o=Da();if(o&&o.getModel(n))return Be=n,yr(),!0;for(let[s,r]of Object.entries(Ye))if(r.getModel(n))return ut=s,Be=n,yr(),!0;return!1}function yr(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=Se();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Qe();t()}catch{}}function y_(){vt();let t=new Set;for(let e of Object.values(Ye))for(let n of e.getModelNames())t.add(n);return Array.from(t)}function w_(){return vt(),Object.entries(Ye).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(n=>({...n,active:t===ut&&n.id===Be}))}))}function b_(){vt();let t=[];for(let[e,n]of Object.entries(Ye)){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 __(t){Gs=Array.isArray(t)?t:[]}function x_(){return[...Gs]}function k_(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 ep(t){let e=[ut,...Gs.filter(r=>r!==ut)],n,o=0,s=0;for(let r=0;r<e.length;r++){let i=e[r],a=Ye[i];if(!a||!a.isConfigured())continue;s++;let l=f_(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?Qf(Be,i):Be;return u&&d!==Be&&process.stderr.write(` [fallback: ${i}:${d}]
|
|
949
949
|
`),await t(a,i,d)}catch(u){if(n=u,k_(u)&&r<e.length-1)continue;throw u}}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 v_(t,e,n={}){return vt(),ep((o,s,r)=>o.stream(t,e,{model:r,signal:n.signal,...n}))}async function S_(t,e,n={}){if(vt(),n.provider){let o=Ye[n.provider];if(!o||!o.isConfigured())throw new Error(`Provider '${n.provider}' is not available`);let s={model:n.model||Be,...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 ep(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 E_(){vt();let t=[];for(let[e,n]of Object.entries(Ye))n.isConfigured()&&t.push({name:e,models:Object.values(n.getModels())});return t}function T_(){for(let t of Object.keys(Ye))delete Ye[t];ut=null,Be=null,Gs=[]}tp.exports={registerProvider:os,getProvider:p_,getActiveProvider:Da,getActiveProviderName:m_,getActiveModelId:h_,getActiveModel:g_,setActiveModel:$_,getModelNames:y_,parseModelSpec:Zf,listProviders:w_,listAllModels:b_,callStream:v_,callChat:S_,getConfiguredProviders:E_,setFallbackChain:__,getFallbackChain:x_,resolveModelForProvider:Qf,MODEL_EQUIVALENTS:La,_reset:T_}});var qa=G((xv,np)=>{"use strict";var Gt=require("fs"),wr=require("path"),R_=require("readline"),he="\x1B[0m",br="\x1B[1m",Ve="\x1B[2m",_r="\x1B[33m",ja="\x1B[36m",Ks="\x1B[32m";function C_(t){return(e,n="")=>new Promise(o=>{let s=n?` ${Ve}[${n}]${he}`:"";t.question(` ${ja}${e}${s}${he}: `,r=>o(r.trim()||n))})}function Ys(t,e){return new Promise(n=>{e&&e.pause(),process.stdout.write(` ${ja}${t}${he}: `);let o=process.stdin,s=o.isRaw,r="";o.setRawMode(!0),o.resume(),o.setEncoding("utf8");let i=a=>{a==="\r"||a===`
|
|
950
950
|
`?(o.setRawMode(s||!1),o.removeListener("data",i),process.stdout.write(`
|
|
951
951
|
`),e&&e.resume(),n(r)):a===""?(process.stdout.write(`
|
|
@@ -976,13 +976,13 @@ ${Ks} \u2713 Setup complete!${he}
|
|
|
976
976
|
`);console.log=t,console.warn=t,console.info=t;let{setConfirmHook:e}=Xe(),n=new Map,o=0;e((a,l)=>{let u="cfm-"+ ++o,d=l?.toolName||"",f=!1;try{let{isCritical:m}=Xe();f=m(a)}catch{}return Tn({type:"confirm_request",id:u,question:a,tool:d,critical:f}),new Promise(m=>{n.set(u,m)})});let s=null,r={onToken(a){s&&Tn({type:"token",id:s,text:a})},onThinkingToken(){},onToolStart(a,l){s&&Tn({type:"tool_start",id:s,tool:a,args:l||{}})},onToolEnd(a,l,u){s&&Tn({type:"tool_end",id:s,tool:a,summary:l||"",ok:!!u})}},i=O_.createInterface({input:process.stdin,output:null,terminal:!1});Tn({type:"ready"}),i.on("line",async a=>{let l=a.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),Tn({type:"done",id:d})}catch(m){Tn({type:"error",id:d,message:m?.message||String(m)})}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,m]of n)n.delete(f),m(!1);break}default:break}}),i.on("close",()=>{process.exit(0)})}sp.exports={startServerMode:N_}});var cp=G((vv,ap)=>{"use strict";var xr=require("fs"),{T:Nt,isDark:M_}=fn(),$t="\x1B[0m",P_=!M_,I_=process.env.FOOTER_DEBUG==="1"||process.env.FOOTER_DEBUG==="2",L_=process.env.FOOTER_DEBUG==="2",rs=null;function an(...t){I_&&(rs||(rs=xr.openSync("/tmp/footer-debug.log","w")),xr.writeSync(rs,t.join(" ")+`
|
|
977
977
|
`))}function rp(t,e){if(!L_||typeof e!="string")return;rs||(rs=xr.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>
|
|
978
978
|
`).replace(/[\x00-\x08\x0b-\x1f\x7f]/g,o=>`<${o.charCodeAt(0).toString(16).padStart(2,"0")}>`);xr.writeSync(rs,`${t}: ${n}
|
|
979
|
-
`)}function ip(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Fa=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 Nt.footer_sep+"\u2500".repeat(e)+$t;let i=` ${Nt.footer_divider}\xB7${$t} `,a=[];n&&a.push(`${Nt.footer_model}${n}${$t}`),o&&a.push(`${Nt.footer_branch}${o}${$t}`),s&&a.push(`${Nt.footer_project}${s}${$t}`);let l=a.join(i),u=[n,o,s].filter(Boolean).join(" \xB7 ").length,d="\u2500 ";if(r){let h=r.length,p=Math.max(0,e-d.length-u-1-1-h-3),g="\u2500".repeat(p);return`${Nt.footer_sep}${d}${$t}${l}${Nt.footer_sep} ${g} ${$t}${Nt.footer_mode}${r}${$t}${Nt.footer_sep} \u2500\u2500${$t}`}let f=Math.max(0,e-d.length-u-2),m="\u2500".repeat(f);return`${Nt.footer_sep}${d}${$t}${l}${Nt.footer_sep} ${m}${$t}`}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(P_)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 rp("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);an("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),a="";for(let l=i;l<=o;l++)a+=this._goto(l)+"\x1B[2K";n(a),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(p,...g){if(rp("PATCH",p),!n._active||typeof p!="string")return o(p,...g);if(n._inRefreshLine){let
|
|
979
|
+
`)}function ip(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Fa=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 Nt.footer_sep+"\u2500".repeat(e)+$t;let i=` ${Nt.footer_divider}\xB7${$t} `,a=[];n&&a.push(`${Nt.footer_model}${n}${$t}`),o&&a.push(`${Nt.footer_branch}${o}${$t}`),s&&a.push(`${Nt.footer_project}${s}${$t}`);let l=a.join(i),u=[n,o,s].filter(Boolean).join(" \xB7 ").length,d="\u2500 ";if(r){let h=r.length,p=Math.max(0,e-d.length-u-1-1-h-3),g="\u2500".repeat(p);return`${Nt.footer_sep}${d}${$t}${l}${Nt.footer_sep} ${g} ${$t}${Nt.footer_mode}${r}${$t}${Nt.footer_sep} \u2500\u2500${$t}`}let f=Math.max(0,e-d.length-u-2),m="\u2500".repeat(f);return`${Nt.footer_sep}${d}${$t}${l}${Nt.footer_sep} ${m}${$t}`}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(P_)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 rp("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);an("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),a="";for(let l=i;l<=o;l++)a+=this._goto(l)+"\x1B[2K";n(a),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(p,...g){if(rp("PATCH",p),!n._active||typeof p!="string")return o(p,...g);if(n._inRefreshLine){let x=p.replace(/\n/g,"");return x?o(x,...g):!0}if(n._cursorOnInputRow)if(p.includes(`
|
|
980
980
|
`)&&p.length>4&&!p.includes("\r"))an("STDOUT: agent output, leaving input row, data="+JSON.stringify(p).slice(0,100)),n._cursorOnInputRow=!1,o(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd)));else{if(p.length<=4&&!p.includes(`
|
|
981
|
-
`)&&!p.includes("\r")&&!/[\x00-\x1f\x7f]/.test(p))return an("STDOUT: char intercept:",JSON.stringify(p)),n._origRefreshLine&&n._doRefreshLine(),!0;{let
|
|
982
|
-
`);for(let
|
|
983
|
-
`);process.stdout.write(`\x1B[${m}A`)}let
|
|
984
|
-
`);process.stdout.write(
|
|
985
|
-
`),m
|
|
981
|
+
`)&&!p.includes("\r")&&!/[\x00-\x1f\x7f]/.test(p))return an("STDOUT: char intercept:",JSON.stringify(p)),n._origRefreshLine&&n._doRefreshLine(),!0;{let x=p.replace(/\n/g,"");return x?o(x,...g):!0}}let y=n._cols||80,w=0,k=p.split(`
|
|
982
|
+
`);for(let x=0;x<k.length;x++){let _=ip(k[x]);_>0&&(w+=Math.floor((_-1)/y))}let R=k.length-1;return R+w>0&&(n._lastOutputRow=Math.min(n._lastOutputRow+R+w,n._scrollEnd)),o(p,...g)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(p,...g){if(!n._active)return n._origStderrWrite(p,...g);if(typeof p=="string"&&p.includes("\r")){let y=Math.min(n._lastOutputRow+1,n._scrollEnd);if(n._cursorOnInputRow){n._origWrite("\x1B7"),n._origWrite(n._goto(y));let w=n._origStderrWrite(p,...g);return n._origWrite("\x1B8"),w}n._origWrite(n._goto(y))}return n._origStderrWrite(p,...g)},this._origLog=console.log,this._origError=console.error;function s(...p){if(!n._active){n._origLog(...p);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origLog(...p),n.drawFooter(),o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!0}function r(...p){if(!n._active){n._origError(...p);return}n._origWrite(n._goto(Math.min(n._lastOutputRow+1,n._scrollEnd))),n._cursorOnInputRow=!1,n._origError(...p),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(p){n._origSetPr(p),n._active&&n.drawFooter(p)},this._origPrompt=e.prompt.bind(e),e.prompt=function(p){if(!n._active)return n._origPrompt(p);an("PROMPT: goto rowInput="+n._rowInput),e.prevRows=0,o(n._goto(n._rowInput)+$t+"\x1B[2K"),n._cursorOnInputRow=!0,n._origPrompt(p)};let i=e.question.bind(e);e.question=function(p,g){if(!n._active)return i(p,g);o(n._goto(n._rowInput)+"\x1B[2K"),e.prevRows=0,n._cursorOnInputRow=!0,i(p,y=>{o(n._goto(n._rowInput)+"\x1B[2K"),n._cursorOnInputRow=!1,n.drawFooter(),g(y)})};let a=Object.getPrototypeOf(e),l=Object.getOwnPropertySymbols(a).find(p=>p.toString()==="Symbol(_refreshLine)"),u=l?a[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)+$t+"\x1B[2K");let p=n._cols,g=e._prompt||"",y=ip(g),w=p-y-1;n._inRefreshLine=!0;try{if(e.line.length<=w){an("REFRESH: short line, len="+e.line.length),u();return}an("REFRESH: long line, len="+e.line.length+", max="+w);let k=e.line,R=e.cursor,x=Math.max(1,w-1),_=Math.max(0,R-x),b=(_>0?"\xAB":"")+k.slice(_,_+x+(_>0?0:1));e.line=b,e.cursor=b.length,u(),e.line=k,e.cursor=R}finally{n._inRefreshLine=!1}},u){let p=this._doRefreshLine;l&&Object.defineProperty(e,l,{value:p,writable:!0,configurable:!0}),e._refreshLine=p}e.on("line",()=>{n._active&&(an("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,m=()=>{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(m,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 p=n._rows,g=n._cols;(n._dirty||p!==n._prevTermRows||g!==n._prevTermCols)&&(an("CONSISTENCY: dirty="+n._dirty+" rows="+p+"/"+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}}};ap.exports={StickyFooter:Fa}});var dp=G((Sv,up)=>{var{C:Re}=Ce(),{listProviders:D_,getActiveProviderName:j_,getActiveModelId:q_,setActiveModel:F_}=Ae();function lp(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,k)=>w.isHeader?-1:k).filter(w=>w>=0);if(i.length===0){r(null);return}let a=e.findIndex(w=>w.isCurrent),l=a>=0?i.indexOf(a):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 m=0;function h(){if(m>0){process.stdout.write(`\x1B[${m}A`);for(let _=0;_<m;_++)process.stdout.write(`\x1B[2K
|
|
983
|
+
`);process.stdout.write(`\x1B[${m}A`)}let w=[];w.push(` ${Re.bold}${Re.cyan}${o}${Re.reset}`),w.push(` ${Re.dim}${s}${Re.reset}`),w.push("");let{start:k,end:R}=f();k>0&&w.push(` ${Re.dim}\u2191 more${Re.reset}`);for(let _=k;_<R;_++){let b=e[_];if(b.isHeader){w.push(` ${Re.bold}${Re.dim}${b.label}${Re.reset}`);continue}let A=i[l]===_,O=A?`${Re.cyan}> `:" ",P=b.isCurrent?` ${Re.yellow}<current>${Re.reset}`:"";A?w.push(`${O}${Re.bold}${b.label}${Re.reset}${P}`):w.push(`${O}${Re.dim}${b.label}${Re.reset}${P}`)}R<e.length&&w.push(` ${Re.dim}\u2193 more${Re.reset}`);let x=w.join(`
|
|
984
|
+
`);process.stdout.write(x+`
|
|
985
|
+
`),m=w.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function y(w,k){if(k){if(k.name==="up"||k.ctrl&&k.name==="p"){l>0&&(l--,h());return}if(k.name==="down"||k.ctrl&&k.name==="n"){l<i.length-1&&(l++,h());return}if(k.name==="return"){let R=e[i[l]];g(),r(R?R.value:null);return}if(k.name==="escape"||k.ctrl&&k.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",y),h()})}async function U_(t){let e=D_(),n=j_(),o=q_(),s=[];for(let i of e)if(i.models.length!==0){s.push({label:i.provider,value:null,isHeader:!0});for(let a of i.models){let l=i.provider===n&&a.id===o;s.push({label:` ${a.name} (${i.provider}:${a.id})`,value:`${i.provider}:${a.id}`,isCurrent:l})}}let r=await lp(t,s,{title:"Select Model"});return r?(F_(r),console.log(`${Re.green}Switched to ${r}${Re.reset}`),!0):(console.log(`${Re.dim}Cancelled${Re.reset}`),!1)}up.exports={pickFromList:lp,showModelPicker:U_}});var Wa=G((Tv,wp)=>{var fp=require("fs"),W_=require("path"),{atomicWrite:B_,withFileLockSync:H_}=Qt(),{callChat:pp}=Ae(),{remember:G_,listMemories:Ev,recall:K_}=rn(),Ua=4,Y_=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
986
986
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
987
987
|
|
|
988
988
|
Return ONLY valid JSON in this exact format:
|
|
@@ -1060,7 +1060,7 @@ ${i.content}`;n(a,l.content+d),s.push({name:a,reason:i.reason||"",action:"update
|
|
|
1060
1060
|
${Y.bold}${Y.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${Y.reset}`),console.log(`${Y.bold}${Y.cyan}\u2551 nex-code Server Setup Wizard \u2551${Y.reset}`),console.log(`${Y.bold}${Y.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${Y.reset}
|
|
1061
1061
|
`);let o=Object.keys(n);if(o.length>0&&(console.log(`${Y.dim}Existing profiles: ${o.join(", ")}${Y.reset}`),!await is("Add or update a server profile?",!0))){console.log(`${Y.dim}No changes made.${Y.reset}
|
|
1062
1062
|
`);return}let s={...n},r=!0;for(;r;){console.log(`
|
|
1063
|
-
${Y.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${Y.reset}`);let l=await nt("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${Y.red} Name is required.${Y.reset}`);continue}let u=await nt("Host / IP address");if(!u){console.log(`${Y.red} Host is required.${Y.reset}`);continue}let d=await nt("SSH user","root"),f=await nt("SSH port","22"),m=parseInt(f,10)||22,h=await nt("SSH key path (leave empty for SSH agent)",""),p=await Ha("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await is("Allow sudo commands?",!0),
|
|
1063
|
+
${Y.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${Y.reset}`);let l=await nt("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${Y.red} Name is required.${Y.reset}`);continue}let u=await nt("Host / IP address");if(!u){console.log(`${Y.red} Host is required.${Y.reset}`);continue}let d=await nt("SSH user","root"),f=await nt("SSH port","22"),m=parseInt(f,10)||22,h=await nt("SSH key path (leave empty for SSH agent)",""),p=await Ha("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await is("Allow sudo commands?",!0),y={host:u,user:d};m!==22&&(y.port=m),h&&(y.key=h),p!=="other"&&(y.os=p),g&&(y.sudo=!0),s[l]=y,console.log(`
|
|
1064
1064
|
${Y.green}\u2713${Y.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${p!=="other"?` [${p}]`:""}`),r=await is(`
|
|
1065
1065
|
Add another server?`,!1)}tt.existsSync(t)||tt.mkdirSync(t,{recursive:!0}),tt.writeFileSync(e,JSON.stringify(s,null,2)+`
|
|
1066
1066
|
`,"utf-8"),console.log(`
|
|
@@ -1073,8 +1073,8 @@ ${Y.dim}Use /servers to list profiles, /servers ping to check connectivity.${Y.r
|
|
|
1073
1073
|
`)}async function _p(t,e){let n=e||as.join(process.cwd(),bp),o=as.join(n,"deploy.json"),s={};if(tt.existsSync(o))try{s=JSON.parse(tt.readFileSync(o,"utf-8"))}catch{}if(!t){let u=as.join(n,"servers.json");if(tt.existsSync(u))try{t=JSON.parse(tt.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
1074
1074
|
${Y.bold}${Y.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${Y.reset}`),console.log(`${Y.bold}${Y.cyan}\u2551 Deploy Config Wizard \u2551${Y.reset}`),console.log(`${Y.bold}${Y.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${Y.reset}
|
|
1075
1075
|
`);let i=Object.keys(s);i.length>0&&console.log(`${Y.dim}Existing deploy configs: ${i.join(", ")}${Y.reset}`);let a={...s},l=!0;for(;l;){console.log(`
|
|
1076
|
-
${Y.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${Y.reset}`);let u=await nt("Config name (e.g. prod, staging)");if(!u){console.log(`${Y.red} Name is required.${Y.reset}`);continue}let d;r.length>0?d=await Ha("Target server",r,r[0]):d=await nt("Target server (profile name or user@host)");let f=await Ha("Deploy method",["rsync","git"],"rsync"),m="",h=[],p="";if(f==="rsync"){m=await nt("Local path to sync (e.g. dist/ or ./build)","dist/");let
|
|
1077
|
-
${Y.green}\u2713${Y.reset} Deploy config "${u}": [${f}] ${R}`),
|
|
1076
|
+
${Y.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${Y.reset}`);let u=await nt("Config name (e.g. prod, staging)");if(!u){console.log(`${Y.red} Name is required.${Y.reset}`);continue}let d;r.length>0?d=await Ha("Target server",r,r[0]):d=await nt("Target server (profile name or user@host)");let f=await Ha("Deploy method",["rsync","git"],"rsync"),m="",h=[],p="";if(f==="rsync"){m=await nt("Local path to sync (e.g. dist/ or ./build)","dist/");let x=await nt("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env");h=x?x.split(",").map(_=>_.trim()).filter(Boolean):[]}else p=await nt("Branch to pull (leave empty for current remote branch)","main");let g=await nt(f==="git"?"Remote repo path (e.g. /home/jarvis/my-app)":"Remote destination path (e.g. /var/www/app)");if(!g){console.log(`${Y.red} Remote path is required.${Y.reset}`);continue}let y=await nt("Command to run on remote after deploy (leave empty to skip)",""),w=await nt("Health check URL or remote command (leave empty to skip)",""),k={server:d,method:f,remote_path:g};f==="rsync"?(k.local_path=m,h.length>0&&(k.exclude=h)):p&&(k.branch=p),y&&(k.deploy_script=y),w&&(k.health_check=w),a[u]=k;let R=f==="git"?`${d}:${g}${p?` (${p})`:""}`:`${m.endsWith("/")?m:m+"/"} \u2192 ${d}:${g}`;console.log(`
|
|
1077
|
+
${Y.green}\u2713${Y.reset} Deploy config "${u}": [${f}] ${R}`),y&&console.log(` ${Y.dim} Then: ${y}${Y.reset}`),w&&console.log(` ${Y.dim} Health: ${w}${Y.reset}`),l=await is(`
|
|
1078
1078
|
Add another deploy config?`,!1)}tt.existsSync(n)||tt.mkdirSync(n,{recursive:!0}),tt.writeFileSync(o,JSON.stringify(a,null,2)+`
|
|
1079
1079
|
`,"utf-8"),console.log(`
|
|
1080
1080
|
${Y.green}\u2713 Saved .nex/deploy.json (${Object.keys(a).length} config${Object.keys(a).length!==1?"s":""})${Y.reset}`),console.log(`${Y.dim}Use: deploy prod (or with explicit params)${Y.reset}
|
|
@@ -1097,10 +1097,10 @@ ${u}
|
|
|
1097
1097
|
${f}
|
|
1098
1098
|
`;ze.writeFileSync(n,a),i=!0}return{saved:!0,envUpdated:i,changes:o}}var $x=/thinking|reasoning|instruct|planner|orchestrat/i;function yx(t){return $x.test(t)}function wx(t){if(!t||t.length===0)return{updated:!1};let e=Js.join(Er.homedir(),".nex-code","models.env");if(!ze.existsSync(e))return{updated:!1};let n=ze.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],a=s?t.find(d=>d.model===s):null,l=a?a.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+=`
|
|
1099
1099
|
${u}
|
|
1100
|
-
`,ze.writeFileSync(e,n),{updated:!0,previousModel:s,newModel:i.model}}Ap.exports={findNewModels:dx,fetchCloudModels:Rp,loadKnownModels:Ka,markBenchmarked:ux,updateReadme:mx,updateModelsEnv:hx,updateRoutingConfig:gx,generateBenchmarkBlock:Cp,checkOrchestratorCandidate:yx,updateOrchestratorModel:wx,SENTINEL_START:Ya,SENTINEL_END:Sr}});var Rn=G((Nv,jp)=>{"use strict";var{C:j}=Ce(),bx=Ae(),{TOOL_DEFINITIONS:Op}=Et(),Vs=[{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:"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"))}],Np=["minimax-m2.7:cloud","qwen3-coder:480b","kimi-k2:1t","devstral-2:123b","devstral-small-2:24b"],Mp=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],_x=7,Rr={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},xx="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 Pp(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:xx},{role:"user",content:t.prompt}],s=Date.now();try{let r=await bx.callChat(o,Op,{provider:"ollama",model:e,temperature:0,timeout:9e4});n.latencyMs=Date.now()-s;let i=r.tool_calls||[];if(t.expectedTool===null){let a=i.length===0;n.producedToolCall=a,n.correctTool=a,n.validArgs=!0,n.schemaCompliant=!0}else if(i.length>0){let a=i[0],l=a.function?.name||"unknown",u=a.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=Op.find(m=>m.function?.name===l);if(n.validArgs=!!t.validateArgs(u,f),f){let m=f.function?.parameters||{},h=m.required||[],p=Object.keys(m.properties||{});n.schemaCompliant=h.every(g=>u[g]!==void 0)&&Object.keys(u).every(g=>p.includes(g))}}}}catch(r){n.latencyMs=Date.now()-s,n.error=r.message.slice(0,120)}return n}function Qs(t){return t.error?0:((t.producedToolCall?Rr.producedToolCall:0)+(t.correctTool?Rr.correctTool:0)+(t.validArgs?Rr.validArgs:0)+(t.schemaCompliant?Rr.schemaCompliant:0))*100}var kx={coding:"coding",search:"coding",shell:"coding",schema:"coding","multi-step":"coding",reasoning:"coding",frontend:"frontend",sysadmin:"sysadmin",data:"data",agentic:"agentic"};function za(t){return Object.entries(t).map(([e,n])=>{let o=n.map(Qs),s=o.reduce((a,l)=>a+l,0)/o.length,r=a=>Math.round(n.filter(a).length/n.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic"]){let l=n.filter(d=>kx[d.category]===a);if(l.length===0)continue;let u=l.map(Qs).reduce((d,f)=>d+f,0)/l.length;i[a]=Math.round(u*10)/10}return{model:e,score:Math.round(s*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(n.reduce((a,l)=>a+l.latencyMs,0)/n.length),errorCount:n.filter(a=>a.error).length,categoryScores:i,results:n}}).sort((e,n)=>n.score-e.score)}function vx(t){let e={};for(let n of["coding","frontend","sysadmin","data","agentic"]){let o=t.filter(s=>s.categoryScores[n]!==void 0).sort((s,r)=>r.categoryScores[n]-s.categoryScores[n]);o.length>0&&(e[n]={model:o[0].model,score:o[0].categoryScores[n]})}return e}function Ip(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(`
|
|
1101
|
-
${
|
|
1102
|
-
${
|
|
1103
|
-
${
|
|
1100
|
+
`,ze.writeFileSync(e,n),{updated:!0,previousModel:s,newModel:i.model}}Ap.exports={findNewModels:dx,fetchCloudModels:Rp,loadKnownModels:Ka,markBenchmarked:ux,updateReadme:mx,updateModelsEnv:hx,updateRoutingConfig:gx,generateBenchmarkBlock:Cp,checkOrchestratorCandidate:yx,updateOrchestratorModel:wx,SENTINEL_START:Ya,SENTINEL_END:Sr}});var Rn=G((Nv,jp)=>{"use strict";var{C:q}=Ce(),bx=Ae(),{TOOL_DEFINITIONS:Op}=Et(),Vs=[{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:"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"))}],Np=["minimax-m2.7:cloud","qwen3-coder:480b","kimi-k2:1t","devstral-2:123b","devstral-small-2:24b"],Mp=["minimax-m2.7:cloud","qwen3-coder:480b","devstral-2:123b"],_x=7,Rr={producedToolCall:.2,correctTool:.35,validArgs:.3,schemaCompliant:.15},xx="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 Pp(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:xx},{role:"user",content:t.prompt}],s=Date.now();try{let r=await bx.callChat(o,Op,{provider:"ollama",model:e,temperature:0,timeout:9e4});n.latencyMs=Date.now()-s;let i=r.tool_calls||[];if(t.expectedTool===null){let a=i.length===0;n.producedToolCall=a,n.correctTool=a,n.validArgs=!0,n.schemaCompliant=!0}else if(i.length>0){let a=i[0],l=a.function?.name||"unknown",u=a.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=Op.find(m=>m.function?.name===l);if(n.validArgs=!!t.validateArgs(u,f),f){let m=f.function?.parameters||{},h=m.required||[],p=Object.keys(m.properties||{});n.schemaCompliant=h.every(g=>u[g]!==void 0)&&Object.keys(u).every(g=>p.includes(g))}}}}catch(r){n.latencyMs=Date.now()-s,n.error=r.message.slice(0,120)}return n}function Qs(t){return t.error?0:((t.producedToolCall?Rr.producedToolCall:0)+(t.correctTool?Rr.correctTool:0)+(t.validArgs?Rr.validArgs:0)+(t.schemaCompliant?Rr.schemaCompliant:0))*100}var kx={coding:"coding",search:"coding",shell:"coding",schema:"coding","multi-step":"coding",reasoning:"coding",frontend:"frontend",sysadmin:"sysadmin",data:"data",agentic:"agentic"};function za(t){return Object.entries(t).map(([e,n])=>{let o=n.map(Qs),s=o.reduce((a,l)=>a+l,0)/o.length,r=a=>Math.round(n.filter(a).length/n.length*100),i={};for(let a of["coding","frontend","sysadmin","data","agentic"]){let l=n.filter(d=>kx[d.category]===a);if(l.length===0)continue;let u=l.map(Qs).reduce((d,f)=>d+f,0)/l.length;i[a]=Math.round(u*10)/10}return{model:e,score:Math.round(s*10)/10,toolCallRate:r(a=>!a.error&&(a.producedToolCall||a.category==="reasoning")),correctRate:r(a=>a.correctTool),validArgsRate:r(a=>a.validArgs),schemaRate:r(a=>a.schemaCompliant),avgLatency:Math.round(n.reduce((a,l)=>a+l.latencyMs,0)/n.length),errorCount:n.filter(a=>a.error).length,categoryScores:i,results:n}}).sort((e,n)=>n.score-e.score)}function vx(t){let e={};for(let n of["coding","frontend","sysadmin","data","agentic"]){let o=t.filter(s=>s.categoryScores[n]!==void 0).sort((s,r)=>r.categoryScores[n]-s.categoryScores[n]);o.length>0&&(e[n]={model:o[0].model,score:o[0].categoryScores[n]})}return e}function Ip(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(`
|
|
1101
|
+
${q.bold}${n}${q.reset}`),console.log(r);let i=o.map(u=>u.label.padEnd(u.width)).join(" ");if(console.log(`${q.dim}${i}${q.reset}`),console.log(r),t.forEach((u,d)=>{let f=String(d+1).padEnd(o[0].width),m=u.model.slice(0,o[1].width).padEnd(o[1].width),h=String(u.score).padEnd(o[2].width),p=`${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),k=`${(u.avgLatency/1e3).toFixed(1)}s`.padEnd(o[7].width),R=u.errorCount>0?`${q.red}${u.errorCount}${q.reset}`:`${q.dim}0${q.reset}`,x=u.score>=80?q.green:u.score>=60?q.yellow:q.red,_=d===0?`${q.yellow}${f}${q.reset}`:`${q.dim}${f}${q.reset}`;console.log(`${_} ${x}${m}${q.reset} ${q.bold}${x}${h}${q.reset} ${p} ${g} ${y} ${w} ${q.dim}${k}${q.reset} ${R}`)}),console.log(r),t.length>0){let u=t[0];if(console.log(`
|
|
1102
|
+
${q.bold}${q.green}Winner: ${u.model}${q.reset} score ${u.score}/100`),t.length>1){let d=(u.score-t[1].score).toFixed(1);console.log(`${q.dim}+${d} pts over ${t[1].model}${q.reset}`)}}let a=["coding","frontend","sysadmin","data","agentic"];if(t.some(u=>Object.keys(u.categoryScores).length>1)){console.log(`
|
|
1103
|
+
${q.bold}Best model per task type:${q.reset}`);for(let u of a){let d=t.filter(p=>p.categoryScores[u]!==void 0).sort((p,g)=>g.categoryScores[u]-p.categoryScores[u]);if(d.length===0)continue;let f=d[0],m=f.categoryScores[u],h=m>=80?q.green:m>=60?q.yellow:q.red;console.log(` ${q.dim}${u.padEnd(10)}${q.reset} ${h}${f.model}${q.reset} ${q.dim}${m}/100${q.reset}`)}}console.log()}async function Sx({models:t,quick:e=!1,onProgress:n}={}){let o=e?Vs.slice(0,_x):Vs,s=t?.length>0?t:e?Mp:Np,r={};for(let a of s){r[a]=[];for(let l of o){n?.({model:a,task:l.id,done:!1});let u=await Pp(l,a);r[a].push(u),n?.({model:a,task:l.id,done:!0,score:Qs(u),error:u.error})}}let i=za(r);return Ip(i,o.length),i}async function Ex({newModels:t,existingRanking:e=[],onProgress:n}={}){if(!t||t.length===0)return e;let o={};for(let i of t){o[i]=[];for(let a of Vs){n?.({model:i,task:a.id,done:!1});let l=await Pp(a,i);o[i].push(l),n?.({model:i,task:a.id,done:!0,score:Qs(l),error:l.error})}}let r=[...za(o)];for(let i of e)r.find(a=>a.model===i.model)||r.push(i);return r.sort((i,a)=>a.score-i.score),Ip(r,Vs.length),r}var Cr=[{id:"simple_question",name:"Simple Convergence",prompt:"What is 2+2?",maxTurns:3,successCriteria:["4"]}];function Lp(t){let e=require("fs"),o=require("path").join(t||process.cwd(),".nex","benchmark-config.json");if(!e.existsSync(o))return console.log(`${q.yellow}No scenarios configured.${q.reset} Create ${q.dim}.nex/benchmark-config.json${q.reset} to define your benchmark scenarios.
|
|
1104
1104
|
Example:
|
|
1105
1105
|
{
|
|
1106
1106
|
"scenarios": [
|
|
@@ -1113,17 +1113,17 @@ ${j.bold}Best model per task type:${j.reset}`);for(let u of a){let d=t.filter(p=
|
|
|
1113
1113
|
}
|
|
1114
1114
|
]
|
|
1115
1115
|
}
|
|
1116
|
-
`),Cr;try{let s=JSON.parse(e.readFileSync(o,"utf-8"));return!Array.isArray(s.scenarios)||s.scenarios.length===0?(console.log(`${
|
|
1117
|
-
`),Cr):s.scenarios}catch(s){return console.log(`${
|
|
1118
|
-
`),Cr}}function Dp(t,e){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=sr(),r=n(t),i=r.score,a=[],l=s(t).toLowerCase();e.successCriteria.every(m=>l.includes(m.toLowerCase()))&&(i=Math.min(10,i+1),a.push("+1.0 all success criteria met"));let d=o(t);d.length<e.maxTurns/2&&(i=Math.min(10,i+.5),a.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:a}}async function Tx(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 a=s.resolve(__dirname,"..","bin","nex-code.js"),l=e.cwd||process.cwd(),u=[a,"--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}}),m=t.maxTurns*60*1e3,h=!1,p=setTimeout(()=>{h=!0;try{f.kill("SIGTERM")}catch{}},m);f.on("close",g=>{clearTimeout(p);try{o.unlinkSync(i)}catch{}let
|
|
1116
|
+
`),Cr;try{let s=JSON.parse(e.readFileSync(o,"utf-8"));return!Array.isArray(s.scenarios)||s.scenarios.length===0?(console.log(`${q.yellow}benchmark-config.json has no scenarios \u2014 using defaults.${q.reset}
|
|
1117
|
+
`),Cr):s.scenarios}catch(s){return console.log(`${q.yellow}Failed to parse benchmark-config.json: ${s.message}${q.reset}
|
|
1118
|
+
`),Cr}}function Dp(t,e){let{scoreMessages:n,_extractToolCalls:o,_getLastAssistantText:s}=sr(),r=n(t),i=r.score,a=[],l=s(t).toLowerCase();e.successCriteria.every(m=>l.includes(m.toLowerCase()))&&(i=Math.min(10,i+1),a.push("+1.0 all success criteria met"));let d=o(t);d.length<e.maxTurns/2&&(i=Math.min(10,i+.5),a.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:a}}async function Tx(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 a=s.resolve(__dirname,"..","bin","nex-code.js"),l=e.cwd||process.cwd(),u=[a,"--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}}),m=t.maxTurns*60*1e3,h=!1,p=setTimeout(()=>{h=!0;try{f.kill("SIGTERM")}catch{}},m);f.on("close",g=>{clearTimeout(p);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 Rx(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(`
|
|
1119
1119
|
\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),m=l.grade.padStart(2);console.log(`\u2502 ${u} ${d} ${f} ${m} \u2502`)}console.log(`\u2502 ${" ".repeat(r-2)} \u2502`);let a=`Overall: ${o}/10 (${s}) \xB7 v${e} \xB7 ${n}`;console.log(`\u2502 ${a.substring(0,r-4).padEnd(r-4)} \u2502`),console.log(`\u2514${"\u2500".repeat(r+1)}\u2518
|
|
1120
|
-
`)}function Cx(t=10){let e=require("fs"),o=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(o)){console.log(`${
|
|
1121
|
-
`);return}let s=[];try{s=JSON.parse(e.readFileSync(o,"utf-8"))}catch{s=[]}if(!Array.isArray(s)||s.length===0){console.log(`${
|
|
1120
|
+
`)}function Cx(t=10){let e=require("fs"),o=require("path").join(process.cwd(),".nex","benchmark-history.json");if(!e.existsSync(o)){console.log(`${q.yellow}No score history yet. Run a session first.${q.reset}
|
|
1121
|
+
`);return}let s=[];try{s=JSON.parse(e.readFileSync(o,"utf-8"))}catch{s=[]}if(!Array.isArray(s)||s.length===0){console.log(`${q.yellow}Score history is empty.${q.reset}
|
|
1122
1122
|
`);return}let r=s.slice(-t);console.log(`
|
|
1123
|
-
${
|
|
1124
|
-
${
|
|
1125
|
-
`);for(let l of r)console.log(` ${
|
|
1126
|
-
${
|
|
1123
|
+
${q.bold}Score History (last ${r.length} session${r.length===1?"":"s"}):${q.reset}`);for(let i of r){let a=(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||"?",m=i.issues&&i.issues.length>0?`${q.yellow}\u26A0 ${i.issues.slice(0,2).map(p=>p.substring(0,30)).join(", ")}${q.reset}`:`${q.green}\u2713${q.reset}`,h=i.score>=8?q.green:i.score>=6?q.yellow:q.red;console.log(` ${q.dim}${a}${q.reset} ${q.dim}v${l}${q.reset} ${q.dim}${u}${q.reset} ${h}${d} ${f}${q.reset} ${m}`)}console.log()}async function Ax({dryRun:t=!1,model:e,cwd:n,onProgress:o}={}){let s=On(),r=Lp(n);if(t){console.log(`
|
|
1124
|
+
${q.bold}Jarvis Benchmark \u2014 Scenarios (dry-run):${q.reset}
|
|
1125
|
+
`);for(let l of r)console.log(` ${q.cyan}${l.id.padEnd(20)}${q.reset} ${q.dim}${l.name}${q.reset} maxTurns=${l.maxTurns}`),console.log(` ${q.dim}${l.prompt.substring(0,80)}${q.reset}`);return console.log(),[]}let i=(()=>{if(e)return e;try{let{getActiveModel:l}=Fn();return l&&l()||"unknown"}catch{return"unknown"}})(),a=[];for(let l of r){o?.({id:l.id,name:l.name,done:!1}),console.log(`
|
|
1126
|
+
${q.dim}Running scenario: ${l.name}...${q.reset}`);let{messages:u,timedOut:d}=await Tx(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=Dp(u,l);let m={id:l.id,name:l.name,score:f.score,grade:f.grade,issues:f.issues,bonuses:f.bonuses};a.push(m),o?.({id:l.id,name:l.name,done:!0,score:f.score,grade:f.grade});try{let{appendScoreHistory:h}=sr();h(f.score,{version:s.version,model:i,sessionName:`bench:${l.id}`,issues:f.issues})}catch{}}return Rx(a,s.version,i),a}jp.exports={runBenchmark:Sx,runDiscoverBenchmark:Ex,buildSummary:za,buildCategoryWinners:vx,TASKS:Vs,scoreResult:Qs,DEFAULT_MODELS:Np,QUICK_MODELS:Mp,runJarvisBenchmark:Ax,showScoreTrend:Cx,loadScenarios:Lp,DEFAULT_SCENARIOS:Cr,scoreJarvisScenario:Dp}});var Yp=G((Mv,Kp)=>{"use strict";var Ox=require("os"),Up=require("path"),Xa=require("fs"),{callWithRetry:qp}=Ko(),{parseModelSpec:Nx}=Ae(),{extractJSON:Fp,DECOMPOSE_PROMPT:Mx,SYNTHESIZE_PROMPT:Px}=qs(),{C:yt}=Ce(),Ar=Up.join(Ox.homedir(),".nex-code","orchestrator-bench.json"),Wp=[{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 Bp(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 Hp(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 Gp(t,e){let n={};if(e){let s=Nx(e);s.provider&&(n.provider=s.provider),s.model&&(n.model=s.model)}let o=Date.now();try{if(t.type==="decompose"){let s=Mx.replace("{maxSubTasks}",String(t.maxSubTasks)).replace("{prompt}",t.prompt),r=await qp([{role:"system",content:s},{role:"user",content:t.prompt}],[],n),i=Fp(r.content||""),a=Date.now()-o;return{score:Bp(i,t),latencyMs:a}}if(t.type==="synthesize"){let s=t.subResults.map((d,f)=>{let m=d.status==="done"?"SUCCESS":"FAILED";return`--- Agent ${f+1} [${m}] ---
|
|
1127
1127
|
Task: ${d.task}
|
|
1128
1128
|
Result: ${d.result}
|
|
1129
1129
|
Tools: ${d.toolsUsed.join(", ")}`}).join(`
|
|
@@ -1205,7 +1205,7 @@ ${c.bold}${c.cyan}Token Usage:${c.reset}`),console.log(` ${c.dim}Model:${c.rese
|
|
|
1205
1205
|
${c.dim}Breakdown:${c.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}=qn();return o.join(" ").trim()==="reset"?(r(),console.log(`${c.green}Cost tracking reset${c.reset}`),!0):(console.log(`
|
|
1206
1206
|
${s()}
|
|
1207
1207
|
`),!0)}case"/budget":{let{getCostLimits:s,getProviderSpend:r,checkBudget:i,removeCostLimit:a,saveCostLimits:l,setCostLimit:u}=qn(),d=o[0];if(!d){let h=s(),p=ec();console.log(`
|
|
1208
|
-
${c.bold}${c.cyan}Cost Limits:${c.reset}`);let g=!1;for(let
|
|
1208
|
+
${c.bold}${c.cyan}Cost Limits:${c.reset}`);let g=!1;for(let y of p){let w=r(y.provider),k=h[y.provider];if(k!==void 0){g=!0;let R=Math.min(100,Math.round(w/k*100)),x=10,_=Math.round(R/100*x),b=x-_,O=`${R>=100?c.red:R>=80?c.yellow:c.green}${"\u2588".repeat(_)}${c.dim}${"\u2591".repeat(b)}${c.reset}`;console.log(` ${c.bold}${y.provider}:${c.reset} $${w.toFixed(2)} / $${k.toFixed(2)} (${R}%) ${O}`)}else y.provider==="ollama"||y.provider==="local"?console.log(` ${c.bold}${y.provider}:${c.reset} ${c.dim}free (no limit)${c.reset}`):w>0&&console.log(` ${c.bold}${y.provider}:${c.reset} $${w.toFixed(2)} ${c.dim}(no limit)${c.reset}`)}return g||console.log(` ${c.dim}No limits set. Use /budget <provider> <amount> to set one.${c.reset}`),console.log(),!0}let f=o[1];if(!f){let h=i(d);return h.limit!==null?console.log(`${c.bold}${d}:${c.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${c.bold}${d}:${c.reset} $${h.spent.toFixed(2)} ${c.dim}(no limit)${c.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return a(d),l(),console.log(`${c.green}Removed cost limit for ${d}${c.reset}`),!0;let m=parseFloat(f);return isNaN(m)||m<=0?(console.log(`${c.red}Invalid amount: ${f}. Use a positive number or 'off'.${c.reset}`),!0):(u(d,m),l(),console.log(`${c.green}Set ${d} budget limit: $${m.toFixed(2)}${c.reset}`),!0)}case"/clear":{let{clearConversation:s,getConversationMessages:r}=Se(),{clearHistory:i}=Ft(),a=r();if(a.filter(d=>d.role==="user").length>=4){process.stdout.write(`${c.dim}Reflecting on session...${c.reset} `);let{learnFromSession:d}=Wa();d(a).then(f=>{if(!f.skipped&&!f.error&&(f.applied.length>0||f.nexAdded.length>0)){let m=f.applied.length+f.nexAdded.length;process.stdout.write(`${c.green}${m} learning(s) saved${c.reset}
|
|
1209
1209
|
`)}else process.stdout.write(`${c.dim}nothing new${c.reset}
|
|
1210
1210
|
`)}).catch(()=>process.stdout.write(`
|
|
1211
1211
|
`))}s(),i();let{deleteSession:u}=Ct();return u("_autosave"),console.log(`${c.green}Conversation cleared${c.reset}`),!0}case"/context":return await Zp(St),!0;case"/tree":{let{generateFileTree:s}=tr(),r=parseInt(o.join(" ").trim(),10),i=!isNaN(r)&&r>0?Math.min(r,8):3,a=s(St,{maxDepth:i,maxFiles:300});return console.log(`
|
|
@@ -1215,31 +1215,31 @@ ${c.bold}${c.cyan}Project tree${c.reset}${c.dim} (depth ${i})${c.reset}
|
|
|
1215
1215
|
${c.bold}${c.cyan}Sessions:${c.reset}`);for(let i of r){let a=i.updatedAt?new Date(i.updatedAt).toLocaleString():"?",l=i.name==="_autosave"?` ${c.dim}(auto)${c.reset}`:"",u=i.score!=null?` \xB7 score ${i.score}/10${i.scoreGrade?` (${i.scoreGrade})`:""}`:"";console.log(` ${c.cyan}${i.name}${c.reset}${l} \u2014 ${i.messageCount} msgs, ${a}${c.dim}${u}${c.reset}`)}return console.log(),!0}case"/resume":{let{getLastSession:s}=Ct(),{setConversationMessages:r}=Se(),i=s();return i?(r(i.messages),console.log(`${c.green}Resumed: ${i.name} (${i.messageCount} messages)${c.reset}`),!0):(console.log(`${c.yellow}No session to resume${c.reset}`),!0)}case"/remember":{let{remember:s}=rn(),r=o.join(" ").trim();if(!r)return console.log(`${c.red}Usage: /remember <key>=<value> or /remember <text>${c.reset}`),!0;let i=r.indexOf("="),a,l;return i>0?(a=r.substring(0,i).trim(),l=r.substring(i+1).trim()):(a=r.substring(0,40).replace(/\s+/g,"-"),l=r),s(a,l),console.log(`${c.green}Remembered: ${a}${c.reset}`),!0}case"/forget":{let{forget:s}=rn(),r=o.join(" ").trim();return r?(s(r)?console.log(`${c.green}Forgotten: ${r}${c.reset}`):console.log(`${c.red}Memory not found: ${r}${c.reset}`),!0):(console.log(`${c.red}Usage: /forget <key>${c.reset}`),!0)}case"/memory":{let{listMemories:s}=rn(),r=s();if(r.length===0)return console.log(`${c.dim}No memories saved${c.reset}`),!0;console.log(`
|
|
1216
1216
|
${c.bold}${c.cyan}Memory:${c.reset}`);for(let i of r)console.log(` ${c.cyan}${i.key}${c.reset} = ${i.value}`);return console.log(),!0}case"/brain":{let{listDocuments:s,readDocument:r,writeDocument:i,removeDocument:a,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=Ts(),m=o[0],h=o.slice(1).join(" ").trim();switch(m){case"add":{if(!h)return console.log(`${c.red}Usage: /brain add <name> [content]${c.reset}`),console.log(`${c.dim} /brain add api-notes \u2014 creates empty file${c.reset}`),console.log(`${c.dim} /brain add api-notes This is content \u2014 writes directly${c.reset}`),!0;let p=h.indexOf(" ");if(p<0){i(h,`# ${h}
|
|
1217
1217
|
|
|
1218
|
-
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${c.green}Created .nex/brain/${h}.md${c.reset}`),console.log(`${c.dim}Edit it directly at: ${g}${c.reset}`)}else{let g=h.substring(0,p),
|
|
1219
|
-
${c.bold}${c.cyan}Brain Documents:${c.reset}`);let g=Math.max(8,...p.map(
|
|
1220
|
-
${c.bold}${c.cyan}Brain Search: "${h}"${c.reset}`);for(let g of p){let
|
|
1221
|
-
${c.cyan}${g.name}${c.reset} ${c.dim}(score: ${
|
|
1218
|
+
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${c.green}Created .nex/brain/${h}.md${c.reset}`),console.log(`${c.dim}Edit it directly at: ${g}${c.reset}`)}else{let g=h.substring(0,p),y=h.substring(p+1);i(g,y),console.log(`${c.green}Added to brain: ${g}${c.reset}`)}return!0}case"list":{let p=s();if(p.length===0)return console.log(`${c.dim}No brain documents yet. Use /brain add <name> to create one.${c.reset}`),!0;console.log(`
|
|
1219
|
+
${c.bold}${c.cyan}Brain Documents:${c.reset}`);let g=Math.max(8,...p.map(w=>w.name.length)),y=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd(y)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat(y)}${"-".repeat(7)} --------`);for(let w of p){let{frontmatter:k}=r(w.name),R=Array.isArray(k.tags)?k.tags.join(", "):"",x=w.size<1024?`${w.size}B`:`${(w.size/1024).toFixed(1)}K`,_=w.modified.toLocaleDateString();console.log(` ${c.cyan}${w.name.padEnd(g+2)}${c.reset}${c.dim}${R.substring(0,y-1).padEnd(y)}${x.padStart(7)} ${_}${c.reset}`)}return console.log(),!0}case"search":{if(!h)return console.log(`${c.red}Usage: /brain search <query>${c.reset}`),!0;let p=await f(h,{topK:5});if(p.length===0)return console.log(`${c.dim}No matching brain documents for: ${h}${c.reset}`),!0;console.log(`
|
|
1220
|
+
${c.bold}${c.cyan}Brain Search: "${h}"${c.reset}`);for(let g of p){let y=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
|
|
1221
|
+
${c.cyan}${g.name}${c.reset} ${c.dim}(score: ${y})${c.reset}`),console.log(` ${c.dim}${g.excerpt||""}${c.reset}`)}return console.log(),!0}case"show":{if(!h)return console.log(`${c.red}Usage: /brain show <name>${c.reset}`),!0;let p=r(h);return p.content?(console.log(`
|
|
1222
1222
|
${c.bold}${c.cyan}${h}.md${c.reset}
|
|
1223
|
-
`),console.log(p.content),!0):(console.log(`${c.red}Document not found: ${h}${c.reset}`),!0)}case"remove":{if(!h)return console.log(`${c.red}Usage: /brain remove <name>${c.reset}`),!0;let{confirm:p}=Xe();if(!await p(`Remove brain document "${h}"?`))return console.log(`${c.dim}Cancelled${c.reset}`),!0;let
|
|
1224
|
-
${c.bold}${c.cyan}Brain Status${c.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync(
|
|
1223
|
+
`),console.log(p.content),!0):(console.log(`${c.red}Document not found: ${h}${c.reset}`),!0)}case"remove":{if(!h)return console.log(`${c.red}Usage: /brain remove <name>${c.reset}`),!0;let{confirm:p}=Xe();if(!await p(`Remove brain document "${h}"?`))return console.log(`${c.dim}Cancelled${c.reset}`),!0;let y=a(h);return console.log(y?`${c.green}Removed: ${h}.md${c.reset}`:`${c.red}Document not found: ${h}${c.reset}`),!0}case"rebuild":{let p=l(),g=Object.keys(p.documents).length;return console.log(`${c.green}Index rebuilt: ${g} document(s)${c.reset}`),!0}case"embed":{if(!await d())return console.log(`${c.yellow}Ollama embedding model not available.${c.reset}`),console.log(`${c.dim}Set NEX_EMBED_MODEL env var (default: nomic-embed-text) and ensure Ollama is running.${c.reset}`),!0;console.log(`${c.dim}Building embedding index...${c.reset}`);try{let g=await u(),y=Object.keys(g.documents||{}).length;console.log(`${c.green}Embedding index built: ${y} document(s)${c.reset}`)}catch(g){console.log(`${c.red}Embedding failed: ${g.message}${c.reset}`)}return!0}case"status":{let p=s(),g=require("fs"),y=require("path"),w=y.join(process.cwd(),".nex","brain",".brain-index.json"),k=y.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
|
|
1224
|
+
${c.bold}${c.cyan}Brain Status${c.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync(w)?c.green+"present"+c.reset:c.dim+"not built"+c.reset}`),console.log(` Embeddings: ${g.existsSync(k)?c.green+"present"+c.reset:c.dim+"not built (run /brain embed)"+c.reset}`),p.length>0){let R=p.reduce((x,_)=>x+_.size,0);console.log(` Total size: ${R<1024?R+"B":(R/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:p}=require("child_process"),{promisify:g}=require("util"),y=g(p);try{let{stdout:w}=await y("git diff .nex/brain/",{cwd:process.cwd()});w.trim()?(console.log(`
|
|
1225
1225
|
${c.bold}${c.cyan}Brain Changes (git diff):${c.reset}
|
|
1226
|
-
`),console.log(
|
|
1226
|
+
`),console.log(w)):console.log(`${c.dim}No pending brain changes (clean git state)${c.reset}`)}catch{console.log(`${c.dim}Not a git repo or no brain dir${c.reset}`)}return!0}case"undo":{let p=require("fs"),y=require("path").join(process.cwd(),".nex","brain");if(!p.existsSync(y))return console.log(`${c.dim}No brain directory found${c.reset}`),!0;let w=s();if(w.length===0)return console.log(`${c.dim}No brain documents to undo${c.reset}`),!0;let k=w[0],{exec:R}=require("child_process"),{promisify:x}=require("util"),_=x(R);try{await _(`git checkout -- ".nex/brain/${k.name}.md"`,{cwd:process.cwd()}),l(),console.log(`${c.green}Undone: restored ${k.name}.md from git${c.reset}`)}catch{console.log(`${c.red}Could not undo \u2014 not tracked in git or no prior version${c.reset}`)}return!0}default:{let p=s();if(p.length===0)console.log(`
|
|
1227
1227
|
${c.bold}${c.cyan}Brain Knowledge Base${c.reset}`),console.log(`${c.dim}No documents yet. Create with /brain add <name>${c.reset}`),console.log(`
|
|
1228
1228
|
${c.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${c.reset}
|
|
1229
1229
|
`);else{console.log(`
|
|
1230
|
-
${c.bold}${c.cyan}Brain: ${p.length} document(s)${c.reset}`);for(let g of p){let{frontmatter:
|
|
1230
|
+
${c.bold}${c.cyan}Brain: ${p.length} document(s)${c.reset}`);for(let g of p){let{frontmatter:y}=r(g.name),w=Array.isArray(y.tags)?` [${y.tags.join(", ")}]`:"";console.log(` ${c.cyan}${g.name}${c.reset}${c.dim}${w}${c.reset}`)}console.log(`
|
|
1231
1231
|
${c.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${c.reset}
|
|
1232
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:s,learnBrainFromSession:r}=Wa(),{getConversationMessages:i}=Se(),a=i(),l=a.filter(u=>u.role==="user").length;if(l<4)return console.log(`${c.yellow}Session too short to learn from (need 4+ user messages, have ${l})${c.reset}`),!0;console.log(`${c.dim}Analyzing session for learnings...${c.reset}`);try{let[u,d]=await Promise.all([s(a),r(a)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${c.dim}Session too short${c.reset}`),!0;u.error&&console.log(`${c.red}Reflection error: ${u.error}${c.reset}`),console.log(""),u.summary&&(console.log(`${c.bold}Session:${c.reset} ${c.dim}${u.summary}${c.reset}`),console.log(""));let f=u.applied&&u.applied.length>0,m=u.nexAdded&&u.nexAdded.length>0,h=d.written&&d.written.length>0;if(!f&&!m&&!h)console.log(`${c.dim}No new learnings extracted from this session${c.reset}`);else{if(f){console.log(`${c.bold}${c.cyan}Memory updates:${c.reset}`);for(let{key:p,value:g,action:
|
|
1232
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:s,learnBrainFromSession:r}=Wa(),{getConversationMessages:i}=Se(),a=i(),l=a.filter(u=>u.role==="user").length;if(l<4)return console.log(`${c.yellow}Session too short to learn from (need 4+ user messages, have ${l})${c.reset}`),!0;console.log(`${c.dim}Analyzing session for learnings...${c.reset}`);try{let[u,d]=await Promise.all([s(a),r(a)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${c.dim}Session too short${c.reset}`),!0;u.error&&console.log(`${c.red}Reflection error: ${u.error}${c.reset}`),console.log(""),u.summary&&(console.log(`${c.bold}Session:${c.reset} ${c.dim}${u.summary}${c.reset}`),console.log(""));let f=u.applied&&u.applied.length>0,m=u.nexAdded&&u.nexAdded.length>0,h=d.written&&d.written.length>0;if(!f&&!m&&!h)console.log(`${c.dim}No new learnings extracted from this session${c.reset}`);else{if(f){console.log(`${c.bold}${c.cyan}Memory updates:${c.reset}`);for(let{key:p,value:g,action:y}of u.applied){let w=y==="updated"?`${c.yellow}~${c.reset}`:`${c.green}+${c.reset}`;console.log(` ${w} ${c.bold}${p}${c.reset} = ${g}`)}}if(m){console.log(`${c.bold}${c.cyan}Added to NEX.md:${c.reset}`);for(let p of u.nexAdded)console.log(` ${c.green}+${c.reset} ${p}`)}if(h){console.log(`${c.bold}${c.cyan}Brain documents:${c.reset}`);for(let{name:p,reason:g,action:y}of d.written){let w=y==="updated"?`${c.yellow}~${c.reset}`:`${c.green}+${c.reset}`;console.log(` ${w} ${c.bold}${p}.md${c.reset}${g?c.dim+" \u2014 "+g+c.reset:""}`)}}}console.log("")}catch(u){console.log(`${c.red}Learn failed: ${u.message}${c.reset}`)}return!0}case"/optimize":{let{getConversationMessages:s}=Se(),{getUsage:r}=Qe(),{TOOL_DEFINITIONS:i}=Et(),{listMemories:a}=rn(),l=s(),u=r(l,i),d=Yt(),f=Cn(),m=a();console.log(`
|
|
1233
1233
|
${c.bold}${c.cyan}Optimization Report${c.reset}
|
|
1234
1234
|
`);let h=u.percentage>80?c.red:u.percentage>50?c.yellow:c.green;if(console.log(`${c.bold}Context Window:${c.reset} ${h}${u.percentage}%${c.reset} used (${u.used.toLocaleString()} / ${u.limit.toLocaleString()} tokens)`),u.percentage>75?console.log(` ${c.yellow}\u2192 Tip: Use /clear to free context (auto-learns first)${c.reset}`):u.percentage>50?console.log(` ${c.dim}\u2192 Context is filling up, consider /clear soon${c.reset}`):console.log(` ${c.green}\u2192 Context healthy${c.reset}`),console.log(`
|
|
1235
|
-
${c.bold}Memory:${c.reset} ${m.length} entries`),m.length===0)console.log(` ${c.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${c.reset}`);else{let R=[...m].sort((b,A)=>new Date(A.updatedAt)-new Date(b.updatedAt))[0],
|
|
1236
|
-
${c.bold}Active Model:${c.reset} ${f}:${d.id}`);let p=d.contextWindow||d.maxTokens||0;p>0&&p<32e3&&l.length>10?console.log(` ${c.yellow}\u2192 Small context window (${(p/1e3).toFixed(0)}k). Consider /model for larger context${c.reset}`):p>=128e3&&console.log(` ${c.green}\u2192 Large context window (${(p/1e3).toFixed(0)}k) \u2014 good for long sessions${c.reset}`);let g=l.filter(
|
|
1237
|
-
${c.bold}Session:${c.reset} ${g} turns, ${l.length} messages total`),g>=4&&g%10===0&&console.log(` ${c.cyan}\u2192 Good time to /learn and capture session insights${c.reset}`);let
|
|
1238
|
-
${c.bold}Quick Wins:${c.reset}`);for(let
|
|
1235
|
+
${c.bold}Memory:${c.reset} ${m.length} entries`),m.length===0)console.log(` ${c.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${c.reset}`);else{let R=[...m].sort((b,A)=>new Date(A.updatedAt)-new Date(b.updatedAt))[0],x=R?Math.round((Date.now()-new Date(R.updatedAt))/6e4):null,_=x!==null?x<60?`${x}m ago`:`${Math.round(x/60)}h ago`:"?";console.log(` ${c.dim}Latest update: ${_}${c.reset}`),m.length>30&&console.log(` ${c.yellow}\u2192 Many memories (${m.length}) \u2014 consider pruning with /forget${c.reset}`)}console.log(`
|
|
1236
|
+
${c.bold}Active Model:${c.reset} ${f}:${d.id}`);let p=d.contextWindow||d.maxTokens||0;p>0&&p<32e3&&l.length>10?console.log(` ${c.yellow}\u2192 Small context window (${(p/1e3).toFixed(0)}k). Consider /model for larger context${c.reset}`):p>=128e3&&console.log(` ${c.green}\u2192 Large context window (${(p/1e3).toFixed(0)}k) \u2014 good for long sessions${c.reset}`);let g=l.filter(k=>k.role==="user").length;console.log(`
|
|
1237
|
+
${c.bold}Session:${c.reset} ${g} turns, ${l.length} messages total`),g>=4&&g%10===0&&console.log(` ${c.cyan}\u2192 Good time to /learn and capture session insights${c.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(`
|
|
1238
|
+
${c.bold}Quick Wins:${c.reset}`);for(let k of y)console.log(` ${c.cyan}\u2192${c.reset} ${k}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:s,approvePlan:r,startExecution:i,setPlanMode:a,getPlanContent:l,getPlanContent:u,formatPlan:d,extractStepsFromText:f,createPlan:m}=It(),{invalidateSystemPromptCache:h}=Se(),p=o.join(" ").trim();if(p==="status"){let g=s();return console.log(d(g)),!0}if(p==="edit"){let g=l();if(!g)return console.log(`${c.yellow}No plan to edit. Generate a plan first with /plan${c.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 k=process.env.EDITOR||process.env.VISUAL||"nano",{spawnSync:R}=require("child_process");if(console.log(`${c.dim}Opening plan in ${k}... (save and close to update)${c.reset}`),R(k,[w],{stdio:"inherit"}).status===0){let{setPlanContent:_}=It(),b=require("fs").readFileSync(w,"utf-8");_(b);let A=f(b);if(A.length>0){let P=s()?.task||"Task";m(P,A),console.log(`${c.green}Plan updated \u2014 ${A.length} steps extracted.${c.reset}`)}else console.log(`${c.green}Plan updated.${c.reset}`)}else console.log(`${c.yellow}Editor exited with error \u2014 plan unchanged.${c.reset}`);try{require("fs").unlinkSync(w)}catch{}return!0}if(p==="approve"){let g=l();if(r()){i(),a(!1),eo(),h();let w=s()?.steps?.length||0,k=w>0?` (${w} steps)`:"";if(console.log(`${c.green}${c.bold}Plan approved!${c.reset}${k} Executing...`),console.log(`${c.dim}Plan mode disabled \u2014 all tools now available.${c.reset}`),g){let{processInput:R}=Se(),x=`[PLAN APPROVED \u2014 EXECUTE NOW]
|
|
1239
1239
|
|
|
1240
1240
|
Implement the following plan step by step. All tools are now available.
|
|
1241
1241
|
|
|
1242
|
-
${g}`;try{await R(
|
|
1242
|
+
${g}`;try{await R(x)}catch(_){console.log(`${c.red}Error: ${_.message?.split(`
|
|
1243
1243
|
`)[0]}${c.reset}`)}}}else console.log(`${c.red}No plan to approve. Enter plan mode first with /plan${c.reset}`);return!0}return a(!0),eo(),h(),console.log(`
|
|
1244
1244
|
${c.cyan}${c.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${c.reset}
|
|
1245
1245
|
${c.cyan}${c.bold}\u2502${c.reset} Analysis only \u2014 no file changes until approved ${c.cyan}${c.bold}\u2502${c.reset}
|
|
@@ -1319,8 +1319,8 @@ ${c.bold}${c.cyan}Kubernetes Overview${c.reset}${l?c.dim+" (remote: "+l+")"+c.re
|
|
|
1319
1319
|
`);try{let{stdout:f}=await a(d("kubectl get namespaces --no-headers -o custom-columns=NAME:.metadata.name"),{timeout:15e3}),m=f.trim().split(`
|
|
1320
1320
|
`).filter(Boolean);console.log(`${c.bold}Namespaces (${m.length}):${c.reset}`);for(let h of m)console.log(` ${c.cyan}${h}${c.reset}`);console.log()}catch{return console.log(`${c.dim}Could not reach cluster \u2014 is kubectl configured?${c.reset}
|
|
1321
1321
|
`),!0}try{let{stdout:f}=await a(d("kubectl get pods -A --no-headers -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,READY:.status.containerStatuses[0].ready,STATUS:.status.phase,RESTARTS:.status.containerStatuses[0].restartCount"),{timeout:2e4}),m=f.trim().split(`
|
|
1322
|
-
`).filter(Boolean),h=m.filter(
|
|
1323
|
-
`);let
|
|
1322
|
+
`).filter(Boolean),h=m.filter(w=>w.includes("Running")).length,p=m.filter(w=>w.includes("Pending")).length,g=m.filter(w=>w.includes("Failed")||w.includes("Error")||w.includes("CrashLoop")).length;console.log(`${c.bold}Pods: ${m.length} total ${c.green}${h} running${c.reset} ${c.yellow}${p} pending${c.reset} ${c.red}${g} unhealthy${c.reset}
|
|
1323
|
+
`);let y=m.filter(w=>!w.includes("Running")&&!w.includes("<none>"));if(y.length>0){console.log(`${c.bold}${c.red}Unhealthy Pods:${c.reset}`);for(let w of y)console.log(` ${c.red}${w}${c.reset}`);console.log()}console.log(`${c.dim}Use k8s_pods / k8s_logs / k8s_exec tools for details${c.reset}`),console.log(`${c.dim}Or: /k8s user@host to query a remote cluster${c.reset}
|
|
1324
1324
|
`)}catch(f){console.log(`${c.dim}Could not list pods: ${f.message}${c.reset}
|
|
1325
1325
|
`)}return!0}case"/servers":{let{loadServerProfiles:s,resolveProfile:r,sshExec:i}=Gn(),a=s(),l=Object.keys(a);if(l.length===0)return console.log(`
|
|
1326
1326
|
${c.dim}No servers configured. Create .nex/servers.json:${c.reset}`),console.log(`${c.dim} { "prod": { "host": "1.2.3.4", "user": "jarvis", "os": "almalinux9" } }${c.reset}
|
|
@@ -1329,38 +1329,38 @@ ${c.bold}${c.cyan}Server connectivity:${c.reset}`),await Promise.all(f.map(async
|
|
|
1329
1329
|
${c.bold}${c.cyan}Configured servers (${l.length}):${c.reset}`);for(let f of l)console.log(` ${c.green}${f}${c.reset} ${c.dim}${d(f,a[f])}${c.reset}`);return console.log(`
|
|
1330
1330
|
${c.dim}/servers ping \u2014 check SSH connectivity for all servers${c.reset}`),console.log(`${c.dim}/servers ping <name> \u2014 check a specific server${c.reset}
|
|
1331
1331
|
`),!0}case"/docker":{let{loadServerProfiles:s,sshExec:r}=Gn(),{exec:i}=require("child_process"),{promisify:a}=require("util"),l=a(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(`
|
|
1332
|
-
${c.bold}${c.cyan}Docker Containers:${c.reset}`);for(let[m,h]of f){let p=m==="local"?`${c.dim}local${c.reset}`:`${c.cyan}${m}${c.reset}`;try{let g;if(m==="local"){let{stdout:
|
|
1333
|
-
`).forEach(
|
|
1332
|
+
${c.bold}${c.cyan}Docker Containers:${c.reset}`);for(let[m,h]of f){let p=m==="local"?`${c.dim}local${c.reset}`:`${c.cyan}${m}${c.reset}`;try{let g;if(m==="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(` ${p}: ${c.red}SSH error (${y.exitCode})${c.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${p}: ${c.dim}(no containers)${c.reset}`):(console.log(` ${p}:`),g.split(`
|
|
1333
|
+
`).forEach(y=>console.log(` ${c.dim}${y}${c.reset}`)))}catch(g){console.log(` ${p}: ${c.red}${g.message}${c.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:s}=Li(),r=s(),i=Object.keys(r),a=o[0];if(a&&i.includes(a)){let l=o.includes("--dry-run")||o.includes("-n"),u=r[a],{executeTool:d}=Et();console.log(`
|
|
1334
1334
|
${c.bold}Running deploy: ${a}${l?" (dry run)":""}${c.reset}`);let f=await d("deploy",{...u,dry_run:l});return console.log(f),!0}if(i.length===0)return console.log(`
|
|
1335
1335
|
${c.dim}No deploy configs. Run /init to create .nex/deploy.json${c.reset}
|
|
1336
1336
|
`),!0;console.log(`
|
|
1337
1337
|
${c.bold}${c.cyan}Deploy configs (${i.length}):${c.reset}`);for(let[l,u]of Object.entries(r)){let d=u.method||"rsync",f=`[${d}]`,m=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(p=>` ${c.dim}\u2192 ${p}${c.reset}`).join("");console.log(` ${c.green}${l}${c.reset} ${c.dim}${f} ${m}${c.reset}${h}`)}return console.log(`
|
|
1338
1338
|
${c.dim}/deploy <name> \u2014 run a named deploy${c.reset}`),console.log(`${c.dim}/deploy <name> --dry-run \u2014 preview without syncing${c.reset}
|
|
1339
|
-
`),!0}case"/init":{let{runServerWizard:s,runDeployWizard:r,setWizardRL:i}=kp();return i(e),o[0]==="deploy"?await r():await s(),!0}case"/setup":{let{runSetupWizard:s}=qa();return await s({rl:e,force:!0}),!0}case"/benchmark":{if(o.includes("--history")){let
|
|
1340
|
-
${c.bold}${c.cyan}OpenClaw Nightly Results (${
|
|
1341
|
-
`),console.log(` ${c.dim}${"Date".padEnd(12)} ${"Model".padEnd(25)} ${"Score".padEnd(8)} ${"Pass".padEnd(8)}${c.reset}`),console.log(` ${c.dim}${"\u2500".repeat(58)}${c.reset}`);let R=[];for(let
|
|
1342
|
-
${c.bold}Trend:${c.reset} ${A}${c.reset} over ${R.length} days`)}}console.log();break}if(o.includes("--discover")){let{findNewModels:w,
|
|
1343
|
-
${c.bold}Checking Ollama Cloud for new models...${c.reset}`);let b;try{b=await
|
|
1339
|
+
`),!0}case"/init":{let{runServerWizard:s,runDeployWizard:r,setWizardRL:i}=kp();return i(e),o[0]==="deploy"?await r():await s(),!0}case"/setup":{let{runSetupWizard:s}=qa();return await s({rl:e,force:!0}),!0}case"/benchmark":{if(o.includes("--history")){let y=require("os"),w=He.join(y.homedir(),"Coding","nex-code-benchmarks","results");if(!st.existsSync(w)){console.log(`${c.yellow}No nightly results at ${w}${c.reset}`),console.log(`${c.dim}Use /benchmark (no flags) to run a live model comparison.${c.reset}`);break}let k=st.readdirSync(w).filter(x=>x.endsWith(".json")).sort().slice(-7);if(k.length===0){console.log(`${c.yellow}No result files found${c.reset}`);break}console.log(`
|
|
1340
|
+
${c.bold}${c.cyan}OpenClaw Nightly Results (${k.length}-day trend)${c.reset}
|
|
1341
|
+
`),console.log(` ${c.dim}${"Date".padEnd(12)} ${"Model".padEnd(25)} ${"Score".padEnd(8)} ${"Pass".padEnd(8)}${c.reset}`),console.log(` ${c.dim}${"\u2500".repeat(58)}${c.reset}`);let R=[];for(let x of k)try{let _=JSON.parse(st.readFileSync(He.join(w,x),"utf-8")),b=x.replace(".json",""),A=_.tasks?.length||_.total||0,O=_.tasks?.filter(xe=>xe.passed||xe.score>=.7)?.length||_.passed||0,P=_.score??_.overall_score??(A>0?Math.round(O/A*100):"N/A"),D=_.model||_.config?.model||"unknown";R.push({date:b,model:D,total:A,passed:O,score:P});let Me=typeof P=="number"?P>=80?c.green:P>=60?c.yellow:c.red:c.dim;console.log(` ${b.padEnd(12)} ${D.substring(0,24).padEnd(25)} ${Me}${String(P).padEnd(8)}${c.reset} ${O}/${A}`)}catch{}if(R.length>=2){let x=R[0].score,_=R[R.length-1].score;if(typeof x=="number"&&typeof _=="number"){let b=_-x,A=b>0?`${c.green}\u25B2 +${b}`:b<0?`${c.red}\u25BC ${b}`:`${c.dim}\u2192 stable`;console.log(`
|
|
1342
|
+
${c.bold}Trend:${c.reset} ${A}${c.reset} over ${R.length} days`)}}console.log();break}if(o.includes("--discover")){let{findNewModels:y,markBenchmarked:w,updateReadme:k,updateModelsEnv:R}=Tr(),{runDiscoverBenchmark:x,buildSummary:_}=Rn();console.log(`
|
|
1343
|
+
${c.bold}Checking Ollama Cloud for new models...${c.reset}`);let b;try{b=await y()}catch(H){console.log(`${c.red}Discovery failed: ${H.message}${c.reset}`);break}let{newModels:A,allCloud:O}=b;if(console.log(`${c.dim}${O.length} models available on cloud${c.reset}`),A.length===0){console.log(`${c.green}No new models since last benchmark run.${c.reset}
|
|
1344
1344
|
`);break}console.log(`${c.cyan}New models to benchmark (${A.length}):${c.reset} ${A.join(", ")}
|
|
1345
|
-
`);let
|
|
1345
|
+
`);let P=require("os"),D=He.join(P.homedir(),".nex-code","benchmark-results.json"),Me=[];try{st.existsSync(D)&&(Me=JSON.parse(st.readFileSync(D,"utf-8")))}catch{}let xe="",de=await x({newModels:A,existingRanking:Me,onProgress:({model:H,task:ne,done:I,score:F,error:se})=>{if(!I){H!==xe&&(xe&&process.stdout.write(`
|
|
1346
1346
|
`),xe=H,process.stdout.write(`${c.cyan}${H}${c.reset} `));return}let z=se?`${c.red}\u2717${c.reset}`:F>=80?`${c.green}\xB7${c.reset}`:F>=40?`${c.yellow}\xB7${c.reset}`:`${c.red}\xB7${c.reset}`;process.stdout.write(z)}});xe&&process.stdout.write(`
|
|
1347
|
-
`);try{st.writeFileSync(
|
|
1347
|
+
`);try{st.writeFileSync(D,JSON.stringify(de,null,2))}catch{}w(O);let fe=He.join(process.cwd(),"README.md"),ae=k(de,fe),be=R(de),{buildCategoryWinners:te}=Rn(),{updateRoutingConfig:E}=Tr(),M=te(de),W=E(M);if(ae&&console.log(`${c.green}README.md benchmark table updated${c.reset}`),be.updated?console.log(`${c.green}DEFAULT_MODEL: ${be.previousModel} \u2192 ${be.newModel}${c.reset}`):be.reason&&console.log(`${c.dim}models.env unchanged: ${be.reason}${c.reset}`),W.changes.length>0){console.log(`${c.green}Routing updated:${c.reset}`);for(let H of W.changes)console.log(` ${c.dim}${H}${c.reset}`)}return console.log(),!0}let{runBenchmark:s,DEFAULT_MODELS:r,QUICK_MODELS:i}=Rn(),a=o.includes("--quick"),l=o.find(y=>y.startsWith("--models=")),u=l?l.replace("--models=","").split(",").map(y=>y.trim()).filter(Boolean):[],d=a?7:15,f=u.length>0?u:a?i:r;console.log(`
|
|
1348
1348
|
${c.bold}Starting benchmark${c.reset} ${c.dim}${d} tasks \xB7 ${f.length} models \xB7 ollama cloud${c.reset}`),console.log(`${c.dim}Models: ${f.join(", ")}${c.reset}
|
|
1349
|
-
`);let m="",h=0,p=d*f.length,g=await s({models:f,quick:a,onProgress:({model:w,
|
|
1350
|
-
`),m=
|
|
1351
|
-
`),!a&&g&&g.length>0){let{buildCategoryWinners:
|
|
1352
|
-
${c.bold}Per-category routing saved:${c.reset}`);for(let
|
|
1349
|
+
`);let m="",h=0,p=d*f.length,g=await s({models:f,quick:a,onProgress:({model:y,task:w,done:k,score:R,error:x})=>{if(!k){y!==m&&(m&&process.stdout.write(`
|
|
1350
|
+
`),m=y,process.stdout.write(`${c.cyan}${y}${c.reset} `));return}h++;let _=x?`${c.red}\u2717${c.reset}`:R>=80?`${c.green}\xB7${c.reset}`:R>=40?`${c.yellow}\xB7${c.reset}`:`${c.red}\xB7${c.reset}`;process.stdout.write(_)}});if(m&&process.stdout.write(`
|
|
1351
|
+
`),!a&&g&&g.length>0){let{buildCategoryWinners:y}=Rn(),{updateRoutingConfig:w,updateReadme:k,updateModelsEnv:R}=Tr(),x=y(g),_=w(x);if(_.changes.length>0){console.log(`
|
|
1352
|
+
${c.bold}Per-category routing saved:${c.reset}`);for(let P of _.changes)console.log(` ${c.dim}${P}${c.reset}`)}let b=He.join(process.cwd(),"README.md");k(g,b)&&console.log(`${c.green}README.md updated${c.reset}`),R(g);let A=require("os"),O=He.join(A.homedir(),".nex-code","benchmark-results.json");try{st.writeFileSync(O,JSON.stringify(g,null,2))}catch{}}return!0}case"/bench":{let{runJarvisBenchmark:s}=Rn(),r=o.includes("--dry-run"),i=o.find(l=>l.startsWith("--model=")),a=i?i.replace("--model=","").trim():void 0;return r||console.log(`
|
|
1353
1353
|
${c.bold}Jarvis Benchmark${c.reset} ${c.dim}5 agentic scenarios \xB7 each run as child process${c.reset}
|
|
1354
1354
|
`),await s({dryRun:r,model:a,cwd:St,onProgress:({id:l,name:u,done:d,score:f,grade:m})=>{if(!d)process.stdout.write(`${c.dim} \u2192 ${u}...${c.reset}`);else{let h=f>=8?c.green:f>=6?c.yellow:c.red;process.stdout.write(` ${h}${f}/10 (${m})${c.reset}
|
|
1355
1355
|
`)}}}),!0}case"/trend":{let{showScoreTrend:s}=Rn(),r=parseInt(o[0],10)||10;return s(r),!0}case"/orchestrate":{let s=o.join(" ").trim();if(!s)return console.log(`${c.yellow}Usage: /orchestrate <prompt>${c.reset}`),console.log(`${c.dim}Example: /orchestrate fix login bug, update docs, add dark mode${c.reset}`),!0;let{runOrchestrated:r}=qs();return await r(s),!0}case"/bench-orchestrator":{let{runOrchestratorBenchmark:s,printResults:r}=Yp(),i=o.find(u=>u.startsWith("--models=")),a=i?i.replace("--models=","").split(",").map(u=>u.trim()):void 0,l=await s({models:a,onProgress:({model:u,scenario:d,done:f,score:m,error:h})=>{f?h?process.stdout.write(` ${c.red}ERR${c.reset}
|
|
1356
1356
|
`):process.stdout.write(` ${c.green}${m}/10${c.reset}
|
|
1357
|
-
`):process.stdout.write(`${c.dim} \u2192 ${u}: ${d}...${c.reset}`)}});return r(l),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:if(Vx(t))return!0;{let s=[...no,...Nr()].map(l=>l.cmd.split(" ")[0]),r=(l,u)=>{let d=l.length,f=u.length,m=Array.from({length:d+1},(h,p)=>Array.from({length:f+1},(g,
|
|
1357
|
+
`):process.stdout.write(`${c.dim} \u2192 ${u}: ${d}...${c.reset}`)}});return r(l),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:if(Vx(t))return!0;{let s=[...no,...Nr()].map(l=>l.cmd.split(" ")[0]),r=(l,u)=>{let d=l.length,f=u.length,m=Array.from({length:d+1},(h,p)=>Array.from({length:f+1},(g,y)=>p===0?y:y===0?p:0));for(let h=1;h<=d;h++)for(let p=1;p<=f;p++)m[h][p]=l[h-1]===u[p-1]?m[h-1][p-1]:1+Math.min(m[h-1][p],m[h][p-1],m[h-1][p-1]);return m[d][f]},i=null,a=3;for(let l of s){let u=r(n,l);u<a&&(a=u,i=l)}console.log(i?`${c.red}Unknown command: ${n}.${c.reset} ${c.dim}Did you mean ${c.reset}${c.cyan}${i}${c.reset}${c.dim}? Type /help for all commands.${c.reset}`:`${c.red}Unknown command: ${n}. Type /help${c.reset}`)}return!0}}var nc=1e3;function sc(){return He.join(process.cwd(),".nex","repl_history")}function am(){try{let t=sc();if(st.existsSync(t))return st.readFileSync(t,"utf-8").split(`
|
|
1358
1358
|
`).filter(Boolean).slice(-nc)}catch{}return[]}function Or(t){try{let e=sc(),n=He.dirname(e);st.existsSync(n)||st.mkdirSync(n,{recursive:!0}),st.appendFileSync(e,t+`
|
|
1359
|
-
`)}catch{}}function wt(){return`${c.bold}${c.cyan}>${c.reset} `}function eo(){if(!global._nexFooter)return;let{isPlanMode:t,getAutonomyLevel:e}=It(),{getAutoConfirm:n}=Xe(),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 oc="\x1B[200~",rc="\x1B[201~";function nk(t){return typeof t=="string"&&t.includes(oc)}function sk(t){return typeof t=="string"&&t.includes(rc)}function to(t){return typeof t!="string"?t:t.split(oc).join("").split(rc).join("")}async function ok(){if(!Xx("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"),tc("local:llama3"),!0}catch{return!1}}async function rk(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:n}=Se();t(em);let s=ec().some(
|
|
1360
|
-
`),!0):!1)(),a=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:
|
|
1359
|
+
`)}catch{}}function wt(){return`${c.bold}${c.cyan}>${c.reset} `}function eo(){if(!global._nexFooter)return;let{isPlanMode:t,getAutonomyLevel:e}=It(),{getAutoConfirm:n}=Xe(),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 oc="\x1B[200~",rc="\x1B[201~";function nk(t){return typeof t=="string"&&t.includes(oc)}function sk(t){return typeof t=="string"&&t.includes(rc)}function to(t){return typeof t!="string"?t:t.split(oc).join("").split(rc).join("")}async function ok(){if(!Xx("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"),tc("local:llama3"),!0}catch{return!1}}async function rk(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:n}=Se();t(em);let s=ec().some(I=>I.configured),r=(async()=>{Jx();let I=Yt(),F=Cn();return{model:I,providerName:F}})(),i=(async()=>s?!0:await ok()?(console.log(`${c.green}\u2713 Local Ollama detected \u2014 using local models${c.reset}`),console.log(`${c.dim}Tip: Set API keys for cloud providers for more model options (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${c.reset}
|
|
1360
|
+
`),!0):!1)(),a=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:I}=Jp();return await I()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,i,a]);!u&&!s&&(console.error(`
|
|
1361
1361
|
${c.red}\u2717 No provider configured and no local Ollama detected.${c.reset}
|
|
1362
|
-
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:m}=Ft();f().then(
|
|
1363
|
-
${z}\x1B[33m\u2753${se} ${z}${
|
|
1362
|
+
`),process.exit(1));let{loadPersistedHistory:f,pruneHistory:m}=Ft();f().then(I=>{}),m().catch(()=>{});let h=am(),p=Hx.createInterface({input:process.stdin,output:process.stdout,prompt:wt(),completer:sm,history:h,historySize:nc});Qx(p);let{setAskUserHandler:g}=Et();g(async(I,F)=>{let se="\x1B[0m",z="\x1B[1m",Q="\x1B[2m",pe="\x1B[36m";return process.stdout.write(`
|
|
1363
|
+
${z}\x1B[33m\u2753${se} ${z}${I}${se}
|
|
1364
1364
|
|
|
1365
1365
|
`),F.forEach(($e,ye)=>{process.stdout.write(` ${pe}${ye+1}${se} ${$e}
|
|
1366
1366
|
`)}),process.stdout.write(` ${Q}${F.length+1}${se} ${Q}Eigene Antwort\u2026${se}
|
|
@@ -1368,25 +1368,25 @@ ${c.red}\u2717 No provider configured and no local Ollama detected.${c.reset}
|
|
|
1368
1368
|
${pe}[1-${F.length+1}]${se} \u203A `),new Promise($e=>{p.resume(),p.once("line",ye=>{let je=ye.trim(),Ge=parseInt(je);Ge>=1&&Ge<=F.length?(process.stdout.write(`
|
|
1369
1369
|
`),$e(F[Ge-1])):Ge===F.length+1||je===""?(process.stdout.write(` ${pe}\u203A${se} `),p.once("line",zt=>{process.stdout.write(`
|
|
1370
1370
|
`),$e(zt.trim()||"")})):(process.stdout.write(`
|
|
1371
|
-
`),$e(je))})})});let
|
|
1372
|
-
`),await Zp(St);let
|
|
1373
|
-
${c.yellow} Task cancelled. Press Ctrl+C again to exit.${c.reset}`),
|
|
1374
|
-
`).replace(/\r/g,"").trim();if(O=[],A=!1,!
|
|
1375
|
-
`).length,z=se>1?`[Pasted content #${F} \u2014 ${se} lines]`:`[Pasted content #${F}]`,Q=p.line||"",pe=Q&&!Q.endsWith(" ")?" ":"",
|
|
1376
|
-
`)),xe()}if(Q){A=!0,O=[];let
|
|
1377
|
-
`)),!0}if(pe){let
|
|
1378
|
-
`)),xe()}if(A){let
|
|
1371
|
+
`),$e(je))})})});let y=new tk;y.activate(p),global._nexFooter=y,global._nexRawWrite=I=>y.rawWrite(I),ek(()=>eo()),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}`;Gx(w,St,{yolo:Qa()});{y.setStatusInfo({model:w,branch:"",project:He.basename(St)});let{execFile:I}=require("child_process");I("git",["rev-parse","--abbrev-ref","HEAD"],{encoding:"utf8"},(F,se)=>{!F&&se&&y.setStatusInfo({model:w,branch:se.trim(),project:He.basename(St)})})}d.hasNewVersion&&console.log(`${c.yellow}\u{1F4A1} New version available!${c.reset} Run ${c.cyan}npm update -g nex-code${c.reset} to upgrade from ${c.dim}${d.currentVersion}${c.reset} to ${c.green}${d.latestVersion}${c.reset}
|
|
1372
|
+
`),await Zp(St);let k=!1,R=0,x=!1,_=null;function b(){Qp(),y.deactivate(),Vp(),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",b),process.on("exit",()=>{Qp()}),p.on("SIGINT",()=>{if(Vp(),R++,R>=2){b();return}if(k){Kt&&Kt.abort();let{cancelPendingAskUser:I}=Et();I(),console.log(`
|
|
1373
|
+
${c.yellow} Task cancelled. Press Ctrl+C again to exit.${c.reset}`),k=!1,p.setPrompt(wt()),p.prompt()}else console.log(`${c.dim} (Press Ctrl+C again to exit)${c.reset}`),p.setPrompt(wt()),p.prompt(),_&&clearTimeout(_),_=setTimeout(()=>{R=0,_=null},2e3)}),process.on("SIGINT",()=>{process.stdin.isTTY?(R++,R>=2&&b()):b()});let A=!1,O=[],P=0,D={},Me=!1;function xe(){let I=O.join(`
|
|
1374
|
+
`).replace(/\r/g,"").trim();if(O=[],A=!1,!I)return!0;P++,Me=!0;let F=P;D[F]=I;let se=I.split(`
|
|
1375
|
+
`).length,z=se>1?`[Pasted content #${F} \u2014 ${se} lines]`:`[Pasted content #${F}]`,Q=p.line||"",pe=Q&&!Q.endsWith(" ")?" ":"",ue=Q+pe+z;return p.setPrompt(wt()),p.prompt(),p.line=ue,p.cursor=ue.length,p._refreshLine(),!0}function de(I){return I.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(F,se)=>D[Number(se)]||"")}function fe(){P=0,D={},Me=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let I=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(F,...se){if(F!=="data")return I.call(process.stdin,F,...se);let z=se[0];if(Buffer.isBuffer(z)&&(z=z.toString("utf8")),typeof z!="string")return I.call(process.stdin,F,...se);let Q=z.includes(oc),pe=z.includes(rc);if(Q&&pe){let ue=to(z);return ue&&O.push(...ue.split(`
|
|
1376
|
+
`)),xe()}if(Q){A=!0,O=[];let ue=to(z);return ue&&O.push(...ue.split(`
|
|
1377
|
+
`)),!0}if(pe){let ue=to(z);return ue&&O.push(...ue.split(`
|
|
1378
|
+
`)),xe()}if(A){let ue=to(z);return ue&&O.push(...ue.split(`
|
|
1379
1379
|
`)),!0}return z.includes(`
|
|
1380
1380
|
`)&&z.length>40&&!A?(O.push(...z.replace(/\r/g,"").split(`
|
|
1381
|
-
`)),xe()):
|
|
1382
|
-
${Q}. `).trim()}let{loadSession:H}=Ct(),{setConversationMessages:ne}=Se();if(e()===0){let
|
|
1383
|
-
`),p.prompt()}return}if(E!==null){if(E._mode==="triple"){if(
|
|
1384
|
-
`).trim();if(E=null,Q){Or(Q.replace(/\n/g,"\\n")),
|
|
1385
|
-
`)[0]||"An unexpected error occurred";console.log(`${c.red}Error: ${$e}${c.reset}`)}}
|
|
1386
|
-
`).trim();if(E=null,Q){Or(Q.replace(/\n/g,"\\n")),
|
|
1387
|
-
`)[0]||"An unexpected error occurred";console.log(`${c.red}Error: ${ye}${c.reset}`)}}let{getConversationLength:pe}=Se();
|
|
1388
|
-
`).forEach(($e,ye)=>{let je=ye===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",Ge=2+$e.length,zt=" ".repeat(Math.max(0,pe-Ge));console.log(`${Q}${je} ${$e}${zt}\x1B[0m`)})}if(process.env.NEX_AUTO_PLAN!=="0"&&!Qa()){let{isPlanMode:Q,setPlanMode:pe}=It(),{invalidateSystemPromptCache:
|
|
1389
|
-
`)[0]||"An unexpected error occurred";console.log(`${c.red}Error: ${pe}${c.reset}`)}}
|
|
1381
|
+
`)),xe()):I.call(process.stdin,F,...se)}}let ae=0;function be(){if(ae>0){let I=y._scrollEnd,F="\x1B7";for(let se=0;se<ae;se++)F+=`\x1B[${I-ae+1+se};1H\x1B[2K`;F+="\x1B8",y.rawWrite(F),ae=0}}function te(I){let F=[...no,...Nr()].filter(ye=>ye.cmd.startsWith(I));if(!F.length||F.length===1&&F[0].cmd===I)return;let se=y._scrollEnd,z=Math.min(10,se-2);if(z<1)return;let Q=F.slice(0,z),pe=Math.max(...Q.map(ye=>ye.cmd.length));ae=Q.length,F.length>z&&ae++;let ue=se-ae+1,$e="\x1B7";for(let ye=0;ye<Q.length;ye++){let{cmd:je,desc:Ge}=Q[ye],zt=je.substring(0,I.length),An=je.substring(I.length),Mr=" ".repeat(Math.max(0,pe-je.length+2));$e+=`\x1B[${ue+ye};1H\x1B[2K ${c.cyan}${zt}${c.reset}${c.dim}${An}${Mr}${Ge}${c.reset}`}F.length>z&&($e+=`\x1B[${ue+Q.length};1H\x1B[2K ${c.dim}\u2026 +${F.length-z} more${c.reset}`),$e+="\x1B8",y.rawWrite($e)}process.stdin.isTTY&&process.stdin.on("keypress",(I,F)=>{be(),!(F&&(F.name==="tab"||F.name==="return"))&&setImmediate(()=>{p.line&&p.line.startsWith("/")&&te(p.line)})});let E=null,M=`${c.dim}...${c.reset} `;function W(I){return(I.match(/[^\s\d](\d{1,2})\.\s+\S/g)||[]).length<2?I:I.replace(/([^\s\d])(\d{1,2})\.\s+/g,(se,z,Q)=>`${z}
|
|
1382
|
+
${Q}. `).trim()}let{loadSession:H}=Ct(),{setConversationMessages:ne}=Se();if(e()===0){let I=H("_autosave");if(I&&I.messages&&I.messages.length>0&&Date.now()-new Date(I.updatedAt).getTime()<1440*60*1e3){let{confirm:se}=Xe();if(await se("Previous session found. Resume?")){let pe=I.messages,ue=pe.length>20?pe.slice(-20):pe;ne(ue);let{getUsage:$e,forceCompress:ye}=Qe();if($e(ue,[]).percentage>=30){let{messages:Ge}=ye(ue,[]);ne(Ge)}}}}p.setPrompt(wt()),p.prompt(),p.on("line",async I=>{if(be(),Object.keys(D).length>0&&(I=de(I),fe(),p.setPrompt(wt())),k){let Q=I.trim();if(Q){let{injectMidRunNote:pe}=Se();pe(Q),process.stdout.write(`${c.cyan} \u270E Queued \u2014 will be applied in the next step${c.reset}
|
|
1383
|
+
`),p.prompt()}return}if(E!==null){if(E._mode==="triple"){if(I.trim()==='"""'){let Q=E.join(`
|
|
1384
|
+
`).trim();if(E=null,Q){Or(Q.replace(/\n/g,"\\n")),k=!0,p.prompt(),R=0,x=!1,_&&(clearTimeout(_),_=null),Kt=new AbortController;try{await n(Q)}catch(ue){if(!Kt?.signal?.aborted){let $e=ue.message?.split(`
|
|
1385
|
+
`)[0]||"An unexpected error occurred";console.log(`${c.red}Error: ${$e}${c.reset}`)}}k=!1;let pe=se();pe>0&&process.stdout.write(`${c.gray}[${pe} messages] ${c.reset}`)}p.setPrompt(wt()),p.prompt();return}E.push(I),p.setPrompt(M),p.prompt();return}if(I.endsWith("\\"))E.push(I.slice(0,-1));else{E.push(I);let Q=E.join(`
|
|
1386
|
+
`).trim();if(E=null,Q){Or(Q.replace(/\n/g,"\\n")),k=!0,p.prompt(),R=0,x=!1,_&&(clearTimeout(_),_=null),Kt=new AbortController;try{await n(Q)}catch($e){if(!Kt?.signal?.aborted){let ye=$e.message?.split(`
|
|
1387
|
+
`)[0]||"An unexpected error occurred";console.log(`${c.red}Error: ${ye}${c.reset}`)}}let{getConversationLength:pe}=Se();k=!1;let ue=pe();ue>0&&process.stdout.write(`${c.gray}[${ue} messages] ${c.reset}`)}p.setPrompt(wt()),p.prompt();return}p.setPrompt(M),p.prompt();return}if(I.trim()==='"""'||I.trim().startsWith('"""')){let Q=I.trim().substring(3);E=Q?[Q]:[],E._mode="triple",p.setPrompt(M),p.prompt();return}if(I.endsWith("\\")){E=[I.slice(0,-1)],E._mode="backslash",p.setPrompt(M),p.prompt();return}let F=W(I.trim());if(!F){p.setPrompt(wt()),p.prompt();return}if(Or(F),F==="/"){tm(),p.setPrompt(wt()),p.prompt();return}if(F.startsWith("/")){await im(F,p),p.setPrompt(wt()),p.prompt();return}{let Q=Kx?"\x1B[48;5;237m":"\x1B[48;2;220;225;235m",pe=process.stdout.columns||80;F.split(`
|
|
1388
|
+
`).forEach(($e,ye)=>{let je=ye===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",Ge=2+$e.length,zt=" ".repeat(Math.max(0,pe-Ge));console.log(`${Q}${je} ${$e}${zt}\x1B[0m`)})}if(process.env.NEX_AUTO_PLAN!=="0"&&!Qa()){let{isPlanMode:Q,setPlanMode:pe}=It(),{invalidateSystemPromptCache:ue}=Se(),$e=/\b(implement|refactor|migrate|redesign)\b/i,ye=/\b(create|build|add|write|introduce|develop|set\s+up)\b/i,je=/^(how|what|why|when|where|which|explain|show|list|tell|describe|can\s+you|could\s+you|do\s+you)\b/i,Ge=/\b(spawn[_\s]?agents?|swarm)\b/i;!je.test(F)&&!Ge.test(F)&&($e.test(F)||ye.test(F)&&F.split(/\s+/).length>=5)&&!Q()&&(pe(!0),ue(),console.log(`${c.cyan}${c.bold}\u2387 Auto Plan Mode${c.reset}${c.dim} \u2014 implementation task detected \xB7 read-only until /plan approve${c.reset}`))}{let{getConversationLength:Q}=Se();if(Q()===0)try{let{detectCategory:pe,getModelForCategory:ue}=Ga(),$e=pe(F);if($e&&$e.id!=="coding"){let ye=ue($e.id),je=Yt();if(ye&&ye!==je?.id&&tc(ye)){let Ge=Yt();console.log(`${c.dim}\u21B3 ${$e.icon} ${$e.label} task \u2014 routing to ${Ge?.name||ye}${c.reset}`),global._nexFooter&&global._nexFooter.setStatusInfo({model:Ge?.name||ye})}}}catch{}}k=!0,p.prompt(),R=0,x=!1,_&&(clearTimeout(_),_=null),Kt=new AbortController;try{await n(F)}catch(Q){if(!Kt?.signal?.aborted){let pe=Q.message?.split(`
|
|
1389
|
+
`)[0]||"An unexpected error occurred";console.log(`${c.red}Error: ${pe}${c.reset}`)}}k=!1;let{getConversationLength:se}=Se(),z=se();z>0&&process.stdout.write(`${c.gray}[${z} messages] ${c.reset}`),p.setPrompt(wt()),p.prompt()}),p.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}cm.exports={startREPL:rk,getPrompt:wt,loadHistory:am,appendHistory:Or,getHistoryPath:sc,HISTORY_MAX:nc,showCommandList:tm,completer:sm,completeFilePath:nm,handleSlashCommand:im,showProviders:Za,showHelp:om,renderBar:rm,hasPasteStart:nk,hasPasteEnd:sk,stripPasteSequences:to,getAbortSignal:em}});var lc=require("path");require("dotenv").config({path:lc.join(__dirname,"..",".env")});require("dotenv").config();var ge=process.argv.slice(2);(ge.includes("--help")||ge.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
1390
1390
|
|
|
1391
1391
|
Options:
|
|
1392
1392
|
--task <prompt> Run a single task and exit (headless mode)
|