nex-code 0.3.35 → 0.3.37
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 +334 -312
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,138 +1,144 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var L=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Sn=L((Gg,Ll)=>{Ll.exports={name:"nex-code",version:"0.3.37",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 --coverage","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",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"}}});var Tr=L((zg,Er)=>{var M={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",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",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},kr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],vr=["\u273D","\u2726","\u2727","\u2726"],Es=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=kr[this.frame%kr.length],s="";if(this.startTime){let n=Math.floor((Date.now()-this.startTime)/1e3);if(n>=60){let o=Math.floor(n/60),i=n%60;s=` ${M.dim}${o}m ${String(i).padStart(2,"0")}s${M.reset}`}else n>=1&&(s=` ${M.dim}${n}s${M.reset}`)}process.stderr.write(`\x1B[2K\r${M.cyan}${e}${M.reset} ${M.dim}${this.text}${M.reset}${s}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),80))}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}},Sr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ts=class{constructor(e){this.labels=e,this.statuses=e.map(()=>"running"),this.frame=0,this.interval=null,this.startTime=null,this.lineCount=e.length}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_render(){if(this._stopped)return;let e=Sr[this.frame%Sr.length],s=this._formatElapsed(),n=s?` ${M.dim}${s}${M.reset}`:"",o="";for(let i=0;i<this.labels.length;i++){let r,c;switch(this.statuses[i]){case"done":r=`${M.green}\u2713${M.reset}`,c=M.dim;break;case"error":r=`${M.red}\u2717${M.reset}`,c=M.dim;break;default:r=`${M.cyan}${e}${M.reset}`,c=""}let l=i===this.labels.length-1?n:"";o+=`\x1B[2K ${r} ${c}${this.labels[i]}${M.reset}${l}
|
|
3
3
|
`}this.lineCount>0&&(o+=`\x1B[${this.lineCount}A`),process.stderr.write(o),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
4
|
-
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${
|
|
5
|
-
`}process.stderr.write(n)}},
|
|
6
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=
|
|
7
|
-
`}
|
|
8
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),
|
|
4
|
+
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${M.dim}${e}${M.reset}`:"",n="";for(let o=0;o<this.labels.length;o++){let i;switch(this.statuses[o]){case"done":i=`${M.green}\u2713${M.reset}`;break;case"error":i=`${M.red}\u2717${M.reset}`;break;default:i=`${M.yellow}\u25CB${M.reset}`}let r=o===this.labels.length-1?s:"";n+=`\x1B[2K ${i} ${M.dim}${this.labels[o]}${M.reset}${r}
|
|
5
|
+
`}process.stderr.write(n)}},En={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Tn={done:M.green,in_progress:M.cyan,pending:M.dim,failed:M.red},et=null,Cs=class{constructor(e,s){this.name=e,this.tasks=s.map(n=>({id:n.id,description:n.description,status:n.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=vr[this.frame%vr.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),i=o?` ${M.dim}(${o})${M.reset}`:"",r=`\x1B[2K${M.cyan}${e}${M.reset} ${this.name}\u2026${i}
|
|
6
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=En[l.status]||En.pending,f=Tn[l.status]||Tn.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;r+=`\x1B[2K ${M.dim}${u}${M.reset} ${f}${d}${M.reset} ${m}
|
|
7
|
+
`}r+=`\x1B[${this.lineCount}A`,process.stderr.write(r),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
8
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),et=this}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._paused||this._renderFinal(),process.stderr.write("\x1B[?25h"),this._paused=!1,et===this&&(et=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
|
|
9
9
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
10
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(c=>c.status==="done").length,n=this.tasks.filter(c=>c.status==="failed").length,o=this.tasks.length,
|
|
11
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=
|
|
12
|
-
`}process.stderr.write(
|
|
13
|
-
`),n=s.slice(0,e),o=s.length-e,
|
|
10
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(c=>c.status==="done").length,n=this.tasks.filter(c=>c.status==="failed").length,o=this.tasks.length,i=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,r=`\x1B[2K${M.green}\u2714${M.reset} ${this.name} ${M.dim}(${e} \xB7 ${i})${M.reset}
|
|
11
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=En[l.status]||En.pending,f=Tn[l.status]||Tn.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;r+=`\x1B[2K ${M.dim}${u}${M.reset} ${f}${d}${M.reset} ${M.dim}${m}${M.reset}
|
|
12
|
+
`}process.stderr.write(r)}};function Il(t){et=t}function ql(){return et}function jl(){et&&(et.stop(),et=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Er.exports={C:M,Spinner:Es,MultiProgress:Ts,TaskProgress:Cs,setActiveTaskProgress:Il,getActiveTaskProgress:ql,cleanupTerminal:jl}});var Ar=L((Kg,Rr)=>{var R={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",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",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"};function Cr(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var Dl={read_file:"\x1B[36m",list_directory:"\x1B[36m",write_file:"\x1B[33m",edit_file:"\x1B[33m",patch_file:"\x1B[33m",bash:"\x1B[35m",grep:"\x1B[34m",search_files:"\x1B[34m",glob:"\x1B[34m",git_commit:"\x1B[32m",git_push:"\x1B[32m",git_pull:"\x1B[32m",git_status:"\x1B[32m",git_diff:"\x1B[32m",git_log:"\x1B[32m",git_branch:"\x1B[32m",git_stash:"\x1B[32m",web_fetch:"\x1B[96m",web_search:"\x1B[96m"},Rs={read_file:"Read file",write_file:"Write",edit_file:"Update",patch_file:"Update",list_directory:"List directory",bash:"Run command",grep:"Search code",search_files:"Search files",glob:"Find files",web_fetch:"Fetch URL",web_search:"Web search",git_status:"Git status",git_diff:"Git diff",git_log:"Git log",git_commit:"Git commit",git_push:"Git push",git_pull:"Git pull",git_branch:"Git branch",git_stash:"Git stash",task_list:"Task list",spawn_agents:"Spawn agents",ask_user:"Ask user",switch_model:"Switch model",gh_run_list:"GH Actions",gh_run_view:"GH Actions",gh_workflow_trigger:"GH trigger",browser_open:"Browser open",browser_screenshot:"Screenshot",browser_click:"Browser click",browser_fill:"Browser fill",ssh_exec:"SSH exec",ssh_upload:"SSH upload",ssh_download:"SSH download",service_manage:"Service",service_logs:"Service logs",container_list:"Containers",container_logs:"Container logs",container_exec:"Container exec",brain_write:"Brain write",deploy:"Deploy"};function Cn(t,e=!1){return e?`${R.red}\u25CF${R.reset}`:`${Dl[t]||R.green}\u25CF${R.reset}`}function Fl(t,e,s=!1){let n=(t||[]).filter(c=>c&&c.canExecute!==!1);if(n.length===0)return`${Cn("",s)} Step ${e}`;if(n.length===1){let c=n[0],l=c.args||{},u=Rs[c.fnName]||c.fnName.replace(/_/g," "),d="";l.path?d=Cr(l.path):l.command?d=String(l.command).substring(0,60):l.query?d=String(l.query).substring(0,50):l.pattern&&(d=String(l.pattern).substring(0,50));let f=d?`${R.dim}(${d})${R.reset}`:"";return`${Cn(c.fnName,s)} ${R.bold}${u}${R.reset} ${f}`}let o=n[0].fnName,i=[...new Set(n.map(c=>Rs[c.fnName]||c.fnName.replace(/_/g," ")))],r=i.length<=3?i.join(" \xB7 "):`${n.length} actions`;return`${Cn(o,s)} ${r}`}function Ul(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=Cr(e.path);break;case"bash":s=(e.command||"").substring(0,80);break;case"grep":case"search_files":s=e.pattern?`"${e.pattern}"${e.path?` in ${e.path}`:""}`:"";break;case"glob":s=e.pattern||"";break;case"web_fetch":s=(e.url||"").substring(0,60);break;case"web_search":s=(e.query||"").substring(0,50);break;default:s=JSON.stringify(e).substring(0,80)}let n=Rs[t]||t.replace(/_/g," "),o=s?` ${R.dim}(${s})${R.reset}`:"";return`${Cn(t)} ${R.bold}${n}${R.reset}${o}`}function Wl(t,e=8){let s=t.split(`
|
|
13
|
+
`),n=s.slice(0,e),o=s.length-e,i=`${R.dim} \u2514 ${R.reset}`,r=" ",c=n.map((l,u)=>`${u===0?i:r}${R.green}${l}${R.reset}`).join(`
|
|
14
14
|
`);return o>0&&(c+=`
|
|
15
|
-
${
|
|
15
|
+
${R.gray} \u2026 +${o} lines${R.reset}`),c}function Bl(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading: ${e.path||"file"}`;case"list_directory":return`Listing: ${e.path||"."}`;case"search_files":return`Searching: ${e.pattern||"..."}`;case"glob":return`Glob: ${e.pattern||"..."}`;case"grep":return`Grep: ${e.pattern||"..."}`;case"web_fetch":return`Fetching: ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Git status...";case"git_diff":return`Git diff${e.file?`: ${e.file}`:""}...`;case"git_log":return`Git log${e.file?`: ${e.file}`:""}...`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;default:return`Running: ${t}`}}function Hl(t,e,s,n){let o=String(s||"");if(n){let r=o.split(`
|
|
16
16
|
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80),c=o.match(/\nHINT: (.+)/),l=c?`
|
|
17
|
-
${
|
|
18
|
-
`).filter(Boolean),c=
|
|
19
|
-
`).length;
|
|
20
|
-
`)
|
|
21
|
-
`).filter(
|
|
22
|
-
|
|
23
|
-
`)
|
|
24
|
-
`).
|
|
25
|
-
`).
|
|
26
|
-
`).filter(
|
|
27
|
-
|
|
28
|
-
`).filter(Boolean).length
|
|
29
|
-
`)
|
|
17
|
+
${R.dim}${c[1].substring(0,100)}${R.reset}`:"";return` ${R.red}\u2514 ${r}${R.reset}${l}`}let i;switch(t){case"read_file":{let r=o.split(`
|
|
18
|
+
`).filter(Boolean),c=r.length,l=r[r.length-1],u=l?parseInt(l.match(/^(\d+):/)?.[1]||"0"):0,d=e.line_start||e.line_end,f=(r[0]||"").replace(/^\d+:\s*/,"").trim(),m=f?` ${R.dim}\u2014 ${f.substring(0,60)}${f.length>60?"\u2026":""}${R.reset}`:"";d&&u>c?i=`Read lines ${e.line_start||1}\u2013${u}${m}`:i=`Read ${c} line${c!==1?"s":""}${m}`;break}case"write_file":{let r=(e.content||"").split(`
|
|
19
|
+
`).length;i=`Wrote ${r} line${r!==1?"s":""}`;break}case"edit_file":{let r=(e.old_text||"").split(`
|
|
20
|
+
`),c=(e.new_text||"").split(`
|
|
21
|
+
`),l=r.length,u=c.length,d=3,f=r.slice(0,d).filter(p=>p.trim()),m=c.slice(0,d).filter(p=>p.trim()),h=[];for(let p of f)h.push(`${R.red} - ${R.reset}${R.dim}${p.trimEnd().substring(0,72)}${R.reset}`);r.length>d&&h.push(`${R.dim} \u2026 +${r.length-d}${R.reset}`);for(let p of m)h.push(`${R.green} + ${R.reset}${R.dim}${p.trimEnd().substring(0,72)}${R.reset}`);c.length>d&&h.push(`${R.dim} \u2026 +${c.length-d}${R.reset}`),i=`${R.reset}${R.red}\u2212${l}${R.reset} ${R.green}+${u}${R.reset}`+(h.length>0?`
|
|
22
|
+
`+h.join(`
|
|
23
|
+
`):"");break}case"patch_file":{let r=e.patches||[],c=r.reduce((u,d)=>u+(d.old_text||"").split(`
|
|
24
|
+
`).length,0),l=r.reduce((u,d)=>u+(d.new_text||"").split(`
|
|
25
|
+
`).length,0);i=`${R.reset}${r.length} patch${r.length!==1?"es":""} ${R.red}\u2212${c}${R.reset} ${R.green}+${l}${R.reset}`;break}case"bash":{let r=o.match(/^EXIT (\d+)/);if(r){let c=r[1],l=o.match(/\nHINT: (.+)/);if(l)i=`${c==="0"?`${R.green}\u2713${R.reset}`:`${R.red}\u2717 Exit ${c}${R.reset}`} ${R.dim}\u2014 ${l[1].substring(0,60)}${R.reset}`;else{let u=o.split(`
|
|
26
|
+
`).filter(h=>h&&!h.startsWith("EXIT ")&&h.trim()),d=u[0]?` ${R.dim}\xB7 ${u[0].substring(0,70)}${R.reset}`:"",f=u.length>1?` ${R.dim}+${u.length-1}${R.reset}`:"";i=`${c==="0"?`${R.green}\u2713${R.reset}`:`${R.red}\u2717 Exit ${c}${R.reset}`}${d}${f}`}}else{let c=o.split(`
|
|
27
|
+
`).filter(Boolean);i=c.length>1?`${c[0].substring(0,60)} ${R.dim}+${c.length-1} more${R.reset}`:(c[0]||"").substring(0,70)||"Done"}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")i="No matches";else{let r=o.split(`
|
|
28
|
+
`).filter(Boolean),c=r.length,u=new Set(r.map(d=>d.split(":")[0]).filter(Boolean)).size;i=u>1?`${c} match${c!==1?"es":""} in ${u} files`:`${c} match${c!==1?"es":""}`}break}case"glob":{if(o==="(no matches)")i="No files found";else{let r=o.split(`
|
|
29
|
+
`).filter(Boolean).length;i=`${r} file${r!==1?"s":""} found`}break}case"list_directory":{let r=o==="(empty)"?0:o.split(`
|
|
30
|
+
`).filter(Boolean).length;i=`${r} entr${r!==1?"ies":"y"}`;break}case"git_status":{let r=o.match(/Branch:\s*(\S+)/),c=o.split(`
|
|
31
|
+
`).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;i=r?`${r[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let r=(o.match(/^\+[^+]/gm)||[]).length,c=(o.match(/^-[^-]/gm)||[]).length;i=r||c?`+${r} \u2212${c} lines`:"No diff";break}case"git_log":{let r=o.split(`
|
|
32
|
+
`).filter(c=>/^commit\s+[0-9a-f]{7}/.test(c)).length;i=r>0?`${r} commit${r!==1?"s":""}`:"Log retrieved";break}case"git_commit":{let r=o.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),c=o.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);i=r?`${r[1]}${c?` \u2014 ${c[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let r=o.match(/(?:->|→)\s*(\S+)/);i=r?`\u2192 ${r[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(o))i="Already up to date";else{let r=(o.match(/^\+/gm)||[]).length;i=r>0?`Pulled \xB7 +${r} lines`:"Pulled"}break}case"web_fetch":i="Fetched";break;case"web_search":{let r=o.split(`
|
|
33
|
+
|
|
34
|
+
`).filter(Boolean).length;i=`${r} result${r!==1?"s":""}`;break}case"task_list":i="Done";break;case"spawn_agents":{let r=(o.match(/✓ Agent/g)||[]).length,c=(o.match(/✗ Agent/g)||[]).length;i=c>0?`${r} done, ${c} failed`:`${r} agent${r!==1?"s":""} done`;break}case"switch_model":{let r=o.match(/Switched to (.+)/);i=r?`\u2192 ${r[1]}`:"Done";break}default:i="Done"}return` ${R.dim}\u2514 ${i}${R.reset}`}Rr.exports={C:R,formatToolCall:Ul,formatResult:Wl,getToolSpinnerText:Bl,formatToolSummary:Hl,formatSectionHeader:Fl}});var ae=L((Jg,Or)=>{var Tt={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",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",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"};function Gl(t,e){return[...t].map(s=>s===" "?s:`\x1B[38;2;${e[0]};${e[1]};${e[2]}m${s}`).join("")+Tt.reset}function zl(t,e){let s=(t.length-1)*e,n=Math.min(Math.floor(s),t.length-2),o=s-n;return[Math.round(t[n][0]+(t[n+1][0]-t[n][0])*o),Math.round(t[n][1]+(t[n+1][1]-t[n][1])*o),Math.round(t[n][2]+(t[n+1][2]-t[n][2])*o)]}function Kl(t,e,s={}){let n=Tt.bold,o=Tt.dim,i=Tt.reset,r=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557 \u2501 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2501 \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2554\u255D \u2501 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2588\u2588\u2557 \u2501 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D","\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2588\u2588\u2557 \u2501 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u2501 \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],c=[[220,240,255],[80,200,255],[40,100,220]],l=r.map((d,f)=>{let m=f/(r.length-1||1);return Gl(d,zl(c,m))}).join(`
|
|
35
|
+
`),u=s.yolo?` ${n}${Tt.yellow}\u26A1 YOLO${i}`:"";console.log(`
|
|
30
36
|
${l}
|
|
31
|
-
${o}Agentic Coding CLI v${
|
|
32
|
-
${o}Model: ${t}${
|
|
33
|
-
`)}var{Spinner:
|
|
34
|
-
`);for(let d=0;d<s.length;d++){let f=d===o,m=f?`${
|
|
37
|
+
${o}Agentic Coding CLI v${Sn().version}${i}
|
|
38
|
+
${o}Model: ${t}${i} ${o}\xB7 /help${i}${u}
|
|
39
|
+
`)}var{Spinner:Jl,MultiProgress:Yl,TaskProgress:Xl,setActiveTaskProgress:Vl,getActiveTaskProgress:Ql,cleanupTerminal:Zl}=Tr(),{formatToolCall:eu,formatResult:tu,getToolSpinnerText:nu,formatToolSummary:su,formatSectionHeader:ou}=Ar();Or.exports={C:Tt,banner:Kl,Spinner:Jl,MultiProgress:Yl,TaskProgress:Xl,setActiveTaskProgress:Vl,getActiveTaskProgress:Ql,cleanupTerminal:Zl,formatToolCall:eu,formatResult:tu,getToolSpinnerText:nu,formatToolSummary:su,formatSectionHeader:ou}});var Ie=L((Yg,Ir)=>{var ru=require("readline"),{C:Le}=ae(),Nr=[/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/],As=[/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 Mr(t){let e=t.match(/ssh\s+[^"]*"([^"]+)"/)?.[1]||t.match(/ssh\s+[^']*'([^']+)'/)?.[1];if(!e)return!1;let n=e.replace(/\bfor\s[\s\S]*?\bdone\b/g,i=>i.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,i=>i.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(i=>i.replace(/\x00/g,";").trim()).filter(Boolean);if(n.length===0)return!1;let o=i=>{let r=i.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(r))return!0;if(/^\s*for\s/.test(i)||/^\s*while\s/.test(i)){let c=i.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return c?c.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>o(u)):As.some(l=>l.test(i))}return/^\w+=\$?\(/.test(r)||/^\w+=["']/.test(r)||/^\w+=\S/.test(r)?!0:As.some(c=>c.test(r))};return n.every(o)}var Os=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],Pr=[/git\s+push/,/npm\s+publish/,/npx\s+.*publish/,/docker\s+rm/,/ssh\s/,/wget\s/,/curl\s.*-o\s/,/pip\s+install/,/npm\s+install\s+-g/],Lr=[...Os,...Pr],Ns=!1,ft=null;function iu(t){Ns=t}function au(){return Ns}function cu(t){ft=t}function lu(t){for(let e of Nr)if(e.test(t))return e;return null}function uu(t){if(/ssh\s/.test(t)&&Mr(t))return!1;for(let e of Lr)if(e.test(t))return!0;return!1}function du(t){for(let e of Os)if(e.test(t))return!0;return!1}function fu(t,e={}){if(Ns)return Promise.resolve(!0);if(!process.stdout.isTTY||!process.stdin.isTTY)return mu(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0,i=!1;ft&&ft.pause();let r=()=>{i&&process.stdout.write(`\x1B[${s.length+1}A`),i=!0,process.stdout.write(`\r\x1B[K${Le.yellow}${t}${Le.reset}
|
|
40
|
+
`);for(let d=0;d<s.length;d++){let f=d===o,m=f?`${Le.yellow}\u276F${Le.reset}`:" ",h=f?`${Le.yellow}${s[d]}${Le.reset}`:s[d];process.stdout.write(`\r\x1B[K ${m} ${h}
|
|
35
41
|
`)}},c=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u),process.stdout.write(`\x1B[${s.length+1}A`);for(let f=0;f<s.length+1;f++)process.stdout.write(`\r\x1B[K
|
|
36
|
-
`);process.stdout.write(`\x1B[${s.length+1}A`),
|
|
37
|
-
`){l(o);return}if(f==="\x1B[A"){o=(o-1+s.length)%s.length,
|
|
38
|
-
`)};return o.length>0&&(
|
|
39
|
-
`);h=g.pop()||"";for(let y of g){if(!y.trim())continue;let $;try{$=JSON.parse(y)}catch{continue}if($.message?.content&&(c($.message.content),f+=$.message.content),$.message?.tool_calls&&(m=m.concat($.message.tool_calls)),$.done){u({content:f,tool_calls:this._normalizeToolCalls(m)});return}}}),l.data.on("error",p=>{n.signal?.aborted||d(new Error(`Stream error: ${p.message}`))}),l.data.on("end",()=>{if(h.trim())try{let p=JSON.parse(h);p.message?.content&&(c(p.message.content),f+=p.message.content),p.message?.tool_calls&&(m=m.concat(p.message.tool_calls))}catch{}u({content:f,tool_calls:this._normalizeToolCalls(m)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`ollama-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};
|
|
42
|
+
`);process.stdout.write(`\x1B[${s.length+1}A`),ft&&ft.resume(),n(d)},l=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&Rn(e.toolName),c(!0)},u=d=>{if(d[0]===3){c(!1);return}let f=d.toString();if(f==="\r"||f===`
|
|
43
|
+
`){l(o);return}if(f==="\x1B[A"){o=(o-1+s.length)%s.length,r();return}if(f==="\x1B[B"){o=(o+1)%s.length,r();return}let m=f.toLowerCase().trim();if(m==="y"){c(!0);return}if(m==="n"){c(!1);return}if(m==="a"&&e.toolName){Rn(e.toolName),c(!0);return}};r(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function mu(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=i=>{let r=i.trim().toLowerCase();r==="a"&&e.toolName?(Rn(e.toolName),n(!0)):n(r!=="n")};if(ft)ft.question(`${Le.yellow}${t} ${s}${Le.reset}`,o);else{let i=ru.createInterface({input:process.stdin,output:process.stdout});i.question(`${Le.yellow}${t} ${s}${Le.reset}`,r=>{i.close(),o(r)})}})}var Rn=()=>{};function pu(t){Rn=t}Ir.exports={FORBIDDEN_PATTERNS:Nr,SSH_SAFE_PATTERNS:As,isSSHReadOnly:Mr,DANGEROUS_BASH:Lr,CRITICAL_BASH:Os,NOTABLE_BASH:Pr,isForbidden:lu,isDangerous:uu,isCritical:du,confirm:fu,setAutoConfirm:iu,getAutoConfirm:au,setReadlineInterface:cu,setAllowAlwaysHandler:pu}});var Ct=L((Xg,qr)=>{var Ms=class t{constructor(e={}){if(new.target===t)throw new Error("BaseProvider is abstract \u2014 use a concrete provider");this.name=e.name||"unknown",this.baseUrl=e.baseUrl||"",this.models=e.models||{},this.defaultModel=e.defaultModel||null}isConfigured(){throw new Error(`${this.name}: isConfigured() not implemented`)}getApiKey(){return null}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}getModel(e){return this.models[e]||null}async chat(e,s,n={}){throw new Error(`${this.name}: chat() not implemented`)}async stream(e,s,n={}){throw new Error(`${this.name}: stream() not implemented`)}formatMessages(e){return{messages:e}}formatTools(e){return e}normalizeResponse(e){throw new Error(`${this.name}: normalizeResponse() not implemented`)}};qr.exports={BaseProvider:Ms}});var Fr=L((Vg,Dr)=>{var An=require("axios"),hu=require("http"),gu=require("https"),{BaseProvider:$u}=Ct(),On=new hu.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Nn=new gu.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),jr={"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}},Ps=class extends $u{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||jr,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){An.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:On,httpsAgent:Nn}).then(e=>{let s=e.data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}).catch(()=>{});return}try{let s=(await An.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:On,httpsAgent:Nn})).data?.models||[];for(let n of s){let o=(n.name||n.model||"").replace(/:latest$/,"");!o||this.models[o]||(this.models[o]={id:o,name:n.name||o,maxTokens:16384,contextWindow:131072})}}catch{}}}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OLLAMA_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OLLAMA_API_KEY not set");return{Authorization:`Bearer ${e}`}}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let r of s.content)r.type==="text"?n.push(r.text??""):r.type==="image"&&r.data&&o.push(r.data);let i={role:"user",content:n.join(`
|
|
44
|
+
`)};return o.length>0&&(i.images=o),i}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,i=this.getModel(o),r=n.maxTokens||i?.maxTokens||16384,c=await An.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:r}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:On,httpsAgent:Nn});return this.normalizeResponse(c.data)}async stream(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,i=this.getModel(o),r=n.maxTokens||i?.maxTokens||16384,c=n.onToken||(()=>{}),l;try{l=await An.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict:r}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:On,httpsAgent:Nn})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.data?.error||u.message;throw new Error(`API Error: ${d}`)}return new Promise((u,d)=>{let f="",m=[],h="";n.signal&&n.signal.addEventListener("abort",()=>{l.data.destroy(),d(new DOMException("The operation was aborted","AbortError"))},{once:!0}),l.data.on("data",p=>{h+=p.toString();let g=h.split(`
|
|
45
|
+
`);h=g.pop()||"";for(let y of g){if(!y.trim())continue;let $;try{$=JSON.parse(y)}catch{continue}if($.message?.content&&(c($.message.content),f+=$.message.content),$.message?.tool_calls&&(m=m.concat($.message.tool_calls)),$.done){u({content:f,tool_calls:this._normalizeToolCalls(m)});return}}}),l.data.on("error",p=>{n.signal?.aborted||d(new Error(`Stream error: ${p.message}`))}),l.data.on("end",()=>{if(h.trim())try{let p=JSON.parse(h);p.message?.content&&(c(p.message.content),f+=p.message.content),p.message?.tool_calls&&(m=m.concat(p.message.tool_calls))}catch{}u({content:f,tool_calls:this._normalizeToolCalls(m)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`ollama-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};Dr.exports={OllamaProvider:Ps,OLLAMA_MODELS:jr}});var zr=L((Qg,Gr)=>{var{callChat:yu}=he(),{estimateTokens:Ls}=Oe(),Ur=process.env.NEX_COMPACTION!=="false",Wr=6,Br=500,wu=`Summarize this conversation history concisely. Focus on:
|
|
40
46
|
- What files were read, created, or modified
|
|
41
47
|
- Key decisions made and their rationale
|
|
42
48
|
- Current state of the task (what's done, what's pending)
|
|
43
49
|
- Any errors encountered and how they were resolved
|
|
44
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
45
|
-
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-
|
|
50
|
+
Be factual and brief. Use bullet points. Max 300 words.`;async function bu(t){if(!Ur||t.length<Wr)return null;let e=[{role:"system",content:wu},{role:"user",content:Hr(t)}];try{let n=((await yu(e,[],{temperature:0,maxTokens:Br})).content||"").trim();if(!n)return null;let o=t.reduce((r,c)=>r+Ls(c.content||"")+(c.tool_calls?Ls(JSON.stringify(c.tool_calls)):0),0),i=Ls(n);return i>=o*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
51
|
+
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-i}}catch{return null}}function Hr(t){return t.map(e=>{let s=e.role==="tool"?"tool_result":e.role,n=(e.content||"").substring(0,500);if(e.tool_calls){let o=e.tool_calls.map(i=>i.function?.name).join(", ");return`[${s}] ${n}
|
|
46
52
|
tools: ${o}`}return`[${s}] ${n}`}).join(`
|
|
47
53
|
|
|
48
|
-
`)}
|
|
54
|
+
`)}Gr.exports={compactMessages:bu,formatMessagesForSummary:Hr,COMPACTION_ENABLED:Ur,COMPACTION_MIN_MESSAGES:Wr,COMPACTION_SUMMARY_BUDGET:Br}});var Oe=L((Zg,Zr)=>{function Jr(){return he().getActiveModel()}var xu={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},Jt=new Map,Kr=1e3,Is=new WeakMap,Yt=null;function _u(){if(Yt!==null)return Yt;try{let e=Jr()?.provider||"ollama";return Yt=xu[e]||4,Yt}catch{return 4}}function ku(){Yt=null}function pt(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)}`,s=Jt.get(e);if(s!==void 0)return s;let n=Math.ceil(t.length/_u());if(Jt.size>=Kr){let o=Kr>>1,i=Jt.keys();for(let r=0;r<o;r++)Jt.delete(i.next().value)}return Jt.set(e,n),n}function vu(t){if(Is.has(t))return Is.get(t);let e=JSON.stringify(t);return Is.set(t,e),e}function Rt(t){let s=4;if(t.content&&(s+=pt(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=pt(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=pt(o):o&&(s+=pt(JSON.stringify(o)))}return s}function Ne(t){let e=0;for(let s of t)e+=Rt(s);return e}function Su(t,e){if(t&&t.length===e.length){let i=!1;for(let r=0;r<e.length;r++)if(t[r]!==e[r]){i=!0;break}if(!i)return 0}let s=t?t.length:0,n=e.length,o=0;for(let i=s;i<n;i++)o+=Rt(e[i]);return o}function Mn(t){return!t||t.length===0?0:pt(JSON.stringify(t))}function Pn(){return Jr()?.contextWindow||32768}function Eu(t,e){let s=Ne(t),n=Mn(e),o=s+n,i=Pn(),r=i>0?o/i*100:0,c=0,l=0,u=0;for(let d of t){let f=Rt(d);d.role==="system"?c+=f:d.role==="tool"?u+=f:l+=f}return{used:o,limit:i,percentage:Math.round(r*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:n},messageCount:t.length}}var Yr=.75,Xr=.1,Vr=10,Tu=200,Cu=500;function Qr(t,e){if(!t||t.length<=e)return t;let n=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=n)return t;let o=t.split(`
|
|
49
55
|
`);if(o.length<=10){let p=Math.floor(n*.6),g=Math.floor(n*.4),y=t.substring(0,p),$=t.substring(t.length-g);return y+`
|
|
50
56
|
...(${t.length} chars total)...
|
|
51
|
-
`+$}let
|
|
57
|
+
`+$}let i=Math.floor(o.length*.4),r=Math.floor(o.length*.4),c=[],l=0,u=Math.floor(n*.4);for(let p=0;p<i&&l<u;p++)if(l+o[p].length+1>u&&o[p].trim().startsWith("```")){c.push(o[p]),l+=o[p].length+1;let g=p+1;for(;g<o.length&&l<u*1.5&&!o[g].trim().startsWith("```");)c.push(o[g]),l+=o[g].length+1,g++;g<o.length&&o[g].trim().startsWith("```")&&(c.push(o[g]),l+=o[g].length+1),p=g}else c.push(o[p]),l+=o[p].length+1;let d=[],f=0,m=Math.floor(n*.4);for(let p=o.length-1;p>=o.length-r&&f<m;p--)if(f+o[p].length+1>m&&o[p].trim().startsWith("```")){d.push(o[p]),f+=o[p].length+1;let g=p-1;for(;g>=0&&f<m*1.5&&!o[g].trim().startsWith("```");)d.push(o[g]),f+=o[g].length+1,g--;g>=0&&o[g].trim().startsWith("```")&&(d.push(o[g]),f+=o[g].length+1),p=g}else d.push(o[p]),f+=o[p].length+1;d.reverse();let h=o.length-c.length-d.length;return c.join(`
|
|
52
58
|
`)+`
|
|
53
59
|
...(${h} lines omitted, ${o.length} total)...
|
|
54
60
|
`+d.join(`
|
|
55
|
-
`)}function
|
|
56
|
-
...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(
|
|
57
|
-
`),
|
|
61
|
+
`)}function Xt(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:Cu,n=e==="aggressive"?50:e==="medium"?100:Tu;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:Qr(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
|
|
62
|
+
...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(i=>({...i,function:{name:i.function.name,arguments:typeof i.function.arguments=="string"?i.function.arguments.substring(0,50):i.function.arguments}}))),o}return t}async function Ru(t,e,s={}){let n=s.threshold??Yr,o=s.safetyMargin??Xr,i=s.keepRecent??Vr,r=Pn(),c=Mn(e),l=Math.floor(r*(n-o)),u=l-c,d=Ne(t),f=d+c;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-i),y=t.slice(p,g),$=t.slice(g),_=y.filter(S=>!S._compacted);if(_.length>=6)try{let{compactMessages:S}=zr(),A=await S(_);if(A){let q=[...y.filter(Z=>Z._compacted),A.message],Q=mt(h,q,$),ne=Ne(Q);if(ne+c<=l)return{messages:Q,compressed:!0,compacted:!0,tokensRemoved:m-ne};y=q}}catch(S){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",S.message)}let T=(f-l)/l,k=y.map(S=>Xt(S,"light")),v=mt(h,k,$),C=Ne(v);if(C+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-C};if(k=y.map(S=>Xt(S,"medium")),v=mt(h,k,$),C=Ne(v),C+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-C};if(k=y.map(S=>Xt(S,"aggressive")),v=mt(h,k,$),C=Ne(v),C+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-C};for(;k.length>0&&C>u;){let S=k.shift();C-=Rt(S)}return v=mt(h,k,$),C=Ne(v),{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-C}}function mt(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function Au(t,e){if(!t)return"";if(pt(t)<=e)return t;let n=e*4,o=t.split(`
|
|
63
|
+
`),i=Math.floor(n*.6),r=Math.floor(n*.4),c="",l=0;for(let h of o){if(c.length+h.length+1>i)break;c+=(c?`
|
|
58
64
|
`:"")+h,l++}let u="",d=0;for(let h=o.length-1;h>=l;h--){let p=o[h]+(u?`
|
|
59
|
-
`:"")+u;if(p.length>
|
|
65
|
+
`:"")+u;if(p.length>r)break;u=p,d++}let m=`
|
|
60
66
|
|
|
61
67
|
... (${o.length-l-d} lines omitted, ${o.length} total) ...
|
|
62
68
|
|
|
63
|
-
`;return c+m+u}var
|
|
64
|
-
`);g=$.pop()||"";for(let
|
|
65
|
-
|
|
66
|
-
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let
|
|
67
|
-
`);
|
|
68
|
-
`);g=$.pop()||"";for(let
|
|
69
|
-
`)};return o.length>0&&(
|
|
70
|
-
`);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&&(
|
|
71
|
-
`)}}function
|
|
72
|
-
`)}function
|
|
73
|
-
`),c}catch(c){throw o.stop(),c}}async function
|
|
69
|
+
`;return c+m+u}var Ou=6;function Nu(t,e){let s=Pn(),n=Mn(e),o=Math.floor(s*.5)-n,i=Ne(t),r=null,c=0;t.length>0&&t[0].role==="system"&&(r=t[0],c=1);let l=Math.max(c,t.length-Ou),u=t.slice(c,l),d=t.slice(l),f=u.map(p=>Xt(p,"aggressive")),m=mt(r,f,d),h=Ne(m);for(;f.length>0&&h>o;){let p=f.shift();h-=Rt(p)}return m=mt(r,f,d),h=Ne(m),{messages:m,tokensRemoved:i-h}}Zr.exports={estimateTokens:pt,estimateMessageTokens:Rt,estimateMessagesTokens:Ne,estimateDeltaTokens:Su,estimateToolsTokens:Mn,serializeMessage:vu,getContextWindow:Pn,getUsage:Eu,compressMessage:Xt,compressToolResult:Qr,fitToContext:Ru,forceCompress:Nu,truncateFileContent:Au,invalidateTokenRatioCache:ku,COMPRESSION_THRESHOLD:Yr,SAFETY_MARGIN:Xr,KEEP_RECENT:Vr}});var si=L((t$,ni)=>{var ei=require("axios"),{BaseProvider:Mu}=Ct(),{serializeMessage:e$}=Oe(),ti={"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}},qs=class extends Mu{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||ti,defaultModel:e.defaultModel||"gpt-4o",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.OPENAI_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("OPENAI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let r=this._messageStringCache.get(o);this._messageFormatCache.set(n,r),s.push(r);continue}let i=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,i),this._messageFormatCache.set(n,i),s.push(i)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||null,tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,i=this.getModel(o),r=n.maxTokens||i?.maxTokens||16384,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:r,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await ei.post(`${this.baseUrl}/chat/completions`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,i=this.getModel(o),r=n.maxTokens||i?.maxTokens||16384,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:r,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await ei.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},g="";n.signal&&n.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 $=g.split(`
|
|
70
|
+
`);g=$.pop()||"";for(let _ of $){let T=_.trim();if(!T||!T.startsWith("data: "))continue;let k=T.slice(6);if(k==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let v;try{v=JSON.parse(k)}catch{continue}let C=v.choices?.[0]?.delta;if(C&&(C.content&&(c(C.content),h+=C.content),C.tool_calls))for(let S of C.tool_calls){let A=S.index??0;p[A]||(p[A]={id:S.id||"",name:"",arguments:""}),S.id&&(p[A].id=S.id),S.function?.name&&(p[A].name+=S.function.name),S.function?.arguments&&(p[A].arguments+=S.function.arguments)}}}),d.data.on("error",y=>{n.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`openai-${Date.now()}`,function:{name:s.name,arguments:s.arguments}}))}};ni.exports={OpenAIProvider:qs,OPENAI_MODELS:ti}});var ai=L((s$,ii)=>{var oi=require("axios"),{BaseProvider:Pu}=Ct(),{serializeMessage:n$}=Oe(),ri={"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}},Lu="2023-06-01",js=class extends Pu{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||ri,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Lu}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s="",n=[];for(let o of e){if(o.role==="system"){s+=(s?`
|
|
71
|
+
|
|
72
|
+
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let i=this._formatSingleMessage(o,n);if(i){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let r=this._getMessageCacheKey(o);this._messageStringCache.set(r,i),this._messageFormatCache.set(o,i)}n.push(i)}}return{messages:n,system:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e,s=[]){if(e.role==="assistant"){let n=[];if(e.content&&n.push({type:"text",text:e.content}),e.tool_calls)for(let o of e.tool_calls)n.push({type:"tool_use",id:o.id||`toolu-${Date.now()}`,name:o.function.name,input:typeof o.function.arguments=="string"?JSON.parse(o.function.arguments||"{}"):o.function.arguments||{}});return{role:"assistant",content:n.length>0?n:[{type:"text",text:""}]}}if(e.role==="tool"){let n=s[s.length-1],o={type:"tool_result",tool_use_id:e.tool_call_id,content:typeof e.content=="string"?e.content:JSON.stringify(e.content)};return n&&n.role==="user"&&Array.isArray(n.content)&&n.content[0]?.type==="tool_result"?(n.content.push(o),null):{role:"user",content:[o]}}if(Array.isArray(e.content)){let n=[];for(let o of e.content)o.type==="text"?n.push({type:"text",text:o.text??""}):o.type==="image"&&o.data&&n.push({type:"image",source:{type:"base64",media_type:o.media_type||"image/png",data:o.data}});return{role:"user",content:n}}return{role:"user",content:e.content}}formatTools(e){return!e||e.length===0?[]:e.map(s=>({name:s.function.name,description:s.function.description||"",input_schema:s.function.parameters||{type:"object",properties:{}}}))}_resolveModelId(e){return this.getModel(e)?.id||e}async chat(e,s,n={}){let o=n.model||this.defaultModel,i=this._resolveModelId(o),r=this.getModel(o),c=n.maxTokens||r?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:i,messages:l,max_tokens:c,temperature:n.temperature??this.temperature};u&&(d.system=u);let f=this.formatTools(s);f.length>0&&(d.tools=f);let m=await oi.post(`${this.baseUrl}/messages`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(m.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,i=this._resolveModelId(o),r=this.getModel(o),c=n.maxTokens||r?.maxTokens||8192,l=n.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f={model:i,messages:u,max_tokens:c,temperature:n.temperature??this.temperature,stream:!0};d&&(f.system=d);let m=this.formatTools(s);m.length>0&&(f.tools=m);let h;try{h=await oi.post(`${this.baseUrl}/messages`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let g=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${g}`)}return new Promise((p,g)=>{let y="",$=[],_=-1,T="";n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",k=>{T+=k.toString();let v=T.split(`
|
|
73
|
+
`);T=v.pop()||"";for(let C of v){let S=C.trim();if(S.startsWith("data: ")){let A=S.slice(6),B;try{B=JSON.parse(A)}catch{continue}switch(B.type){case"content_block_start":{let q=B.content_block;q?.type==="tool_use"&&(_=$.length,$.push({id:q.id,name:q.name,inputJson:""}));break}case"content_block_delta":{let q=B.delta;q?.type==="text_delta"&&q.text&&(l(q.text),y+=q.text),q?.type==="input_json_delta"&&q.partial_json!==void 0&&_>=0&&($[_].inputJson+=q.partial_json);break}case"content_block_stop":_=-1;break;case"message_stop":p({content:y,tool_calls:this._buildToolCalls($)});return}}}}),h.data.on("error",k=>{n.signal?.aborted||g(new Error(`Stream error: ${k.message}`))}),h.data.on("end",()=>{p({content:y,tool_calls:this._buildToolCalls($)})})})}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}_buildToolCalls(e){return e.filter(s=>s.name).map(s=>{let n={};if(s.inputJson)try{n=JSON.parse(s.inputJson)}catch{n=s.inputJson}return{id:s.id||`anthropic-${Date.now()}`,function:{name:s.name,arguments:n}}})}};ii.exports={AnthropicProvider:js,ANTHROPIC_MODELS:ri}});var di=L((r$,ui)=>{var ci=require("axios"),{BaseProvider:Iu}=Ct(),{serializeMessage:o$}=Oe(),li={"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}},Ds=class extends Iu{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||li,defaultModel:e.defaultModel||"gemini-2.5-flash",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("GEMINI_API_KEY not set");return{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s=[];for(let n of e){if(this._messageFormatCache.has(n)){s.push(this._messageFormatCache.get(n));continue}let o=this._getMessageCacheKey(n);if(this._messageStringCache.has(o)){let r=this._messageStringCache.get(o);this._messageFormatCache.set(n,r),s.push(r);continue}let i=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,i),this._messageFormatCache.set(n,i),s.push(i)}return{messages:s}}_getMessageCacheKey(e){let s=e.role||"",n=typeof e.content=="string"?e.content.substring(0,100):"",o=e.tool_calls?e.tool_calls.length:0;return`${s}:${n.length}:${o}`}_formatSingleMessage(e){if(e.role==="assistant"&&e.tool_calls)return{role:"assistant",content:e.content||"",tool_calls:e.tool_calls.map(s=>({id:s.id||`call-${Date.now()}`,type:"function",function:{name:s.function.name,arguments:typeof s.function.arguments=="string"?s.function.arguments:JSON.stringify(s.function.arguments)}}))};if(e.role==="tool")return{role:"tool",content:typeof e.content=="string"?e.content:JSON.stringify(e.content),tool_call_id:e.tool_call_id};if(e.role==="user"&&Array.isArray(e.content)){let s=[];for(let n of e.content)if(n.type==="text")s.push({type:"text",text:n.text??""});else if(n.type==="image"&&n.data){let o=n.data.startsWith("data:")?n.data:`data:${n.media_type||"image/png"};base64,${n.data}`;s.push({type:"image_url",image_url:{url:o,detail:"auto"}})}return{role:"user",content:s}}return{role:e.role,content:e.content}}async chat(e,s,n={}){let o=n.model||this.defaultModel,i=this.getModel(o),r=n.maxTokens||i?.maxTokens||8192,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:r,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await ci.post(`${this.baseUrl}/chat/completions`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,i=this.getModel(o),r=n.maxTokens||i?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:r,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await ci.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},g="";n.signal&&n.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 $=g.split(`
|
|
74
|
+
`);g=$.pop()||"";for(let _ of $){let T=_.trim();if(!T||!T.startsWith("data: "))continue;let k=T.slice(6);if(k==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let v;try{v=JSON.parse(k)}catch{continue}let C=v.choices?.[0]?.delta;if(C&&(C.content&&(c(C.content),h+=C.content),C.tool_calls))for(let S of C.tool_calls){let A=S.index??0;p[A]||(p[A]={id:S.id||"",name:"",arguments:""}),S.id&&(p[A].id=S.id),S.function?.name&&(p[A].name+=S.function.name),S.function?.arguments&&(p[A].arguments+=S.function.arguments)}}}),d.data.on("error",y=>{n.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:s.name,arguments:s.arguments}}))}};ui.exports={GeminiProvider:Ds,GEMINI_MODELS:li}});var pi=L((i$,mi)=>{var Ln=require("axios"),{BaseProvider:qu}=Ct(),fi="http://localhost:11434",Fs=class extends qu{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||fi,models:e.models||{},defaultModel:e.defaultModel||null,...e}),this.timeout=e.timeout||3e5,this.temperature=e.temperature??.2,this._modelsLoaded=!1}isConfigured(){return!0}async loadModels(){if(this._modelsLoaded)return this.models;try{let s=(await Ln.get(`${this.baseUrl}/api/tags`,{timeout:5e3})).data?.models||[];this.models={};for(let n of s){let o=n.name||n.model;if(!o)continue;let i=o.replace(/:latest$/,""),r=32768;try{let c=await Ln.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=c.data?.model_info||c.data?.details||{};r=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(c.data?.modelfile)||32768}catch{}this.models[i]={id:i,name:n.name,maxTokens:Math.min(8192,Math.floor(r*.1)),contextWindow:r}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let r of s.content)r.type==="text"?n.push(r.text??""):r.type==="image"&&r.data&&o.push(r.data);let i={role:"user",content:n.join(`
|
|
75
|
+
`)};return o.length>0&&(i.images=o),i}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let i=await Ln.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:n.maxTokens||8192}},{timeout:n.timeout||this.timeout});return this.normalizeResponse(i.data)}async stream(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let i=n.onToken||(()=>{}),r;try{r=await Ln.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict:n.maxTokens||8192}},{timeout:n.timeout||this.timeout,responseType:"stream",signal:n.signal})}catch(c){if(c.name==="CanceledError"||c.name==="AbortError"||c.code==="ERR_CANCELED")throw c;let l=c.response?.data?.error||c.message;throw new Error(`API Error: ${l}`)}return new Promise((c,l)=>{let u="",d=[],f="";n.signal&&n.signal.addEventListener("abort",()=>{r.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),r.data.on("data",m=>{f+=m.toString();let h=f.split(`
|
|
76
|
+
`);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&&(i(g.message.content),u+=g.message.content),g.message?.tool_calls&&(d=d.concat(g.message.tool_calls)),g.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),r.data.on("error",m=>{n.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),r.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(i(m.message.content),u+=m.message.content),m.message?.tool_calls&&(d=d.concat(m.message.tool_calls))}catch{}c({content:u,tool_calls:this._normalizeToolCalls(d)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`local-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};mi.exports={LocalProvider:Fs,DEFAULT_LOCAL_URL:fi}});var At=L((a$,xi)=>{var ht=require("fs"),Us=require("path"),hi={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:{}},In=[],tt={};function ju(t,e,s,n){if(In.push({provider:t,model:e,input:s,output:n}),tt[t]!==void 0){let o=wi(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
|
|
77
|
+
`)}}function Ws(t,e){let s=hi[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function gi(t){let e=Ws(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function $i(){let t={};for(let i of In){let r=`${i.provider}:${i.model}`;t[r]||(t[r]={provider:i.provider,model:i.model,input:0,output:0}),t[r].input+=i.input,t[r].output+=i.output}let e=Object.values(t).map(i=>({...i,cost:gi(i)})),s=e.reduce((i,r)=>i+r.cost,0),n=e.reduce((i,r)=>i+r.input,0),o=e.reduce((i,r)=>i+r.output,0);return{totalCost:s,totalInput:n,totalOutput:o,breakdown:e}}function Du(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=$i();if(n.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let i of n){let r=i.cost>0?`$${i.cost.toFixed(4)}`:"free";o.push(` ${i.provider}:${i.model}`),o.push(` Input: ${i.input.toLocaleString()} tokens`),o.push(` Output: ${i.output.toLocaleString()} tokens`),o.push(` Cost: ${r}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
|
|
78
|
+
`)}function Fu(t,e,s,n){let o=Ws(t,e),i=(s*o.input+n*o.output)/1e6;return i<=0?"":`[~$${i.toFixed(4)}]`}function Uu(){In=[]}function Wu(t,e){tt[t]=e}function Bu(t){delete tt[t]}function Hu(){return{...tt}}function yi(t){let e=0;for(let s of In)s.provider===t&&(e+=gi(s));return e}function wi(t){let e=yi(t),s=tt[t];if(s===void 0)return{allowed:!0,spent:e,limit:null,remaining:null};let n=Math.max(0,s-e);return{allowed:e<s,spent:e,limit:s,remaining:n}}function bi(){let t=Us.join(process.cwd(),".nex","config.json");if(ht.existsSync(t))try{let e=JSON.parse(ht.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(tt={...e.costLimits})}catch{}}function Gu(){let t=Us.join(process.cwd(),".nex"),e=Us.join(t,"config.json"),s={};if(ht.existsSync(e))try{s=JSON.parse(ht.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=tt,ht.existsSync(t)||ht.mkdirSync(t,{recursive:!0}),ht.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function zu(){tt={}}bi();xi.exports={PRICING:hi,trackUsage:ju,getSessionCosts:$i,formatCosts:Du,formatCostHint:Fu,resetCosts:Uu,getPricing:Ws,setCostLimit:Wu,removeCostLimit:Bu,getCostLimits:Hu,getProviderSpend:yi,checkBudget:wi,loadCostLimits:bi,saveCostLimits:Gu,resetCostLimits:zu}});var qn=L((c$,_i)=>{var Vt=he(),Ku={"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",max_tokens:16384},"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",max_tokens:16384}};function Ju(){return Vt.getActiveModel()}function Yu(t){return Vt.setActiveModel(t)}function Xu(){return Vt.getModelNames()}function Vu(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let n=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(n)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let n=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(n)}catch{}let s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}return null}async function Qu(t,e){let{C:s}=ae(),{Spinner:n}=ae(),o=new n("Thinking...");o.start();let i=!0,r="";try{let c=await Vt.callStream(t,e,{onToken:l=>{i&&(o.stop(),process.stdout.write(`${s.blue}`),i=!1),process.stdout.write(l),r+=l}});return i?o.stop():process.stdout.write(`${s.reset}
|
|
79
|
+
`),c}catch(c){throw o.stop(),c}}async function Zu(t,e){return Vt.callChat(t,e)}_i.exports={MODELS:Ku,getActiveModel:Ju,setActiveModel:Yu,getModelNames:Xu,callOllamaStream:Qu,callOllama:Zu,parseToolArgs:Vu}});var Si=L((l$,vi)=>{var jn=require("path"),{C:b}=ae(),{confirm:ed,getAutoConfirm:td}=Ie(),ki=2e3;function Qt(t,e){let s=t.split(`
|
|
74
80
|
`),n=e.split(`
|
|
75
|
-
`),o=[],
|
|
76
|
-
${b.bold}${b.cyan} Diff: ${t}${b.reset}`);let o=
|
|
77
|
-
${b.bold}${b.cyan} File exists \u2014 showing changes: ${t}${b.reset}`);let n=
|
|
81
|
+
`),o=[],i=s.length,r=n.length;if(i>ki||r>ki){for(let f of s)o.push({type:"remove",line:f});for(let f of n)o.push({type:"add",line:f});return o}let c=Array.from({length:i+1},()=>new Array(r+1).fill(0));for(let f=1;f<=i;f++)for(let m=1;m<=r;m++)s[f-1]===n[m-1]?c[f][m]=c[f-1][m-1]+1:c[f][m]=Math.max(c[f-1][m],c[f][m-1]);let l=i,u=r,d=[];for(;l>0||u>0;)l>0&&u>0&&s[l-1]===n[u-1]?(d.unshift({type:"same",line:s[l-1]}),l--,u--):u>0&&(l===0||c[l][u-1]>=c[l-1][u])?(d.unshift({type:"add",line:n[u-1]}),u--):(d.unshift({type:"remove",line:s[l-1]}),l--);return d}function nd(t,e,s,n=3){console.log(`
|
|
82
|
+
${b.bold}${b.cyan} Diff: ${t}${b.reset}`);let o=Qt(e,s),i=[];if(o.forEach((l,u)=>{l.type!=="same"&&i.push(u)}),i.length===0){console.log(`${b.gray} (no changes)${b.reset}`);return}let r=Math.max(0,i[0]-n),c=Math.min(o.length,i[i.length-1]+n+1);r>0&&console.log(`${b.gray} ...${b.reset}`);for(let l=r;l<c;l++){let u=o[l];switch(u.type){case"remove":console.log(`${b.red} - ${u.line}${b.reset}`);break;case"add":console.log(`${b.green} + ${u.line}${b.reset}`);break;default:console.log(`${b.gray} ${u.line}${b.reset}`)}}c<o.length&&console.log(`${b.gray} ...${b.reset}`),console.log()}function sd(t,e,s){console.log(`
|
|
83
|
+
${b.bold}${b.cyan} File exists \u2014 showing changes: ${t}${b.reset}`);let n=Qt(e,s),o=0;for(let r of n)r.type!=="same"&&o++;if(o===0){console.log(`${b.gray} (identical content)${b.reset}`);return}let i=0;for(let r of n){if(i>=30){console.log(`${b.gray} ...(${o-i} more changes)${b.reset}`);break}switch(r.type){case"remove":console.log(`${b.red} - ${r.line}${b.reset}`),i++;break;case"add":console.log(`${b.green} + ${r.line}${b.reset}`),i++;break;default:i>0&&console.log(`${b.gray} ${r.line}${b.reset}`)}}console.log()}function od(t,e){console.log(`
|
|
78
84
|
${b.bold}${b.cyan} New file: ${t}${b.reset}`);let s=e.split(`
|
|
79
|
-
`),n=s.slice(0,20);for(let o of n)console.log(`${b.green} + ${o}${b.reset}`);s.length>20&&console.log(`${b.gray} ...+${s.length-20} more lines${b.reset}`),console.log()}async function
|
|
80
|
-
${b.bold}${b.cyan} Side-by-side: ${t}${b.reset}`),console.log(` ${b.dim}${"\u2500".repeat(
|
|
81
|
-
`)}function
|
|
85
|
+
`),n=s.slice(0,20);for(let o of n)console.log(`${b.green} + ${o}${b.reset}`);s.length>20&&console.log(`${b.gray} ...+${s.length-20} more lines${b.reset}`),console.log()}async function rd(t){return td()?!0:ed(` ${t}?`)}function id(t,e,s,n){let o=n||process.stdout.columns||80,i=Math.floor((o-3)/2);console.log(`
|
|
86
|
+
${b.bold}${b.cyan} Side-by-side: ${t}${b.reset}`),console.log(` ${b.dim}${"\u2500".repeat(i)}\u252C${"\u2500".repeat(i)}${b.reset}`);let r=Qt(e,s),c=[],l=0;for(;l<r.length;)if(r[l].type==="same")c.push({left:r[l].line,right:r[l].line,type:"same"}),l++;else if(r[l].type==="remove"){let h=[];for(;l<r.length&&r[l].type==="remove";)h.push(r[l].line),l++;let p=[];for(;l<r.length&&r[l].type==="add";)p.push(r[l].line),l++;let g=Math.max(h.length,p.length);for(let y=0;y<g;y++)c.push({left:y<h.length?h[y]:"",right:y<p.length?p[y]:"",type:"changed"})}else r[l].type==="add"&&(c.push({left:"",right:r[l].line,type:"changed"}),l++);let u=c.map((h,p)=>h.type!=="same"?p:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${b.gray}(no changes)${b.reset}`);return}let d=Math.max(0,u[0]-2),f=Math.min(c.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(` ${b.dim}${"\xB7".repeat(i)}\u250A${"\xB7".repeat(i)}${b.reset}`);for(let h=d;h<f;h++){let p=c[h];if(p.type==="same")console.log(` ${b.gray}${m(p.left,i)}${b.reset}\u2502${b.gray}${m(p.right,i)}${b.reset}`);else{let g=p.left?`${b.red}${m(p.left,i)}${b.reset}`:`${m("",i)}`,y=p.right?`${b.green}${m(p.right,i)}${b.reset}`:`${m("",i)}`;console.log(` ${g}\u2502${y}`)}}f<c.length&&console.log(` ${b.dim}${"\xB7".repeat(i)}\u250A${"\xB7".repeat(i)}${b.reset}`),console.log(` ${b.dim}${"\u2500".repeat(i)}\u2534${"\u2500".repeat(i)}${b.reset}
|
|
87
|
+
`)}function ad(t,e,s,n={}){let o=n.label||"Update",i=n.context||3,r=n.annotations||[],c=jn.isAbsolute(t)?jn.relative(process.cwd(),t):t,l=Qt(e,s),u=1,d=1;for(let k of l)k.type==="same"?(k.oldLine=u++,k.newLine=d++):k.type==="remove"?(k.oldLine=u++,k.newLine=null):(k.oldLine=null,k.newLine=d++);let f=0,m=0;for(let k of l)k.type==="add"?f++:k.type==="remove"&&m++;if(console.log(`
|
|
82
88
|
${b.cyan}\u23FA${b.reset} ${b.bold}${o}(${c})${b.reset}`),f===0&&m===0){console.log(` ${b.dim}\u23BF (no changes)${b.reset}
|
|
83
|
-
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),
|
|
84
|
-
`),
|
|
85
|
-
${b.cyan}\u23FA${b.reset} ${b.bold}Create(${n})${b.reset}`);let
|
|
86
|
-
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function
|
|
87
|
-
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&
|
|
88
|
-
${
|
|
89
|
-
${
|
|
90
|
-
${
|
|
89
|
+
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),r.length>0){let k=r.filter(A=>A.severity==="error").length,v=r.filter(A=>A.severity==="warn").length,C=r.filter(A=>A.severity==="info").length,S=[];k>0&&S.push(`${b.red}${k} error${k!==1?"s":""}${b.dim}`),v>0&&S.push(`${b.yellow}${v} warning${v!==1?"s":""}${b.dim}`),C>0&&S.push(`${b.cyan}${C} info${C!==1?"s":""}${b.dim}`),h.push(`found ${S.join(", ")}`)}console.log(` ${b.dim}\u23BF ${h.join(", ")}${b.reset}`);let g=[];l.forEach((k,v)=>{k.type!=="same"&&g.push(v)});let y=[],$=null,_=null;for(let k of g){let v=Math.max(0,k-i),C=Math.min(l.length-1,k+i);$===null?($=v,_=C):(v<=_+1||(y.push([$,_]),$=v),_=C)}$!==null&&y.push([$,_]);let T=" ";for(let k=0;k<y.length;k++){k>0&&console.log(`${T}${b.dim}\xB7\xB7\xB7${b.reset}`);let[v,C]=y[k];for(let S=v;S<=C;S++){let A=l[S],B=A.newLine!=null?A.newLine:A.oldLine,q=String(B).padStart(4),Q=A.type!=="remove"?r.filter(ne=>ne.line===A.newLine):[];A.type==="remove"?console.log(`${T}${b.red}${q} -${A.line}${b.reset}`):A.type==="add"?console.log(`${T}${b.green}${q} +${A.line}${b.reset}`):console.log(`${T}${b.dim}${q}${b.reset} ${A.line}`);for(let ne of Q){let Z=b.cyan,me="\u2139";ne.severity==="error"?(Z=b.red,me="\u2716"):ne.severity==="warn"&&(Z=b.yellow,me="\u26A0"),console.log(`${T} ${Z}${me} ${ne.message}${b.reset}`)}}}console.log()}function cd(t,e,s={}){let n=jn.isAbsolute(t)?jn.relative(process.cwd(),t):t,o=e.split(`
|
|
90
|
+
`),i=s.annotations||[];console.log(`
|
|
91
|
+
${b.cyan}\u23FA${b.reset} ${b.bold}Create(${n})${b.reset}`);let r=[`${o.length} line${o.length!==1?"s":""}`];if(i.length>0){let d=i.filter(p=>p.severity==="error").length,f=i.filter(p=>p.severity==="warn").length,m=i.filter(p=>p.severity==="info").length,h=[];d>0&&h.push(`${b.red}${d} error${d!==1?"s":""}${b.dim}`),f>0&&h.push(`${b.yellow}${f} warning${f!==1?"s":""}${b.dim}`),m>0&&h.push(`${b.cyan}${m} info${m!==1?"s":""}${b.dim}`),r.push(`found ${h.join(", ")}`)}console.log(` ${b.dim}\u23BF ${r.join(", ")}${b.reset}`);let l=" ",u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),m=d+1,h=i.filter(p=>p.line===m);console.log(`${l}${b.green}${f} +${o[d]}${b.reset}`);for(let p of h){let g=b.cyan,y="\u2139";p.severity==="error"?(g=b.red,y="\u2716"):p.severity==="warn"&&(g=b.yellow,y="\u26A0"),console.log(`${l} ${g}${y} ${p.message}${b.reset}`)}}o.length>20&&console.log(`${l}${b.dim} ...+${o.length-20} more lines${b.reset}`),console.log()}vi.exports={diffLines:Qt,showEditDiff:nd,showWriteDiff:sd,showNewFilePreview:od,confirmFileChange:rd,showSideBySideDiff:id,showClaudeDiff:ad,showClaudeNewFile:cd}});var gt=L((u$,Ci)=>{var Ei=require("util").promisify(require("child_process").exec),ld=require("util").promisify(require("child_process").execFile),{C:se}=ae();async function Bs(t){try{let{stdout:e}=await Ei(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Dn(...t){try{let{stdout:e}=await ld("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function ud(){return await Bs("git rev-parse --is-inside-work-tree")==="true"}async function dd(){return await Bs("git branch --show-current")}async function Hs(){try{let{stdout:t}=await Ei("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
92
|
+
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function Fn(t=!1){return await Bs(`git diff ${t?"--cached":""}`)||""}async function Gs(){return(await Hs()).map(e=>e.file)}async function Ti(){let t=await Gs();if(t.length===0)return null;let e=await Fn(),n=await Fn(!0)||e,o=0,i=0;if(n){let d=n.split(`
|
|
93
|
+
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&i++}else o=t.length;let r="chore",c=t.join(" ").toLowerCase();c.includes("test")?r="test":c.includes("readme")||c.includes("doc")?r="docs":o>i*2?r="feat":i>o?r="refactor":r="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${r}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:r,files:t,stats:{additions:o,deletions:i}}}async function fd(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Dn("checkout","-b",s)!==null?s:null}async function md(t){return await Dn("add","-A"),await Dn("commit","-m",t)?await Dn("rev-parse","--short","HEAD"):null}async function pd(){let t=await Ti();if(!t)return`${se.dim}No changes${se.reset}`;let e=[];e.push(`
|
|
94
|
+
${se.bold}${se.cyan}Git Diff Summary:${se.reset}`),e.push(` ${se.green}+${t.stats.additions}${se.reset} ${se.red}-${t.stats.deletions}${se.reset} in ${t.files.length} file(s)`),e.push(`
|
|
95
|
+
${se.bold}${se.cyan}Files:${se.reset}`);for(let s of t.files.slice(0,20))e.push(` ${se.dim}${s}${se.reset}`);return t.files.length>20&&e.push(` ${se.dim}...+${t.files.length-20} more${se.reset}`),e.push(`
|
|
96
|
+
${se.bold}${se.cyan}Suggested message:${se.reset}`),e.push(` ${se.cyan}${t.summary}${se.reset}
|
|
91
97
|
`),e.join(`
|
|
92
|
-
`)}async function
|
|
98
|
+
`)}async function hd(){return(await Hs()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function gd(){let t=await Gs();if(t.length===0)return"";let e=[`CHANGED FILES (${t.length}):`];for(let n of t.slice(0,10))e.push(` ${n}`);let s=await Fn();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
|
|
93
99
|
...(truncated)`:s;e.push(`
|
|
94
100
|
DIFF:
|
|
95
101
|
${n}`)}return e.join(`
|
|
96
|
-
`)}
|
|
102
|
+
`)}Ci.exports={isGitRepo:ud,getCurrentBranch:dd,getStatus:Hs,getDiff:Fn,getChangedFiles:Gs,analyzeDiff:Ti,createBranch:fd,commit:md,formatDiffSummary:pd,getDiffContext:gd,getMergeConflicts:hd}});var Nt=L((d$,Ri)=>{var zs=require("fs").promises,$d=50,He=[],Ot=[];function yd(t,e,s,n){for(He.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});He.length>$d;)He.shift();Ot.length=0}async function wd(){if(He.length===0)return null;let t=He.pop();if(t.oldContent===null)try{await zs.unlink(t.filePath)}catch{}else await zs.writeFile(t.filePath,t.oldContent,"utf-8");return Ot.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function bd(){if(Ot.length===0)return null;let t=Ot.pop();return await zs.writeFile(t.filePath,t.newContent,"utf-8"),He.push(t),{tool:t.tool,filePath:t.filePath}}function xd(t=10){return He.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function _d(){return He.length}function kd(){return Ot.length}function vd(){He.length=0,Ot.length=0}Ri.exports={recordChange:yd,undo:wd,redo:bd,getHistory:xd,getUndoCount:_d,getRedoCount:kd,clearHistory:vd}});var Zt=L((f$,Li)=>{var ve=require("fs"),Mt=require("path"),we=[];function Ks(){return Mt.join(process.cwd(),".nex","skills")}function Ai(){return Mt.join(process.cwd(),".nex","config.json")}function Sd(){let t=Ks();return ve.existsSync(t)||ve.mkdirSync(t,{recursive:!0}),t}function Js(){let t=Ai();if(!ve.existsSync(t))return[];try{let e=JSON.parse(ve.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Oi(t){let e=Ai(),s={};if(ve.existsSync(e))try{s=JSON.parse(ve.readFileSync(e,"utf-8"))}catch{s={}}s.skills||(s.skills={}),s.skills.disabled=t;let n=Mt.dirname(e);ve.existsSync(n)||ve.mkdirSync(n,{recursive:!0}),ve.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function Ni(t,e){let s=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Module must export an object"]};if(t.name!==void 0&&typeof t.name!="string"&&s.push("name must be a string"),t.description!==void 0&&typeof t.description!="string"&&s.push("description must be a string"),t.instructions!==void 0&&typeof t.instructions!="string"&&s.push("instructions must be a string"),t.commands!==void 0)if(!Array.isArray(t.commands))s.push("commands must be an array");else for(let n=0;n<t.commands.length;n++){let o=t.commands[n];(!o.cmd||typeof o.cmd!="string")&&s.push(`commands[${n}].cmd must be a non-empty string`),o.handler!==void 0&&typeof o.handler!="function"&&s.push(`commands[${n}].handler must be a function`)}if(t.tools!==void 0)if(!Array.isArray(t.tools))s.push("tools must be an array");else for(let n=0;n<t.tools.length;n++){let o=t.tools[n];(!o.function||!o.function.name||typeof o.function.name!="string")&&s.push(`tools[${n}].function.name must be a non-empty string`),o.execute!==void 0&&typeof o.execute!="function"&&s.push(`tools[${n}].execute must be a function`)}return{valid:s.length===0,errors:s}}function Mi(t){try{let e=ve.readFileSync(t,"utf-8").trim();return e?{name:Mt.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function Pi(t){try{let e=require(t),{valid:s,errors:n}=Ni(e,t);return s?{name:e.name||Mt.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(i=>({cmd:i.cmd.startsWith("/")?i.cmd:`/${i.cmd}`,desc:i.desc||i.description||"",handler:i.handler||null})),tools:(e.tools||[]).map(i=>({type:i.type||"function",function:{name:i.function.name,description:i.function.description||"",parameters:i.function.parameters||{type:"object",properties:{}}},execute:i.execute||null}))}:(console.error(`Skill validation failed: ${t}
|
|
97
103
|
${n.join(`
|
|
98
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
104
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function Ed(){we=[];let t=Ks();if(!ve.existsSync(t))return we;let e=Js(),s;try{s=ve.readdirSync(t)}catch{return we}for(let n of s){let o=Mt.join(t,n),i;try{i=ve.statSync(o)}catch{continue}if(!i.isFile())continue;let r=null;n.endsWith(".md")?r=Mi(o):n.endsWith(".js")&&(r=Pi(o)),r&&(r.enabled=!e.includes(r.name),we.push(r))}return we}function Td(){let t=[];for(let e of we)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
99
105
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
100
106
|
${t.join(`
|
|
101
107
|
|
|
102
|
-
`)}`}function
|
|
103
|
-
`,l="",u=setTimeout(()=>{f(),
|
|
104
|
-
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===
|
|
105
|
-
`):JSON.stringify(o)}function
|
|
106
|
-
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),
|
|
107
|
-
`+
|
|
108
|
+
`)}`}function Cd(){let t=[];for(let e of we)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function Rd(){let t=[];for(let e of we)if(e.enabled)for(let s of e.tools)t.push({type:"function",function:{name:`skill_${s.function.name}`,description:`[Skill:${e.name}] ${s.function.description}`,parameters:s.function.parameters}});return t}async function Ad(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of we)if(n.enabled){for(let o of n.tools)if(o.function.name===s&&o.execute)try{let i=await o.execute(e);return typeof i=="string"?i:JSON.stringify(i)}catch(i){return`ERROR: Skill tool '${s}' failed: ${i.message}`}}return`ERROR: Skill tool '${s}' not found`}function Od(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of we)if(o.enabled){for(let i of o.commands)if(i.cmd===e&&i.handler){try{i.handler(n)}catch(r){console.error(`Skill command error (${e}): ${r.message}`)}return!0}}return!1}function Nd(){return we.map(t=>({name:t.name,type:t.type,enabled:t.enabled,description:t.description||"",commands:t.commands.length,tools:t.tools.length,filePath:t.filePath}))}function Md(t){let e=we.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Js().filter(n=>n!==t);return Oi(s),!0}function Pd(t){let e=we.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Js();return s.includes(t)||(s.push(t),Oi(s)),!0}function Ld(){return we}Li.exports={initSkillsDir:Sd,loadAllSkills:Ed,getSkillInstructions:Td,getSkillCommands:Cd,getSkillToolDefinitions:Rd,routeSkillCall:Ad,handleSkillCommand:Od,listSkills:Nd,enableSkill:Md,disableSkill:Pd,getLoadedSkills:Ld,_getSkillsDir:Ks,_validateScriptSkill:Ni,_loadMarkdownSkill:Mi,_loadScriptSkill:Pi}});var Wn=L((m$,Ui)=>{var{spawn:Id}=require("child_process"),qd=require("path"),Ii=require("fs"),Ge=new Map;function jd(){return qd.join(process.cwd(),".nex","config.json")}function Ys(){let t=jd();if(!Ii.existsSync(t))return{};try{return JSON.parse(Ii.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Un(t,e,s={},n=1e4){return new Promise((o,i)=>{let r=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:r,method:e,params:s})+`
|
|
109
|
+
`,l="",u=setTimeout(()=>{f(),i(new Error(`MCP request timeout: ${e}`))},n);function d(m){l+=m.toString();let h=l.split(`
|
|
110
|
+
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===r){f(),g.error?i(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):o(g.result);return}}catch{}l=h[h.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(m){f(),i(new Error(`MCP write failed: ${m.message}`))}})}async function qi(t,e){if(Ge.has(t))return Ge.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let r of s)process.env[r]&&(n[r]=process.env[r]);let o=Id(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),i={name:t,proc:o,tools:[],config:e};try{await Un(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let r=await Un(o,"tools/list",{});return i.tools=r&&r.tools||[],Ge.set(t,i),i}catch(r){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${r.message}`)}}function ji(t){let e=Ge.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Ge.delete(t),!0}function Dd(){for(let[t]of Ge)ji(t)}async function Di(t,e,s={}){let n=Ge.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await Un(n.proc,"tools/call",{name:e,arguments:s});return o&&Array.isArray(o.content)?o.content.filter(i=>i.type==="text").map(i=>i.text).join(`
|
|
111
|
+
`):JSON.stringify(o)}function Fi(){let t=[];for(let[e,s]of Ge)for(let n of s.tools)t.push({server:e,name:n.name,description:n.description||"",inputSchema:n.inputSchema||{type:"object",properties:{}}});return t}function Fd(){return Fi().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Ud(t,e){if(!t.startsWith("mcp_"))return null;let s=t.substring(4).split("_");if(s.length<2)return null;let n=s[0],o=s.slice(1).join("_");return Di(n,o,e)}function Wd(){let t=Ys();return Object.entries(t).map(([e,s])=>{let n=Ge.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function Bd(){let t=Ys(),e=[];for(let[s,n]of Object.entries(t))try{let o=await qi(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Ui.exports={loadMCPConfig:Ys,sendRequest:Un,connectServer:qi,disconnectServer:ji,disconnectAll:Dd,callTool:Di,getAllTools:Fi,getMCPToolDefinitions:Fd,routeMCPCall:Ud,listServers:Wd,connectAll:Bd}});var Xs=L((p$,Gi)=>{var{getSkillToolDefinitions:Hd}=Zt(),{getMCPToolDefinitions:Gd}=Wn(),Bn=new Map;function Wi(){let{TOOL_DEFINITIONS:t}=qe();return[...t,...Hd(),...Gd()]}function Bi(t){if(Bn.has(t))return Bn.get(t);let s=Wi().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return Bn.set(t,n),n}function zd(){Bn.clear()}function Hn(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let i=Hi(t.toLowerCase(),o.toLowerCase());i<n&&(n=i,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Hi(t,e){let s=t.length,n=e.length,o=Array.from({length:s+1},()=>Array(n+1).fill(0));for(let i=0;i<=s;i++)o[i][0]=i;for(let i=0;i<=n;i++)o[0][i]=i;for(let i=1;i<=s;i++)for(let r=1;r<=n;r++)o[i][r]=t[i-1]===e[r-1]?o[i-1][r-1]:1+Math.min(o[i-1][r],o[i][r-1],o[i-1][r-1]);return o[s][n]}function Kd(t,e){let s=Bi(t);if(s===null){let d=Wi().map(m=>m.function.name),f=Hn(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
112
|
+
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),i=Object.keys(e),r=[],c={...e},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=Hn(u,i);d&&!o.includes(d)?(c[u]=e[d],delete c[d],l=!0):r.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}for(let u of i)if(!o.includes(u)){let d=Hn(u,o);d&&!(d in c)?(c[d]=e[u],delete c[u],l=!0):l||r.push(`Unknown parameter "${u}".${d?` Did you mean "${d}"?`:""}`)}for(let u of Object.keys(c)){if(!s.properties[u])continue;let d=s.properties[u].type,f=typeof c[u];d==="string"&&f==="number"?(c[u]=String(c[u]),l=!0):d==="number"&&f==="string"&&!isNaN(c[u])?(c[u]=Number(c[u]),l=!0):d==="boolean"&&f==="string"&&(c[u]=c[u]==="true",l=!0)}return r.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
|
|
113
|
+
`+r.map(u=>` - ${u}`).join(`
|
|
108
114
|
`)+`
|
|
109
115
|
|
|
110
|
-
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}
|
|
116
|
+
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}Gi.exports={validateToolArgs:Kd,closestMatch:Hn,levenshtein:Hi,getCachedSchema:Bi,clearSchemaCache:zd}});var Yi=L((h$,Ji)=>{var{levenshtein:Gn}=Xs(),Jd=200,Yd=.3,Xd=2;function Vs(t){return t.replace(/\r\n/g,`
|
|
111
117
|
`).replace(/\r/g,`
|
|
112
|
-
`).replace(/\t/g," ".repeat(
|
|
113
|
-
`).map(e=>{let s=e.replace(/\s+$/,""),n=s.match(/^(\s*)(.*)/);if(!n)return s;let[,o,
|
|
114
|
-
`)}function
|
|
115
|
-
`),
|
|
116
|
-
`),
|
|
117
|
-
`),c=
|
|
118
|
-
`)}if(
|
|
118
|
+
`).replace(/\t/g," ".repeat(Xd)).split(`
|
|
119
|
+
`).map(e=>{let s=e.replace(/\s+$/,""),n=s.match(/^(\s*)(.*)/);if(!n)return s;let[,o,i]=n;return o+i.replace(/ {2,}/g," ")}).join(`
|
|
120
|
+
`)}function Vd(t,e){if(t.includes(e))return e;let s=Vs(t),n=Vs(e);if(!s.includes(n))return null;let o=t.split(`
|
|
121
|
+
`),i=s.split(`
|
|
122
|
+
`),r=n.split(`
|
|
123
|
+
`),c=r[0],l=r[r.length-1];for(let u=0;u<=i.length-r.length;u++){let d=!0;for(let f=0;f<r.length;f++)if(i[u+f]!==r[f]){d=!1;break}if(d)return o.slice(u,u+r.length).join(`
|
|
124
|
+
`)}if(r.length===1){for(let u=0;u<i.length;u++)if(i[u].indexOf(n)!==-1)return o[u]}return null}function Qd(t,e){if(!t||!e)return null;let s=t.split(`
|
|
119
125
|
`),o=e.split(`
|
|
120
|
-
`).length;return s.length===0||o===0?null:o===1?
|
|
121
|
-
`),u=
|
|
122
|
-
`),h=
|
|
123
|
-
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let
|
|
124
|
-
`).filter(Boolean),
|
|
126
|
+
`).length;return s.length===0||o===0?null:o===1?Zd(s,e):tf(s,e,o)}function zi(t){return Math.max(1,Math.floor(t/Jd))}function Ki(t,e){return t<=Math.ceil(e*Yd)}function Zd(t,e){let s=e.trim(),n=zi(t.length),o=null,i=1/0;for(let r=0;r<t.length;r+=n){let c=t[r];if(!c.trim())continue;let l=Gn(c.trim(),s);l<i&&(i=l,o={text:c,distance:l,line:r+1})}return o&&n>1&&(o=ef(t,s,o,n)||o,i=o.distance),Ki(i,e.length)?o:null}function ef(t,e,s,n){let o=s.line-1,i=Math.max(0,o-n),r=Math.min(t.length-1,o+n),c=s.distance,l=null;for(let u=i;u<=r;u++){let d=t[u];if(!d.trim())continue;let f=Gn(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function tf(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=zi(n),i=null,r=1/0;for(let c=0;c<n;c+=o){let l=t.slice(c,c+s).join(`
|
|
127
|
+
`),u=Gn(l,e);u<r&&(r=u,i={text:l,distance:u,line:c+1})}return i&&o>1&&(i=nf(t,e,i,o,s,n)||i,r=i.distance),Ki(r,e.length)?i:null}function nf(t,e,s,n,o,i){let r=s.line-1,c=Math.max(0,r-n),l=Math.min(i-1,r+n),u=s.distance,d=null;for(let f=c;f<=l;f++){let m=t.slice(f,f+o).join(`
|
|
128
|
+
`),h=Gn(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}Ji.exports={normalizeWhitespace:Vs,fuzzyFindText:Vd,findMostSimilar:Qd}});var Vi=L(($$,Xi)=>{var{C:g$}=ae(),sf=[{name:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{name:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{name:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{name:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{name:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{name:"GitHub Token",regex:/ghp_[a-zA-Z0-9]{36}/i},{name:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{name:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{name:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"'][^'"']{8,}/i}],of=[{name:"TODO",regex:/\bTODO\b/i,severity:"warn"},{name:"FIXME",regex:/\bFIXME\b/i,severity:"warn"},{name:"Debugger",regex:/\bdebugger\b/,severity:"error",ext:[".js",".ts",".jsx",".tsx"]},{name:"eval()",regex:/\beval\s*\(/,severity:"warn",ext:[".js",".ts",".jsx",".tsx"]},{name:"Console Log",regex:/\bconsole\.log\(/,severity:"info",ext:[".js",".ts",".jsx",".tsx"]},{name:"ANSI Code",regex:/\\x1b\[[0-9;]*m/,severity:"warn",message:"Avoid hardcoded ANSI codes; use cli/ui.js instead."}];function rf(t,e){let s=e.split(`
|
|
129
|
+
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let i=0;i<s.length;i++){let r=s[i],c=i+1;for(let l of sf)l.regex.test(r)&&n.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of of)l.ext&&!l.ext.includes(o)||l.regex.test(r)&&n.push({line:c,message:l.message||`Found ${l.name}`,severity:l.severity||"warn"})}return s.length>500&&n.push({line:0,message:`Large file detected (${s.length} lines). Consider refactoring.`,severity:"info"}),n}Xi.exports={runDiagnostics:rf}});var eo=L((y$,ea)=>{var af=require("fs").promises,Qi=require("path"),{exec:cf}=require("util").promisify(require("child_process").exec),Pt=[],Zs=null,zn=!1,Qs=0,lf=6e4;function Zi(t){return!(Pt.length===0||Zs!==t||Date.now()-Qs>lf)}async function uf(t){if(!zn&&!Zi(t)){zn=!0,Zs=t;try{try{let{stdout:n}=await cf("rg --files",{cwd:t,timeout:5e3});Pt=n.split(`
|
|
130
|
+
`).filter(Boolean),Qs=Date.now(),zn=!1;return}catch{}let e=[],s=async(n,o)=>{let i;try{i=await af.readdir(n,{withFileTypes:!0})}catch{return}for(let r of i){if(r.name==="node_modules"||r.name===".git"||r.name.startsWith("."))continue;let c=o?`${o}/${r.name}`:r.name;r.isDirectory()?await s(Qi.join(n,r.name),c):e.push(c)}};await s(t,""),Pt=e,Qs=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{zn=!1}}}function df(){return Pt}function ff(){return Zs}function mf(t){return Pt.filter(e=>Qi.basename(e)===t)}function pf(t){let e=t.toLowerCase();return Pt.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}ea.exports={refreshIndex:uf,getFileIndex:df,getIndexedCwd:ff,findFileInIndex:mf,searchIndex:pf,isIndexValid:Zi}});var Lt=L((w$,oa)=>{var Kn=require("fs"),Yn=require("path"),to=require("os"),{execFile:hf}=require("child_process"),{promisify:gf}=require("util"),no=gf(hf),$f=Yn.join(".nex","servers.json"),Jn=Yn.join(to.tmpdir(),"nex-ssh-sockets");function yf(){return Yn.join(process.cwd(),$f)}function ta(){let t=yf();if(!Kn.existsSync(t))return{};try{return JSON.parse(Kn.readFileSync(t,"utf-8"))}catch{return{}}}function wf(t){let e=ta();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,i]=t.includes("@")?t.split("@"):[void 0,t];return{host:i,user:o}}let s=Object.keys(e),n=s.length?`Available profiles: ${s.join(", ")}`:"No profiles configured. Create .nex/servers.json";throw new Error(`Unknown server: "${t}". ${n}`)}function bf(){Kn.existsSync(Jn)||Kn.mkdirSync(Jn,{recursive:!0})}function na(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,to.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),bf();let s=t.user?`${t.user}@${t.host}`:t.host,n=Yn.join(Jn,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function sa(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,to.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function xf(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=na(t),i=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:r,stderr:c}=await no("ssh",[...o,i],{timeout:s,maxBuffer:4194304});return{stdout:r||"",stderr:c||"",exitCode:0}}catch(r){let c=typeof r.code=="number"?r.code:1,l=(r.stderr||r.message||"").toString();return{stdout:(r.stdout||"").toString(),stderr:l,exitCode:c,error:Xn(l,t)}}}async function _f(t,e,s,{timeout:n=12e4}={}){let o=sa(t),i=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${i}:${s}`);try{let{stdout:r,stderr:c}=await no("scp",o,{timeout:n,maxBuffer:1048576});return r||c||`Uploaded ${e} \u2192 ${i}:${s}`}catch(r){let c=(r.stderr||r.message||"").toString();throw new Error(Xn(c,t)||c)}}async function kf(t,e,s,{timeout:n=12e4}={}){let o=sa(t),i=t.user?`${t.user}@${t.host}`:t.host;o.push(`${i}:${e}`,s);try{let{stdout:r,stderr:c}=await no("scp",o,{timeout:n,maxBuffer:1048576});return r||c||`Downloaded ${i}:${e} \u2192 ${s}`}catch(r){let c=(r.stderr||r.message||"").toString();throw new Error(Xn(c,t)||c)}}function Xn(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
|
|
125
131
|
HINT: Connection refused on ${e.host}:${s}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${s} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let s=e.key?`key: ${e.key}`:"SSH agent";return`${t}
|
|
126
132
|
HINT: Auth failed using ${s} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
|
|
127
133
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
128
134
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
129
135
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
130
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function
|
|
131
|
-
`,"utf-8")}
|
|
136
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function vf(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,n=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",i=e.key?` key:${e.key}`:"",r=e.sudo?" sudo:yes":"";return`${t}: ${s}${n}${o}${i}${r}`}oa.exports={loadServerProfiles:ta,resolveProfile:wf,buildSSHArgs:na,sshExec:xf,scpUpload:_f,scpDownload:kf,enrichSSHError:Xn,formatProfile:vf,SSH_SOCKET_DIR:Jn}});var ro=L((b$,ia)=>{var en=require("fs"),so=require("path"),Sf=so.join(".nex","deploy.json");function oo(){return so.join(process.cwd(),Sf)}function ra(){let t=oo();if(!en.existsSync(t))return{};try{return JSON.parse(en.readFileSync(t,"utf-8"))}catch{return{}}}function Ef(t){let e=ra();if(e[t])return{...e[t],_name:t};let s=Object.keys(e),n=s.length?`Available: ${s.join(", ")}`:"No deploy configs found. Create .nex/deploy.json or use explicit params.";throw new Error(`Unknown deploy config: "${t}". ${n}`)}function Tf(t){let e=so.join(process.cwd(),".nex");en.existsSync(e)||en.mkdirSync(e,{recursive:!0}),en.writeFileSync(oo(),JSON.stringify(t,null,2)+`
|
|
137
|
+
`,"utf-8")}ia.exports={loadDeployConfigs:ra,resolveDeployConfig:Ef,saveDeployConfigs:Tf,getDeployConfigPath:oo}});var nn=L((x$,la)=>{var io=null,ze=null,tn=null,aa=`Playwright is not installed. Install with:
|
|
132
138
|
npm install playwright && npx playwright install chromium
|
|
133
|
-
Then restart nex-code.`;function
|
|
134
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function
|
|
135
|
-
`)}function
|
|
139
|
+
Then restart nex-code.`;function ca(){if(tn!==null)return tn;try{require("playwright"),tn=!0}catch{tn=!1}return tn}async function Vn(){if(!ca())throw new Error(aa);return io||(io=require("playwright")),(!ze||!ze.isConnected())&&(ze=await io.chromium.launch({headless:!0})),ze}async function Cf(){if(ze){try{await ze.close()}catch{}ze=null}}process.on("exit",()=>{if(ze)try{ze.close()}catch{}});async function Rf(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await Vn()).newPage();try{await o.goto(t,{waitUntil:s,timeout:e});let i=await o.title(),r=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),c=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:i,url:o.url(),text:r.substring(0,8e3)+(r.length>8e3?`
|
|
140
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function Af(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let r=await(await Vn()).newPage();try{await r.setViewportSize({width:e,height:s}),await r.goto(t,{waitUntil:"networkidle",timeout:o});let c=await r.screenshot({type:"png",fullPage:n}),l=require("os"),u=require("path"),d=require("fs"),f=u.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(f,c),{path:f,base64:c.toString("base64"),media_type:"image/png",title:await r.title(),url:r.url()}}finally{await r.close()}}async function Of(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let i=await(await Vn()).newPage();try{await i.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await i.getByText(s,{exact:!1}).first().click({timeout:1e4}):await i.locator(e).first().click({timeout:1e4}),await i.waitForLoadState("domcontentloaded");let r=await i.title();return`Clicked \u2014 now at: ${i.url()} (${r})`}finally{await i.close()}}async function Nf(t,{selector:e,value:s,submit:n=!1,timeout:o=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let r=await(await Vn()).newPage();try{return await r.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await r.fill(e,String(s)),n&&(await r.keyboard.press("Enter"),await r.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${r.url()}`:"Not submitted."}`}finally{await r.close()}}la.exports={isPlaywrightAvailable:ca,browserNavigate:Rf,browserScreenshot:Af,browserClick:Of,browserFill:Nf,closeBrowser:Cf,INSTALL_MSG:aa}});var Qn=L((_$,ua)=>{var{C:Y}=ae(),on="",ge=[],sn=0,$t=null;function Mf(t){$t=t}function Pf(t,e){on=t,ge=[],sn=0;for(let n of e){sn++;let o=`t${sn}`;ge.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${sn}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=ge.map(n=>({...n}));return $t&&$t("create",{name:t,tasks:s}),s}function Lf(t,e,s){let n=ge.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),$t&&$t("update",{id:t,status:e,result:s}),{...n}):null}function If(){return{name:on,tasks:ge.map(t=>({...t}))}}function qf(){on="",ge=[],sn=0,$t&&$t("clear",{})}function jf(){return ge.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=ge.find(n=>n.id===e);return s&&s.status==="done"}))}function Df(){if(ge.length===0)return`${Y.dim}No active tasks${Y.reset}`;let t=[];on&&(t.push(` ${Y.bold}${Y.cyan}Tasks: ${on}${Y.reset}`),t.push(` ${Y.dim}${"\u2500".repeat(40)}${Y.reset}`));for(let o of ge){let i,r;switch(o.status){case"done":i="\u2713",r=Y.green;break;case"in_progress":i="\u2192",r=Y.cyan;break;case"failed":i="\u2717",r=Y.red;break;default:i="\xB7",r=Y.dim}let c=o.dependsOn.length>0?` ${Y.dim}(after: ${o.dependsOn.join(", ")})${Y.reset}`:"",l=`[${o.status}]`,u=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${r}${i}${Y.reset} ${Y.bold}${o.id}${Y.reset} ${u.padEnd(40)} ${r}${l}${Y.reset}${c}`),o.result&&o.status==="done"){let d=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${Y.dim}\u2192 ${d}${Y.reset}`)}}let e=ge.filter(o=>o.status==="done").length,s=ge.filter(o=>o.status==="failed").length,n=ge.length;return t.push(` ${Y.dim}${"\u2500".repeat(40)}${Y.reset}`),t.push(` ${Y.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${Y.reset}`),t.join(`
|
|
141
|
+
`)}function Ff(){return ge.length>0&&ge.some(t=>t.status==="pending"||t.status==="in_progress")}ua.exports={createTasks:Pf,updateTask:Lf,getTaskList:If,clearTasks:qf,getReadyTasks:jf,renderTaskList:Df,setOnChange:Mf,hasActiveTasks:Ff}});var co=L((k$,fa)=>{var{getActiveModel:Uf,getActiveProviderName:Wf}=he(),rn={essential:["bash","read_file","write_file","edit_file","list_directory"],standard:["bash","read_file","write_file","edit_file","list_directory","search_files","glob","grep","ask_user","git_status","git_diff","git_log","task_list","ssh_exec","service_manage","service_logs","container_list","container_logs","container_exec","container_manage","deploy"],full:null},an={"qwen3-coder:480b":"full","qwen3-coder-next":"full","kimi-k2.5":"full","kimi-k2:1t":"full","kimi-k2-thinking":"full","deepseek-v3.2":"full","deepseek-v3.1:671b":"full","devstral-2:123b":"full","devstral-small-2:24b":"standard","cogito-2.1:671b":"full","qwen3-next:80b":"full","qwen3.5:397b-cloud":"full","qwen3.5:397b":"full","qwen3.5:122b-a10b":"full","qwen3.5:35b-a3b":"full","qwen3.5:27b":"full","qwen3.5:9b":"standard","qwen3.5:4b":"essential","qwen3.5:2b":"essential","qwen3.5:0.8b":"essential","mistral-large-3:675b":"full","gpt-oss:120b":"full","minimax-m2.5":"full","glm-5":"full","glm-4.7":"standard","gemma3:27b":"standard","gemma3:12b":"essential","gemma3:4b":"essential","ministral-3:14b":"standard","ministral-3:8b":"essential","gpt-4o":"full","gpt-4.1":"full",o1:"full",o3:"full","o4-mini":"full","claude-sonnet":"full","claude-sonnet-4-5":"full","claude-opus":"full","claude-haiku":"standard","claude-sonnet-4":"full","gemini-3.1-pro-preview":"full","gemini-3-flash-preview":"full","gemini-2.5-pro":"full","gemini-2.5-flash":"full","gemini-2.0-flash":"standard","gemini-2.0-flash-lite":"essential"},cn={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},je={};function da(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(je=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{je={}}}da();function ao(){let e=Uf()?.id,s=Wf();return e&&je[e]?je[e]:s&&je[`${s}:*`]?je[`${s}:*`]:e&&an[e]?an[e]:s&&cn[s]?cn[s]:"full"}function Bf(t,e){return t&&je[t]?je[t]:e&&je[`${e}:*`]?je[`${e}:*`]:t&&an[t]?an[t]:e&&cn[e]?cn[e]:"full"}function Hf(t,e){let s=e||ao();if(s==="full"||!rn[s])return t;let n=new Set(rn[s]);return t.filter(o=>n.has(o.function.name))}function Gf(){let t=ao(),e=rn[t]?rn[t].length:"all";return{tier:t,toolCount:e}}fa.exports={filterToolsForModel:Hf,getActiveTier:ao,getModelTier:Bf,getTierInfo:Gf,TIERS:rn,MODEL_TIERS:an,PROVIDER_DEFAULT_TIER:cn,loadConfigOverrides:da}});var va=L((S$,ka)=>{var{callStream:zf,getActiveProviderName:es,getActiveModelId:Kf,getConfiguredProviders:Jf,getProvider:ma,getActiveProvider:pa,parseModelSpec:ha}=he(),{parseToolArgs:Yf}=qn(),{filterToolsForModel:Xf,getModelTier:Zn}=co(),{trackUsage:Vf}=At(),{MultiProgress:Qf,C:v$}=ae(),Zf=15,ga=5,$a=3,ts=new Map;function em(t,e){let s=ts.get(t);return s&&s!==e?!1:(ts.set(t,e),!0)}function ln(t){ts.delete(t)}function lo(){ts.clear()}function ya(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNRESET"||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("fetch failed")||e.includes("ETIMEDOUT")||e.includes("ENOTFOUND"))}async function wa(t,e,s){let n;for(let o=0;o<=$a;o++)try{return await zf(t,e,s)}catch(i){if(n=i,o<$a&&ya(i)){let c=(i.message||"").includes("429")?Math.min(2e3*Math.pow(2,o),15e3):Math.min(500*Math.pow(2,o),4e3);await new Promise(l=>setTimeout(l,c).unref());continue}throw i}throw n}var tm=new Set(["ask_user","task_list","spawn_agents"]),nm=new Set(["write_file","edit_file","patch_file"]),sm=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,om=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function ba(t){return om.test(t)?"full":sm.test(t)?"essential":"standard"}function xa(t){let e=Jf(),s=es(),n=[...e].sort((o,i)=>(o.name===s?-1:1)-(i.name===s?-1:1));for(let o of n)for(let i of o.models)if(Zn(i.id,o.name)===t)return{provider:o.name,model:i.id};return null}var rm={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function uo(t){if(t.model){let{provider:o,model:i}=ha(t.model),r=o?ma(o):pa(),c=o||es();if(r&&r.isConfigured()&&(r.getModel(i)||c==="local")){let l=Zn(i,c);return{provider:c,model:i,tier:l}}}let e=ba(t.task),s=rm[e];if(s){let{provider:o,model:i}=ha(s),r=o?ma(o):pa(),c=o||es();if(r&&r.isConfigured()&&(r.getModel(i)||c==="local")){let l=Zn(i,c);return{provider:c,model:i,tier:l}}}let n=xa(e);if(n){let o=Zn(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function _a(t,e={}){let s=Math.min(t.max_iterations||10,Zf),n=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,o=[],i={input:0,output:0},r=new Set,l=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
|
|
136
142
|
|
|
137
143
|
TASK: ${t.task}
|
|
138
144
|
${t.context?`
|
|
@@ -154,150 +160,153 @@ TOOL STRATEGY:
|
|
|
154
160
|
ERROR RECOVERY:
|
|
155
161
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
156
162
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
157
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=
|
|
158
|
-
`)}let y={};d&&(y.provider=d),f&&(y.model=f);try{for(let $=0;$<s;$++){let
|
|
159
|
-
...(truncated)`:
|
|
160
|
-
`)}catch(
|
|
161
|
-
`);for(let
|
|
162
|
-
`);for(let
|
|
163
|
-
...(truncated)`}let f=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(
|
|
164
|
-
${u}`),c+=o(u),c>=
|
|
163
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=uo(t),d=u.provider,f=u.model,m=u.tier,{TOOL_DEFINITIONS:h,executeTool:p}=qe(),g=Xf(h.filter($=>!tm.has($.function.name)),m);if(f&&!t._skipLog){let $=m?` (${m})`:"";process.stderr.write(` [sub-agent: ${d}:${f}${$}]
|
|
164
|
+
`)}let y={};d&&(y.provider=d),f&&(y.model=f);try{for(let $=0;$<s;$++){let _=await wa(l,g,y);if(!_||typeof _!="object")throw new Error("Empty or invalid response from provider");if(_.usage){let A=_.usage.prompt_tokens||0,B=_.usage.completion_tokens||0;i.input+=A,i.output+=B;let q=d||es(),Q=f||Kf();Vf(q,Q,A,B)}let T=_.content||"",k=_.tool_calls,v={role:"assistant",content:T||""};if(k&&k.length>0&&(v.tool_calls=k),l.push(v),!k||k.length===0){for(let A of r)ln(A);return{task:t.task,status:"done",result:T||"(no response)",toolsUsed:o,tokensUsed:i,modelSpec:d&&f?`${d}:${f}`:null}}let C=k.map(A=>{let B=A.function.name,q=Yf(A.function.arguments),Q=A.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!q)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${B}`,tool_call_id:Q});let ne=null;if(nm.has(B)&&q.path){let Z=require("path"),me=Z.isAbsolute(q.path)?q.path:Z.resolve(process.cwd(),q.path);if(r.has(me)||!em(me,n))return Promise.resolve({role:"tool",content:`ERROR: File '${q.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:Q});r.add(me),ne=me}return o.push(B),p(B,q,{autoConfirm:!0,silent:!0}).then(Z=>{ne&&(ln(ne),r.delete(ne));let me=String(Z??"");return{role:"tool",content:me.length>2e4?me.substring(0,2e4)+`
|
|
165
|
+
...(truncated)`:me,tool_call_id:Q}}).catch(Z=>(ne&&(ln(ne),r.delete(ne)),{role:"tool",content:`ERROR: ${Z.message}`,tool_call_id:Q}))}),S=await Promise.all(C);l.push(...S),e.onUpdate&&e.onUpdate(`step ${$+1}/${s}`)}for(let $ of r)ln($);return{task:t.task,status:"truncated",abortReason:"iteration_limit",result:l[l.length-1]?.content||"(max iterations reached)",toolsUsed:o,tokensUsed:i,modelSpec:d&&f?`${d}:${f}`:null}}catch($){for(let _ of r)ln(_);return{task:t.task,status:"failed",result:`Error: ${$.message}`,toolsUsed:o,tokensUsed:i,modelSpec:d&&f?`${d}:${f}`:null}}}async function im(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>ga)return`ERROR: Max ${ga} parallel agents allowed, got ${e.length}`;let s=e.map(i=>uo(i)),n=e.map((i,r)=>{let c=s[r],l=c.model?` [${c.model}]`:"",u=i.task.substring(0,44-l.length);return`Agent ${r+1}${l}: ${u}${i.task.length>u.length?"...":""}`}),o=new Qf(n);o.start();try{let i=e.map((d,f)=>{let m=s[f],h=m.model?{...d,model:`${m.provider}:${m.model}`,_skipLog:!0}:{...d,_skipLog:!0};return _a(h,{onUpdate:()=>{}}).then(p=>(o.update(f,p.status==="failed"?"error":"done"),p)).catch(p=>(o.update(f,"error"),{task:d.task,status:"failed",result:`Error: ${p.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),r=await Promise.all(i);o.stop(),lo();let c=["Sub-agent results:",""],l=0,u=0;for(let d=0;d<r.length;d++){let f=r[d],m=f.status==="done"?"\u2713":f.status==="truncated"?"\u26A0":"\u2717",h=f.modelSpec?` [${f.modelSpec}]`:"";c.push(`${m} Agent ${d+1}${h}: ${f.task}`),c.push(` Status: ${f.status}`),c.push(` Tools used: ${f.toolsUsed.length>0?f.toolsUsed.join(", "):"none"}`),c.push(` Result: ${f.result}`),c.push(""),l+=f.tokensUsed.input,u+=f.tokensUsed.output}return c.push(`Total sub-agent tokens: ${l} input + ${u} output`),c.join(`
|
|
166
|
+
`)}catch(i){return o.stop(),lo(),`ERROR: Sub-agent execution failed: ${i.message}`}}ka.exports={runSubAgent:_a,executeSpawnAgents:im,clearAllLocks:lo,classifyTask:ba,pickModelForTier:xa,resolveSubAgentModel:uo,isRetryableError:ya,callWithRetry:wa}});var fn=L((E$,qa)=>{var ee=require("fs"),Ke=require("path"),am=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 It(){let t=Ke.join(process.cwd(),".nex","brain");return ee.existsSync(t)||ee.mkdirSync(t,{recursive:!0}),t}function Sa(){return Ke.join(It(),".brain-index.json")}function po(){return Ke.join(It(),".embeddings.json")}function un(){let t=Ke.join(process.cwd(),".nex","brain");if(!ee.existsSync(t))return[];try{return ee.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=Ke.join(t,e),n=ee.statSync(s);return{name:e.replace(/\.md$/,""),path:s,size:n.size,modified:new Date(n.mtimeMs)}}).sort((e,s)=>s.modified-e.modified)}catch{return[]}}function dn(t){let e={},s=t,n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(n){let o=n[1].split(`
|
|
167
|
+
`);for(let i of o){let r=i.match(/^(\w+):\s*(.+)$/);if(!r)continue;let c=r[1].trim(),l=r[2].trim();l.startsWith("[")&&l.endsWith("]")?e[c]=l.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[c]=l}s=n[2]}return{frontmatter:e,body:s}}function Ea(t){let e=Ke.join(It(),`${t}.md`);if(!ee.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=ee.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=dn(s);return{name:t,content:s,body:o,frontmatter:n}}function cm(t,e){let s=Ke.join(It(),`${t}.md`);ee.writeFileSync(s,e,"utf-8"),dm(t,e),lm()}function lm(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=po();ee.existsSync(t)&&setImmediate(async()=>{try{await Ma()}catch{}})}function um(t){let e=Ke.join(It(),`${t}.md`);return ee.existsSync(e)?(ee.unlinkSync(e),fm(t),!0):!1}function ns(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!am.has(e))}function ho(t){let e={},{frontmatter:s,body:n}=dn(t),o=Array.isArray(s.tags)?s.tags:[];for(let r of o){let c=r.toLowerCase().replace(/[^a-z0-9-]/g,"");c.length>1&&(e[c]=(e[c]||0)+5)}let i=(n||t).split(`
|
|
168
|
+
`);for(let r of i)if(r.startsWith("#")){let c=r.replace(/^#+\s*/,"");for(let l of ns(c))e[l]=(e[l]||0)+3}for(let r of ns(n||t))e[r]=(e[r]||0)+1;return e}function go(){let t=Sa();if(!ee.existsSync(t))return{documents:{}};try{return JSON.parse(ee.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function $o(t){ee.writeFileSync(Sa(),JSON.stringify(t,null,2),"utf-8")}function dm(t,e){let s=go(),{frontmatter:n}=dn(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:ho(e),tags:o,modified:new Date().toISOString()},$o(s)}function fm(t){let e=go();delete e.documents[t],$o(e)}function mo(){let t=un(),e={documents:{}};for(let s of t){let n=ee.readFileSync(s.path,"utf-8"),{frontmatter:o}=dn(n),i=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:ho(n),tags:i,modified:s.modified.toISOString()}}return $o(e),e}function Ta(){let t=go(),e=un();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return mo()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return mo();return t}function Ca(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=ns(t);if(o.length===0)return[];let i=Ta(),r=[];for(let[c,l]of Object.entries(i.documents)){let u=0;for(let d of o){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>=n&&r.push({name:c,score:u})}return r.sort((c,l)=>l.score-c.score),r.slice(0,s)}var Ra=process.env.NEX_EMBED_MODEL||"nomic-embed-text",fo=400,mm=50;async function Aa(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return!1;try{let t=process.env.OLLAMA_HOST||"http://localhost:11434",e=require("http"),s=require("https"),n=new URL(`${t}/api/tags`),o=n.protocol==="https:"?s:e;return((await new Promise((c,l)=>{let u=o.get(n.toString(),{timeout:2e3},d=>{let f="";d.on("data",m=>f+=m),d.on("end",()=>{try{c(JSON.parse(f))}catch{l(new Error("bad json"))}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("timeout"))})})).models||[]).map(c=>c.name).some(c=>c.startsWith(Ra.split(":")[0]))}catch{return!1}}async function yo(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),n=require("https"),o=new URL(`${e}/api/embeddings`),i=o.protocol==="https:"?n:s,r=JSON.stringify({model:Ra,prompt:t});return new Promise((c,l)=>{let u=i.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)},timeout:3e4},d=>{let f="";d.on("data",m=>f+=m),d.on("end",()=>{try{c(JSON.parse(f).embedding||[])}catch(m){l(m)}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("embedding timeout"))}),u.write(r),u.end()})}function Oa(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,n=0,o=0;for(let r=0;r<t.length;r++)s+=t[r]*e[r],n+=t[r]*t[r],o+=e[r]*e[r];let i=Math.sqrt(n)*Math.sqrt(o);return i===0?0:s/i}function Na(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+fo).join(" ");if(s.push({text:o,offset:n}),n+fo>=e.length)break;n+=fo-mm}return s}async function Ma(){let t=un(),e={documents:{}},s=po();if(ee.existsSync(s))try{e=JSON.parse(ee.readFileSync(s,"utf-8"))}catch{}for(let n of t){let o=e.documents[n.name];if(o&&new Date(o.modified)>=n.modified)continue;let i=ee.readFileSync(n.path,"utf-8"),r=Na(i),c=[];for(let l of r){let u=await yo(l.text);c.push({text:l.text,embedding:u,offset:l.offset})}e.documents[n.name]={chunks:c,modified:n.modified.toISOString()}}for(let n of Object.keys(e.documents))t.some(o=>o.name===n)||delete e.documents[n];return ee.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function Pa(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=po();if(!ee.existsSync(o))return[];let i;try{i=JSON.parse(ee.readFileSync(o,"utf-8"))}catch{return[]}let r=await yo(t),c=[];for(let[l,u]of Object.entries(i.documents||{})){let d=0,f="";for(let m of u.chunks||[]){let h=Oa(r,m.embedding);h>d&&(d=h,f=m.text)}d>=n&&c.push({name:l,score:d,bestChunk:f})}return c.sort((l,u)=>u.score-l.score),c.slice(0,s)}function La(t,e,s={}){let{k:n=60,topK:o=3}=s,i={};return t.forEach((r,c)=>{i[r.name]=(i[r.name]||0)+1/(n+c+1)}),e.forEach((r,c)=>{i[r.name]=(i[r.name]||0)+1/(n+c+1)}),Object.entries(i).map(([r,c])=>({name:r,score:c})).sort((r,c)=>c.score-r.score).slice(0,o)}async function Ia(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=Ca(t,{topK:s,minScore:n}),i=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await Aa()){let c=await Pa(t,{topK:s});i=La(o,c,{topK:s})}}catch{}return i.map(r=>{let c=Ea(r.name),l=(c.body||c.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:r.name,score:r.score,content:c.content,excerpt:l}})}async function pm(t){if(!t||!t.trim())return"";let e=Ke.join(process.cwd(),".nex","brain");if(!ee.existsSync(e)||un().length===0)return"";let n;try{n=await Ia(t,{topK:3})}catch{return""}if(!n||n.length===0)return"";let o;try{o=Oe().estimateTokens}catch{o=l=>Math.ceil(l.length/4)}let i=25e3,r=[],c=0;for(let l of n){let u=l.content||"",d=o(u);if(c+d>i){let m=i-c;if(m<100)break;let h=m/d;u=u.slice(0,Math.floor(u.length*h))+`
|
|
169
|
+
...(truncated)`}let f=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(r.push(`--- ${l.name} (relevance: ${f}) ---
|
|
170
|
+
${u}`),c+=o(u),c>=i)break}return r.length===0?"":`KNOWLEDGE BASE (auto-selected):
|
|
165
171
|
|
|
166
|
-
${
|
|
172
|
+
${r.join(`
|
|
167
173
|
|
|
168
|
-
`)}`}
|
|
169
|
-
${
|
|
170
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
174
|
+
`)}`}qa.exports={getBrainDir:It,listDocuments:un,readDocument:Ea,writeDocument:cm,removeDocument:um,buildIndex:mo,getIndex:Ta,query:Ia,getBrainContext:pm,isEmbeddingAvailable:Aa,generateEmbedding:yo,buildEmbeddingIndex:Ma,semanticQuery:Pa,cosineSimilarity:Oa,_keywordQuery:Ca,_extractKeywords:ho,_chunkText:Na,parseFrontmatter:dn,tokenize:ns,_fuseResults:La}});var qe=L((A$,Ja)=>{var te=require("fs").promises,ja=require("fs"),xe=require("path"),oe=require("util").promisify(require("child_process").exec),Da=require("util").promisify(require("child_process").execFile),{spawnSync:hm}=require("child_process"),wo=require("axios"),{isForbidden:gm,isDangerous:$m,isCritical:Fa,confirm:De}=Ie(),{showClaudeDiff:ss,showClaudeNewFile:ym,showEditDiff:T$,confirmFileChange:mn}=Si(),{C:I,Spinner:Ga,getToolSpinnerText:wm}=ae(),{isGitRepo:bo,getCurrentBranch:Ua,getStatus:bm,getDiff:xm}=gt(),{recordChange:os}=Nt(),{fuzzyFindText:Wa,findMostSimilar:_o}=Yi(),{runDiagnostics:pn}=Vi(),{findFileInIndex:_m,getFileIndex:C$}=eo(),{resolveProfile:Fe,sshExec:nt,scpUpload:km,scpDownload:vm}=Lt(),{resolveDeployConfig:Sm,loadDeployConfigs:R$}=ro(),Em=/^(vim?|nano|emacs|pico|less|more|top|htop|iftop|iotop|glances|telnet\s|screen|tmux|fzf|gum|dialog|whiptail|man\s|node\s*$|python3?\s*$|irb\s*$|rails\s*c|psql\s|mysql\s|redis-cli|mongosh?|sqlite3)\b/,Tm=/^ssh\s/,Cm=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function rs(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=be(e);if(s&&await te.access(s).then(()=>!0).catch(()=>!1))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=xe.extname(t);if(!o)for(let r of n){let c=be(t+r);if(c&&await te.access(c).then(()=>!0).catch(()=>!1))return{fixedPath:c,message:`(auto-fixed: added ${r} extension)`}}if(o){let r=t.replace(/\.[^.]+$/,"");for(let c of n){if(c===o)continue;let l=be(r+c);if(l&&await te.access(l).then(()=>!0).catch(()=>!1))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${c})`}}}let i=xe.basename(t);if(i&&i.length>2)try{let r=_m(i).map(c=>be(c));if(r.length===1)return{fixedPath:r[0],message:`(auto-fixed: found ${i} at ${xe.relative(process.cwd(),r[0])})`};if(r.length>1&&r.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
175
|
+
${r.map(l=>xe.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
176
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function Rm(t){return/\bprintenv\b/.test(t)?"printenv exposes all secrets. Use `echo $VAR_NAME` for a single variable, or `env | grep PATTERN` for filtered output.":/cat\s+.*\.env\b/.test(t)?'Reading .env directly is blocked. Use `grep -v "KEY=" .env` to inspect non-secret entries, or ask the user to share specific values.':/cat\s+.*credentials/i.test(t)?"Credentials files are blocked. Reference the variable name from the application config instead.":/python3?\s+-c\s/.test(t)?"Inline python -c is blocked. Write a temporary script file and run it with `python3 script.py` instead.":/node\s+-e\s/.test(t)?"Inline node -e is blocked. Write a temporary script file and run it with `node script.js` instead.":/curl.*-X\s*POST|curl.*--data/.test(t)?"curl POST is blocked to prevent data exfiltration. Use the application's own API client or ask the user to run the request.":/base64.*\|.*bash/.test(t)?"Piping base64-decoded content to bash is blocked. Decode the content first, inspect it, then run explicitly.":/\beval\s*\(/.test(t)?"eval is blocked. Execute the command directly without eval.":/(?:^|[;&|]\s*)history(?:\s|$)/.test(t)?"Shell history is blocked. Look at git log or project files for context instead.":""}function za(t,e){let s=[];if(/command not found|not recognized/i.test(t)){let n=e.match(/^(\S+)/),o=n?n[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?s.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?s.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):s.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let n=t.match(/Cannot find module '([^']+)'/),o=n?n[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?s.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):s.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&s.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let n=t.match(/port (\d+)|:(\d+)/),o=n?n[1]||n[2]:"";s.push(`HINT: Port ${o||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&s.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&s.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&s.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&s.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let n=t.match(/curl:\s*\((\d+)\)/),o=n?parseInt(n[1],10):null;o===6||/Could not resolve host/i.test(t)?s.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?s.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?s.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?s.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===35||/SSL.*error/i.test(t))&&s.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let n=t.match(/port (\d+)/),o=n?n[1]:"";s.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&s.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&s.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),s.length===0?t:t+`
|
|
171
177
|
|
|
172
178
|
`+s.join(`
|
|
173
|
-
`)}function Da(t,e,s){let n=$o(t,e);if(!n)return null;let o=Math.max(3,Math.ceil(e.length*.05));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var La=!1,un=null;function _m(){un&&(un(),un=null)}async function go(){if(!La){La=!0;try{let{stdout:t}=await Z("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Z('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Z("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Z("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var km=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function be(t){let e=xe.isAbsolute(t)?xe.resolve(t):xe.resolve(process.cwd(),t);for(let s of km)if(s.test(e))return null;return e}var vm=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Use this to find where functions/variables/classes are defined or used. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when requirements are ambiguous, you need to choose between approaches, or a decision has significant impact. Do not ask unnecessary questions \u2014 proceed if the intent is clear.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"deploy",description:'Deploy files to a remote server via rsync + optional remote script. Can use a named config from .nex/deploy.json (e.g. deploy("prod")) or explicit params. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},local_path:{type:"string",description:'Local directory or file to sync (e.g. "dist/", "./build"). Required if no config.'},remote_path:{type:"string",description:'Remote destination path (e.g. "/var/www/app"). Required if no config.'},deploy_script:{type:"string",description:"Shell command to run on the remote after sync. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from sync. Optional."},dry_run:{type:"boolean",description:"Show what would be synced without actually syncing. Default: false."}},required:[]}}}];function ln(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function Ia(t,e,s={}){switch(t){case"bash":{let n=e.command,o=cm(n);if(o){let u=xm(n);return`BLOCKED: Command matches forbidden pattern: ${o}${u?`
|
|
174
|
-
HINT: ${u}`:""}`}if(s.autoConfirm?
|
|
175
|
-
${
|
|
176
|
-
${f}`}}case"read_file":{let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await
|
|
177
|
-
`+m.message:""}`}let
|
|
179
|
+
`)}function Ka(t,e,s){let n=_o(t,e);if(!n)return null;let o=Math.max(3,Math.ceil(e.length*.05));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var Ba=!1,yt=null;function Am(){yt&&(yt(),yt=null)}var ko=null;function Om(t){ko=t}async function xo(){if(!Ba){Ba=!0;try{let{stdout:t}=await oe("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await oe('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await oe("git stash pop",{cwd:process.cwd(),timeout:1e4}),await oe("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Nm=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function be(t){let e=xe.isAbsolute(t)?xe.resolve(t):xe.resolve(process.cwd(),t);for(let s of Nm)if(s.test(e))return null;return e}var Mm=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail. Files are read with UTF-8 encoding. For binary files, use bash with appropriate flags. Alternative: use util.promisify(fs.readFile) for programmatic access.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Use this to find where functions/variables/classes are defined or used. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"deploy",description:'Deploy files to a remote server via rsync + optional remote script. Can use a named config from .nex/deploy.json (e.g. deploy("prod")) or explicit params. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},local_path:{type:"string",description:'Local directory or file to sync (e.g. "dist/", "./build"). Required if no config.'},remote_path:{type:"string",description:'Remote destination path (e.g. "/var/www/app"). Required if no config.'},deploy_script:{type:"string",description:"Shell command to run on the remote after sync. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from sync. Optional."},dry_run:{type:"boolean",description:"Show what would be synced without actually syncing. Default: false."}},required:[]}}}];function hn(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,i="kubectl";if(o&&(i+=` --context ${o}`),i+=` ${t}`,n){let r=i.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${r}"`}return i}async function Ha(t,e,s={}){switch(t){case"bash":{let n=e.command,o=gm(n);if(o){let u=Rm(n);return`BLOCKED: Command matches forbidden pattern: ${o}${u?`
|
|
180
|
+
HINT: ${u}`:""}`}if(s.autoConfirm?Fa(n):$m(n)){let u=Fa(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
|
|
181
|
+
${I.yellow}${u}: ${n}${I.reset}`),!await De(" Execute?"))return"CANCELLED: User declined to execute this command."}let r=process.cwd();try{ja.accessSync(r)}catch{r=require("os").homedir(),s.silent||console.log(`${I.yellow} \u26A0 Working directory no longer exists \u2014 running in ${r}${I.reset}`)}let c=Tm.test(n.trim())&&!Cm.test(n.trim());if(Em.test(n.trim())||c){s.silent||console.log(`${I.dim} \u25B6 interactive: ${n}${I.reset}`);let u=hm("sh",["-c",n],{stdio:"inherit",cwd:r});return u.error?`ERROR: ${u.error.message}`:u.status===0?"(interactive command completed successfully)":`(interactive command exited with code ${u.status})`}let l=s.silent?null:new Ga(`Running: ${n.substring(0,60)}${n.length>60?"...":""}`);l&&l.start();try{let{stdout:u,stderr:d}=await oe(n,{cwd:r,timeout:9e4,maxBuffer:5242880});return l&&l.stop(),u||d||"(no output)"}catch(u){l&&l.stop();let d=(u.stderr||u.stdout||u.message||"").toString().substring(0,5e3),f=za(d,n);return`EXIT ${u.code||1}
|
|
182
|
+
${f}`}}case"read_file":{let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await te.access(n).then(()=>!0).catch(()=>!1)){let m=await rs(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${I.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${xe.relative(process.cwd(),n)}${I.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
183
|
+
`+m.message:""}`}let i=Buffer.alloc(8192),r=await ja.promises.open(n,"r"),{bytesRead:c}=await r.read(i,0,8192,0);await r.close();for(let m=0;m<c;m++)if(i[m]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let l=await te.readFile(n,"utf-8");if(!l&&(await te.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let u=l.split(`
|
|
178
184
|
`),d=(e.line_start||1)-1,f=e.line_end||u.length;return u.slice(d,f).map((m,h)=>`${d+h+1}: ${m}`).join(`
|
|
179
|
-
`)}case"write_file":{await
|
|
180
|
-
`+d.message:""}`}let
|
|
185
|
+
`)}case"write_file":{await xo();let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await te.access(n).then(()=>!0).catch(()=>!1),i=null;if(s.autoConfirm)o&&(i=await te.readFile(n,"utf-8"));else if(o){i=await te.readFile(n,"utf-8");let l=await pn(n,e.content);if(ss(n,i,e.content,{annotations:l}),!await mn("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let l=await pn(n,e.content);if(ym(n,e.content,{annotations:l}),!await mn("Create"))return"CANCELLED: User declined to create file."}let r=xe.dirname(n);return await te.access(r).then(()=>!0).catch(()=>!1)||await te.mkdir(r,{recursive:!0}),await te.writeFile(n,e.content,"utf-8"),os("write_file",n,i,e.content),`Written: ${n} (${e.content.length} chars)`}case"edit_file":{await xo();let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await te.access(n).then(()=>!0).catch(()=>!1)){let d=await rs(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${I.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${xe.relative(process.cwd(),n)}${I.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
186
|
+
`+d.message:""}`}let i=await te.readFile(n,"utf-8"),r=e.old_text,c=!1,l=!1;if(!i.includes(e.old_text)){let d=Wa(i,e.old_text);if(d)r=d,c=!0,console.log(`${I.dim} \u2713 fuzzy whitespace match applied${I.reset}`);else{let f=Ka(i,e.old_text,e.new_text);if(f){if(!s.autoConfirm){let p=await pn(n,f.content);if(ss(n,i,f.content,{annotations:p}),!await mn(`Apply (auto-fix, line ${f.line}, distance ${f.distance})`))return"CANCELLED: User declined to apply edit."}await te.writeFile(n,f.content,"utf-8"),os("edit_file",n,i,f.content);let h=f.matchText.length>80?f.matchText.substring(0,77)+"...":f.matchText;return console.log(`${I.dim} \u2713 auto-fixed edit: line ${f.line}, distance ${f.distance}${I.reset}`),`Edited: ${n} (auto-fixed, line ${f.line}, distance ${f.distance}, matched: "${h}")`}let m=_o(i,e.old_text);return m?`ERROR: old_text not found in ${n}
|
|
181
187
|
Most similar text (line ${m.line}, distance ${m.distance}):
|
|
182
|
-
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=
|
|
183
|
-
`)||"(empty)"}case"search_files":{let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,n);try{let{stdout:
|
|
184
|
-
`).
|
|
185
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),
|
|
186
|
-
`);return
|
|
187
|
-
|
|
188
|
-
\u26A0 Results truncated at 200. Use a more specific pattern.`:
|
|
189
|
-
`).
|
|
190
|
-
`).trim()||"(no matches)"}catch(
|
|
191
|
-
`+m.message:""}`}let
|
|
188
|
+
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=i.split(r).join(e.new_text),f=await pn(n,d);if(ss(n,i,d,{annotations:f}),!await mn(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=i.split(r).join(e.new_text);return await te.writeFile(n,u,"utf-8"),os("edit_file",n,i,u),c?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await te.access(n).then(()=>!0).catch(()=>!1)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=be(u),f=await te.access(d).then(()=>!0).catch(()=>!1);if(d&&f)n=d;else return`ERROR: Directory not found: ${e.path}`}let i=e.max_depth||2,r=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");r=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let c=[],l=async(u,d,f)=>{if(d>i)return;let m;try{m=await te.readdir(u,{withFileTypes:!0})}catch{return}m=m.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of m){if(r&&!h.isDirectory()&&!r.test(h.name))continue;let p=h.isDirectory()?"/":"";c.push(`${f}${h.name}${p}`),h.isDirectory()&&await l(xe.join(u,h.name),d+1,f+" ")}};return await l(n,1,""),c.join(`
|
|
189
|
+
`)||"(empty)"}case"search_files":{let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn","--null","-H"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,n);try{let{stdout:i}=await Da("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),r=i.split("\0"),c=[];for(let l=0;l<r.length;l+=2){let u=r[l],d=r[l+1];if(u&&d){let f=d.split(`
|
|
190
|
+
`).filter(m=>m.trim());for(let m of f)if(c.push(`${u}:${m}`),c.length>=50)break}if(c.length>=50)break}return c.join(`
|
|
191
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),i=e.path?be(e.path):o,r=e.pattern,c=k=>{let v=k.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${v}$`)},l=c(r),u=r.split("/").pop(),d=c(u),{getFileIndex:f,getIndexedCwd:m,refreshIndex:h,isIndexValid:p}=eo(),g=f(),y=m();p(i)||(await h(i),g=f());let $=g.filter(k=>l.test(k)||d.test(xe.basename(k))).map(k=>xe.join(i,k));if($.length===0)return"(no matches)";let _=$.length>200,T=$.slice(0,200).join(`
|
|
192
|
+
`);return _?`${T}
|
|
193
|
+
|
|
194
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:T}case"grep":{let n=e.path?be(e.path):process.cwd(),o=["-rn","-E","--null","-H"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,n);try{let{stdout:i}=await Da("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),r=i.split("\0"),c=[];for(let l=0;l<r.length;l+=2){let u=r[l],d=r[l+1];if(u&&d){let f=d.split(`
|
|
195
|
+
`).filter(m=>m.trim());for(let m of f)if(c.push(`${u}:${m}`),c.length>=100)break}if(c.length>=100)break}return c.join(`
|
|
196
|
+
`).trim()||"(no matches)"}catch(i){return i.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await xo();let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await te.access(n).then(()=>!0).catch(()=>!1)){let m=await rs(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${I.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${xe.relative(process.cwd(),n)}${I.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
197
|
+
`+m.message:""}`}let i=e.patches;if(!Array.isArray(i)||i.length===0)return"ERROR: No patches provided";let r=await te.readFile(n,"utf-8"),c=[],l=!1,u=!1;for(let m=0;m<i.length;m++){let{old_text:h,new_text:p}=i[m];if(r.includes(h))c.push({old_text:h,new_text:p});else{let g=Wa(r,h);if(g)c.push({old_text:g,new_text:p}),l=!0;else{let y=_o(r,h);if(y){let $=Math.max(3,Math.ceil(h.length*.05));if(y.distance<=$)c.push({old_text:y.text,new_text:p}),u=!0;else return`ERROR: Patch ${m+1} old_text not found in ${n}
|
|
192
198
|
Most similar text (line ${y.line}, distance ${y.distance}):
|
|
193
|
-
${y.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${n}`}}}let d=
|
|
199
|
+
${y.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${n}`}}}let d=r;for(let{old_text:m,new_text:h}of c)d=d.split(m).join(h);if(!s.autoConfirm){let m=await pn(n,d);if(ss(n,r,d,{annotations:m}),!await mn(l?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await te.writeFile(n,d,"utf-8"),os("patch_file",n,r,d);let f=u?" (auto-fixed)":l?" (fuzzy match)":"";return`Patched: ${n} (${i.length} replacements)${f}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let i=await wo.get(n,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof i.data=="string"?i.data:JSON.stringify(i.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,o)||"(empty response)"}catch(i){return`ERROR: Failed to fetch ${n}: ${i.message}`}}case"web_search":{let n=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await wo.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"}}),i=o.data?.choices?.[0]?.message?.content||"",r=o.data?.citations||[],c=`[Perplexity grounded search]
|
|
194
200
|
|
|
195
|
-
${
|
|
201
|
+
${i}`;return r.length>0&&(c+=`
|
|
196
202
|
|
|
197
203
|
Sources:
|
|
198
|
-
`+
|
|
199
|
-
`)),c}catch(o){console.error(`${
|
|
204
|
+
`+r.slice(0,n).map((l,u)=>`${u+1}. ${l}`).join(`
|
|
205
|
+
`)),c}catch(o){console.error(`${I.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${I.reset}`)}try{let i=(await wo.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,r=[],c=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=c.exec(i))!==null&&r.length<n;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],d=l[2].replace(/<[^>]+>/g,"").trim();try{r.push({title:d,url:decodeURIComponent(u)})}catch{r.push({title:d,url:u})}}return r.length===0?"(no results)":r.map((u,d)=>`${d+1}. ${u.title}
|
|
200
206
|
${u.url}`).join(`
|
|
201
207
|
|
|
202
|
-
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=
|
|
208
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=nn();try{let o=await n(e.url,{waitFor:e.wait_for}),i=o.links.length>0?`
|
|
203
209
|
|
|
204
210
|
Links:
|
|
205
|
-
`+o.links.map(
|
|
211
|
+
`+o.links.map(r=>` ${r.text} \u2192 ${r.href}`).join(`
|
|
206
212
|
`):"";return`Title: ${o.title}
|
|
207
213
|
URL: ${o.url}
|
|
208
214
|
|
|
209
|
-
${o.text}${
|
|
215
|
+
${o.text}${i}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=nn();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
|
|
210
216
|
Title: ${o.title}
|
|
211
217
|
URL: ${o.url}
|
|
212
218
|
|
|
213
|
-
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=
|
|
214
|
-
${
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
219
|
+
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=nn();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=nn();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"ask_user":{let{question:n,options:o=[]}=e;return ko?new Promise(i=>{yt=()=>i("CANCELLED"),ko(n,o).then(r=>{yt=null,i(r||"User did not answer")})}):new Promise(i=>{let r=require("readline").createInterface({input:process.stdin,output:process.stdout});yt=()=>{r.close(),i("CANCELLED")};let c=o.length>0?`
|
|
220
|
+
${o.map((l,u)=>` ${u+1}. ${l}`).join(`
|
|
221
|
+
`)}
|
|
222
|
+
`:"";console.log(`
|
|
223
|
+
${I.cyan}${I.bold} ? ${n}${I.reset}${c}`),r.question(`${I.cyan} > ${I.reset}`,l=>{yt=null,r.close(),i(l.trim()||"(no response)")})})}case"git_status":{if(!await bo())return"ERROR: Not a git repository";let n=await Ua()||"(detached)",o=await bm();if(o.length===0)return`Branch: ${n}
|
|
224
|
+
Clean working tree (no changes)`;let i=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let r of o){let c=r.status==="M"?"modified":r.status==="A"?"added":r.status==="D"?"deleted":r.status==="??"?"untracked":r.status;i.push(` ${c}: ${r.file}`)}return i.join(`
|
|
225
|
+
`)}case"git_diff":{if(!await bo())return"ERROR: Not a git repository";let n;if(e.file){let o=["diff"];e.staged&&o.push("--cached"),o.push("--",e.file);try{n=execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{n=""}}else n=await xm(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await bo())return"ERROR: Not a git repository";let o=["log","--oneline",`-${Math.min(e.count||10,50)}`];e.file&&o.push("--",e.file);try{return execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()||"(no commits)"}catch{return"(no commits)"}}case"task_list":{let{createTasks:n,updateTask:o,getTaskList:i,renderTaskList:r,hasActiveTasks:c}=Qn(),{getActiveTaskProgress:l}=ae(),u=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let d=n(e.name,e.tasks);return u||console.log(`
|
|
226
|
+
`+r()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
218
227
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
219
228
|
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":o(e.task_id,e.status,e.result)?(u||console.log(`
|
|
220
|
-
`+
|
|
221
|
-
`+
|
|
222
|
-
`)}catch(
|
|
223
|
-
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:
|
|
224
|
-
...(truncated)`:"")}let{stdout:n}=await
|
|
229
|
+
`+r()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let d=i();return d.tasks.length===0?"No active tasks":(u||console.log(`
|
|
230
|
+
`+r()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=va();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:i}=he();return n(e.model)?`Switched to ${o()}:${i()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let n=Math.min(e.limit||10,30),o=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:i}=await oe(`gh ${o.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),r=JSON.parse(i||"[]");return r.length===0?"No workflow runs found.":r.map(l=>{let u=l.conclusion||l.status||"unknown",d=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",f=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${d} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${u} \xB7 ${f}`}).join(`
|
|
231
|
+
`)}catch(i){let r=(i.stderr||i.message||"").toString();return r.includes("not found")||r.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${r.split(`
|
|
232
|
+
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:r}=await oe(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return r.substring(0,8e3)+(r.length>8e3?`
|
|
233
|
+
...(truncated)`:"")}let{stdout:n}=await oe(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),i=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let r of o.jobs||[]){let c=r.conclusion==="success"?"\u2713":r.conclusion==="failure"?"\u2717":"\u25CB";i.push(` ${c} ${r.name} (${r.conclusion||r.status})`);for(let l of r.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";i.push(` ${u} ${l.name}`)}}return i.join(`
|
|
225
234
|
`)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
|
|
226
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=
|
|
227
|
-
${
|
|
228
|
-
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",
|
|
229
|
-
`)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,
|
|
235
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Ie(),o=e.branch||await Ua()||"main",i=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",r=`gh workflow run ${e.workflow} --ref ${o} ${i}`.trim();if(console.log(`
|
|
236
|
+
${I.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${I.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await oe(r,{cwd:process.cwd(),timeout:3e4}),`Workflow "${e.workflow}" triggered on branch "${o}". Check status with gh_run_list.`}catch(l){return`ERROR: ${(l.stderr||l.message||"").toString().split(`
|
|
237
|
+
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",i=hn(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:r,stderr:c}=await oe(i,{timeout:3e4,maxBuffer:2097152});return(r||c||"(no pods)").trim()}catch(r){let c=(r.stderr||r.message||"").toString().split(`
|
|
238
|
+
`)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,i=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(i+=` --since=${e.since}`),e.container&&(i+=` -c ${e.container}`);let r=hn(i,e);try{let{stdout:c,stderr:l}=await oe(r,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
|
|
230
239
|
...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
231
240
|
`)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let n=e.namespace||"default";if(console.log(`
|
|
232
|
-
${
|
|
233
|
-
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let n=!!e.dry_run;if(!n){let
|
|
234
|
-
${
|
|
241
|
+
${I.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${I.reset}`),console.log(`${I.dim} Command: ${e.command}${I.reset}`),!await De(" Execute in pod?"))return"CANCELLED: User declined.";let i=`exec ${e.pod} -n ${n}`;e.container&&(i+=` -c ${e.container}`),i+=` -- sh -c ${JSON.stringify(e.command)}`;let r=hn(i,e);try{let{stdout:c,stderr:l}=await oe(r,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
242
|
+
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let n=!!e.dry_run;if(!n){let r=e.file;if(console.log(`
|
|
243
|
+
${I.yellow} \u26A0 kubectl apply: ${r}${e.namespace?` (ns: ${e.namespace})`:""}${I.reset}`),!await De(" Apply to cluster?"))return"CANCELLED: User declined."}let o=`apply -f ${e.file}`;e.namespace&&(o+=` -n ${e.namespace}`),n&&(o+=" --dry-run=client");let i=hn(o,e);try{let{stdout:r,stderr:c}=await oe(i,{timeout:12e4,maxBuffer:2097152});return(r||c||"(no output)").trim()}catch(r){return`ERROR: ${(r.stderr||r.message||"").toString().split(`
|
|
235
244
|
`)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let n=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let c=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
|
|
236
|
-
${
|
|
237
|
-
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=
|
|
245
|
+
${I.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${n})${I.reset}`),!await De(` ${c}?`))return"CANCELLED: User declined."}let i=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,r=hn(i,e);try{let{stdout:c,stderr:l}=await oe(r,{timeout:12e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
246
|
+
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=fn(),{name:i,content:r,mode:c}=e;if(c==="create"&&o(i).content)return`ERROR: Document "${i}" already exists. Use mode "update" to overwrite.`;if(c==="append"){let l=o(i),u=l.content?l.content+`
|
|
238
247
|
|
|
239
|
-
`+
|
|
240
|
-
${
|
|
248
|
+
`+r:r;return n(i,u),`Appended to brain document: ${i}.md`}return n(i,r),`${c==="create"?"Created":"Updated"} brain document: ${i}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=Fe(e.server)}catch(h){return`ERROR: ${h.message}`}let o=e.command,i=!!e.sudo,r=(e.timeout||30)*1e3;if(/\b(rm|rmdir|mv|cp|chmod|chown|dd|mkfs|systemctl\s+(start|stop|restart|reload|enable|disable)|dnf\s+(install|remove|update|upgrade)|yum\s+(install|remove)|apt(-get)?\s+(install|remove|purge)|pip\s+install|pip3\s+install|firewall-cmd\s+--permanent|semanage|setsebool|passwd|userdel|useradd|nginx\s+-s\s+(reload|stop)|service\s+\w+\s+(start|stop|restart))\b/.test(o)){let h=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
249
|
+
${I.yellow} \u26A0 Remote command on ${h}: ${o}${I.reset}`),!await De(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await nt(n,o,{timeout:r,sudo:i}),m=[l,u].filter(Boolean).join(`
|
|
241
250
|
`).trim();return d!==0?`EXIT ${d}
|
|
242
|
-
${f||m||"(no output)"}`:m||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=
|
|
243
|
-
${
|
|
244
|
-
${
|
|
245
|
-
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await
|
|
246
|
-
`).trim();return d!==0?/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${e.service}" not found on ${
|
|
247
|
-
${f||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,
|
|
248
|
-
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=
|
|
251
|
+
${f||m||"(no output)"}`:m||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=Fe(e.server)}catch(r){return`ERROR: ${r.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
252
|
+
${I.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${I.reset}`),!await De(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await km(n,e.local_path,e.remote_path)}catch(r){return`ERROR: ${r.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let n;try{n=Fe(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await vm(n,e.remote_path,e.local_path)}catch(o){return`ERROR: ${o.message}`}}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let n=["status","start","stop","restart","reload","enable","disable"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost",i=e.action==="status",r=null;if(!o)try{r=Fe(e.server)}catch(l){return`ERROR: ${l.message}`}if(!i){let l=o?"local machine":r.user?`${r.user}@${r.host}`:r.host;if(console.log(`
|
|
253
|
+
${I.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${I.reset}`),!await De(" Execute?"))return"CANCELLED: User declined service action."}let c=`systemctl ${e.action} ${e.service}`;if(o){let u=e.action!=="status"?`sudo ${c}`:c;try{let{stdout:d,stderr:f}=await oe(u,{timeout:15e3});return(d||f||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(d){let f=(d.stderr||d.message||"").toString().trim();return/not found|loaded.*not-found/i.test(f)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${d.code||1}
|
|
254
|
+
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await nt(r,c,{timeout:15e3,sudo:!0}),m=[l,u].filter(Boolean).join(`
|
|
255
|
+
`).trim();return d!==0?/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${e.service}" not found on ${r.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${d}
|
|
256
|
+
${f||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,i=e.since?`--since "${e.since}"`:"",r=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${o} ${i} ${r} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:p,stderr:g}=await oe(c,{timeout:15e3});return(p||g||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
|
|
257
|
+
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=Fe(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await nt(l,c,{timeout:2e4}),h=[u,d].filter(Boolean).join(`
|
|
249
258
|
`).trim();return f!==0?`EXIT ${f}
|
|
250
|
-
${m||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",
|
|
251
|
-
${(m.stderr||m.message||"").toString().trim()}`}let
|
|
259
|
+
${m||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",i=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:m,stderr:h}=await oe(i,{timeout:1e4});return(m||h||"(no containers)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
260
|
+
${(m.stderr||m.message||"").toString().trim()}`}let r;try{r=Fe(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await nt(r,i,{timeout:15e3}),f=[c,l].filter(Boolean).join(`
|
|
252
261
|
`).trim();return u!==0?`EXIT ${u}
|
|
253
|
-
${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,
|
|
254
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=
|
|
262
|
+
${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,i=e.since?`--since "${e.since}"`:"",r=`docker logs --tail ${o} ${i} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:h,stderr:p}=await oe(r,{timeout:15e3});return(h||p||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
263
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Fe(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await nt(c,r,{timeout:2e4}),m=[l,u].filter(Boolean).join(`
|
|
255
264
|
`).trim();return d!==0?`EXIT ${d}
|
|
256
265
|
${f||m}`:m||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!o.test(e.command.trim())){let h=n?"local":e.server;if(console.log(`
|
|
257
|
-
${
|
|
258
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=
|
|
266
|
+
${I.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${I.reset}`),!await De(" Execute?"))return"CANCELLED: User declined."}let r=`docker exec ${e.container} sh -c ${JSON.stringify(e.command)}`;if(n)try{let{stdout:h,stderr:p}=await oe(r,{timeout:3e4});return(h||p||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
267
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Fe(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await nt(c,r,{timeout:35e3}),m=[l,u].filter(Boolean).join(`
|
|
259
268
|
`).trim();return d!==0?`EXIT ${d}
|
|
260
269
|
${f||m}`:m||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let p=o?"local":e.server;if(console.log(`
|
|
261
|
-
${
|
|
262
|
-
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=
|
|
270
|
+
${I.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${I.reset}`),!await De(" Execute?"))return"CANCELLED: User declined."}let r=e.action==="remove"?"rm":e.action,c=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${r} ${e.container}`;if(o)try{let{stdout:p,stderr:g}=await oe(c,{timeout:3e4});return(p||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(p){return`EXIT ${p.code||1}
|
|
271
|
+
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=Fe(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await nt(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
|
|
263
272
|
`).trim();return f!==0?`EXIT ${f}
|
|
264
|
-
${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={
|
|
265
|
-
${
|
|
266
|
-
${m||"(nothing to sync)"}`;let h="";if(e.deploy_script){let{stdout:p,stderr:g,exitCode:y,error:$}=await
|
|
273
|
+
${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...Sm(e.config),...e},delete e.config,delete e._name}catch(p){return`ERROR: ${p.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.local_path)return"ERROR: local_path is required";if(!e.remote_path)return"ERROR: remote_path is required";let n;try{n=Fe(e.server)}catch(p){return`ERROR: ${p.message}`}let o=n.user?`${n.user}@${n.host}`:n.host,i=n.port&&Number(n.port)!==22?`-e "ssh -p ${n.port}"`:"",r=n.key?`-e "ssh -i ${n.key.replace(/^~/,require("os").homedir())}"`:"",c=n.key?`-e "ssh -i ${n.key.replace(/^~/,require("os").homedir())}${n.port&&Number(n.port)!==22?` -p ${n.port}`:""}"`:i,l=(e.exclude||[]).map(p=>`--exclude="${p}"`).join(" "),u=e.dry_run?"--dry-run":"",d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,f=`rsync -avz --delete ${u} ${l} ${c} ${d} ${o}:${e.remote_path}`.trim().replace(/\s+/g," ");if(!e.dry_run&&!s.autoConfirm&&(console.log(`
|
|
274
|
+
${I.yellow} \u26A0 Deploy: ${d} \u2192 ${o}:${e.remote_path}${I.reset}`),e.deploy_script&&console.log(`${I.yellow} Then run: ${e.deploy_script}${I.reset}`),!await De(" Proceed with deployment?")))return"CANCELLED: User declined.";let m="";try{let{stdout:p,stderr:g}=await oe(f,{timeout:12e4});m=(p||g||"").trim()}catch(p){return`ERROR (rsync): ${(p.stderr||p.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN:
|
|
275
|
+
${m||"(nothing to sync)"}`;let h="";if(e.deploy_script){let{stdout:p,stderr:g,exitCode:y,error:$}=await nt(n,e.deploy_script,{timeout:6e4}),_=[p,g].filter(Boolean).join(`
|
|
267
276
|
`).trim();if(y!==0)return`rsync OK
|
|
268
277
|
|
|
269
278
|
ERROR (deploy_script, exit ${y}):
|
|
270
|
-
${$||
|
|
279
|
+
${$||_}`;h=`
|
|
271
280
|
|
|
272
281
|
Remote script output:
|
|
273
|
-
${
|
|
274
|
-
${m}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function
|
|
275
|
-
`)}function
|
|
282
|
+
${_||"(no output)"}`}return`Deployed ${d} \u2192 ${o}:${e.remote_path}
|
|
283
|
+
${m}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function Pm(t,e,s={}){let n=s.silent?null:wm(t,e);if(!n)return Ha(t,e,s);let o=new Ga(n);o.start();try{let i=await Ha(t,e,s);return o.stop(),i}catch(i){throw o.stop(),i}}Ja.exports={TOOL_DEFINITIONS:Mm,executeTool:Pm,resolvePath:be,autoFixPath:rs,autoFixEdit:Ka,enrichBashError:za,cancelPendingAskUser:Am,setAskUserHandler:Om}});var Xa=L((O$,Ya)=>{var{loadServerProfiles:So}=Lt(),vo={almalinux9:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all. Open port: firewall-cmd --permanent --add-port=PORT/tcp && firewall-cmd --reload.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent | audit2why. Fix context: restorecon -Rv /path.","Nginx config: /etc/nginx/. Test: nginx -t. Reload: systemctl reload nginx.","Process list: ps aux. Ports: ss -tuln.","Python: python3. Pip: pip3. Virtualenv: python3 -m venv."],almalinux8:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent."],ubuntu:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw. Status: ufw status. Allow port: ufw allow PORT/tcp.","SELinux NOT active by default (AppArmor instead). Check: aa-status."],debian:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw or iptables."],macos:["Package manager: Homebrew (brew). Install: brew install <pkg>. Update: brew update && brew upgrade.","Service manager: launchctl (NOT systemctl). Start: brew services start <name>. List: brew services list.",`No systemd. No journalctl. Use: log show --predicate 'process == "nginx"' --last 1h instead.`,"Firewall: macOS built-in (pfctl or System Settings). Check: pfctl -s rules.","Process list: ps aux. Ports: lsof -i -n -P | grep LISTEN."]};function Lm(){let t=So();if(Object.keys(t).length===0)return null;let s=["## Remote Servers (.nex/servers.json)"];s.push(""),s.push("Available server profiles (use with ssh_exec, ssh_upload, ssh_download, service_manage, service_logs, container_list, container_logs, container_exec, container_manage, deploy):");for(let[o,i]of Object.entries(t)){let r=i.user?`${i.user}@${i.host}`:i.host,c=i.port&&Number(i.port)!==22?`:${i.port}`:"",l=i.os?` \u2014 OS: ${i.os}`:"",u=i.sudo?", sudo available":"";s.push(`- **${o}**: ${r}${c}${l}${u}`)}let n=new Set;for(let o of Object.values(t))o.os&&vo[o.os]&&n.add(o.os);if(n.size>0){s.push("");for(let o of n){let i={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;s.push(`### ${i} Notes`);for(let r of vo[o])s.push(`- ${r}`)}}return s.join(`
|
|
284
|
+
`)}function Im(t){let e=So();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function qm(){return Object.keys(So())}Ya.exports={getServerContext:Lm,hasServerOS:Im,getProfileNames:qm,OS_HINTS:vo}});var To=L((N$,Qa)=>{var Me=require("fs").promises,Te=require("path"),is=require("util").promisify(require("child_process").exec),{C:Ue}=ae(),{getMergeConflicts:Va}=gt(),{getServerContext:jm}=Xa(),Eo=new Map,qt=new Map,as=null,Dm=3e4;async function st(t){try{return await t()}catch{return null}}async function Fm(){if(!as||Date.now()>as)return!1;let t=[Te.join(process.cwd(),"package.json"),Te.join(process.cwd(),"README.md"),Te.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await Me.stat(e),n=qt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(qt.has(e))return!1}try{let e=Te.join(process.cwd(),".git","HEAD"),s=await Me.stat(e),n=qt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function Um(){let t=[Te.join(process.cwd(),"package.json"),Te.join(process.cwd(),"README.md"),Te.join(process.cwd(),".gitignore"),Te.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await Me.stat(e);qt.set(e,s.mtimeMs)}catch{qt.delete(e)}}async function Wm(t){let e="fileContext",s=Eo.get(e),n=!1;if(s&&await Fm()&&(n=!0),!n){let u=[],d=Te.join(t,"package.json");if(await st(()=>Me.access(d).then(()=>!0).catch(()=>!1)))try{let y=await Me.readFile(d,"utf-8"),$=JSON.parse(y),_={name:$.name,version:$.version};$.scripts&&(_.scripts=Object.keys($.scripts).slice(0,15)),$.dependencies&&(_.deps=Object.keys($.dependencies).length),$.devDependencies&&(_.devDeps=Object.keys($.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(_)}`)}catch{}let m=Te.join(t,"README.md");if(await st(()=>Me.access(m).then(()=>!0).catch(()=>!1))){let $=(await Me.readFile(m,"utf-8")).split(`
|
|
276
285
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
277
286
|
${$.join(`
|
|
278
|
-
`)}`)}let p=Te.join(t,".gitignore");if(await
|
|
287
|
+
`)}`)}let p=Te.join(t,".gitignore");if(await st(()=>Me.access(p).then(()=>!0).catch(()=>!1))){let y=await Me.readFile(p,"utf-8");u.push(`GITIGNORE:
|
|
279
288
|
${y.trim()}`)}s=u.join(`
|
|
280
289
|
|
|
281
|
-
`),
|
|
282
|
-
${
|
|
290
|
+
`),Eo.set(e,s),as=Date.now()+Dm,await Um()}let o=[s],[i,r,c,l]=await Promise.all([st(async()=>{let{stdout:u}=await is("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),st(async()=>{let{stdout:u}=await is("git status --short",{cwd:t,timeout:5e3});return u.trim()}),st(async()=>{let{stdout:u}=await is("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),Va()]);if(i&&o.push(`GIT BRANCH: ${i}`),r&&o.push(`GIT STATUS:
|
|
291
|
+
${r}`),c&&o.push(`RECENT COMMITS:
|
|
283
292
|
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
284
293
|
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
285
|
-
${u}`)}try{let u=
|
|
294
|
+
${u}`)}try{let u=jm();u&&o.push(u)}catch{}return o.join(`
|
|
286
295
|
|
|
287
|
-
`)}async function
|
|
288
|
-
${e}`);let s=
|
|
289
|
-
${s}`);let n=
|
|
296
|
+
`)}async function Bm(t){let e=Te.join(t,"package.json"),s="";if(await st(()=>Me.access(e).then(()=>!0).catch(()=>!1)))try{let r=await Me.readFile(e,"utf-8"),c=JSON.parse(r);s=`${c.name||"?"} v${c.version||"?"}`}catch{}let[o,i]=await Promise.all([st(async()=>{let{stdout:r}=await is("git branch --show-current",{cwd:t,timeout:5e3});return r.trim()}),Va()]);if(s&&console.log(`${Ue.dim} project: ${s}${Ue.reset}`),o&&console.log(`${Ue.dim} branch: ${o}${Ue.reset}`),i&&i.length>0){console.log(`${Ue.red} \u26A0 ${i.length} unresolved merge conflict(s):${Ue.reset}`);for(let r of i)console.log(`${Ue.red} ${r.file}${Ue.reset}`);console.log(`${Ue.yellow} \u2192 Resolve conflicts before starting tasks${Ue.reset}`)}console.log()}Qa.exports={gatherProjectContext:Wm,printContext:Bm,_clearContextCache:()=>{Eo.clear(),qt.clear(),as=null}}});var bt=L((M$,nc)=>{var Ye=require("fs"),Co=require("path");function cs(){return Co.join(process.cwd(),".nex","sessions")}function Za(){let t=cs();Ye.existsSync(t)||Ye.mkdirSync(t,{recursive:!0})}function Ro(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Co.join(cs(),`${e}.json`)}function Ao(t,e,s={}){Za();let n=Ro(t),o={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return Ye.writeFileSync(n,JSON.stringify(o,null,2),"utf-8"),{path:n,name:t}}function ec(t){let e=Ro(t);if(!Ye.existsSync(e))return null;try{return JSON.parse(Ye.readFileSync(e,"utf-8"))}catch{return null}}function tc(){Za();let t=cs(),e=Ye.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Ye.readFileSync(Co.join(t,n),"utf-8"));s.push({name:o.name||n.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider})}catch{}return s.sort((n,o)=>(o.updatedAt||"").localeCompare(n.updatedAt||""))}function Hm(t){let e=Ro(t);return Ye.existsSync(e)?(Ye.unlinkSync(e),!0):!1}function Gm(){let t=tc();return t.length===0?null:ec(t[0].name)}var wt=null,Je=null,gn=null;function zm(t,e={}){t.length!==0&&(wt&&clearTimeout(wt),Je=t,gn=e||{},wt=setTimeout(()=>{Je&&Je.length>0&&Ao("_autosave",Je,gn),wt=null,Je=null,gn=null},5e3))}function Km(){wt&&(clearTimeout(wt),wt=null),Je&&Je.length>0&&(Ao("_autosave",Je,gn),Je=null,gn=null)}nc.exports={saveSession:Ao,loadSession:ec,listSessions:tc,deleteSession:Hm,getLastSession:Gm,autoSave:zm,flushAutoSave:Km,_getSessionsDir:cs}});var ot=L((P$,cc)=>{var Xe=require("fs"),ls=require("path"),Jm=require("os");function Oo(){return ls.join(process.cwd(),".nex","memory")}function No(){return ls.join(Oo(),"memory.json")}function Ym(){return ls.join(process.cwd(),"NEX.md")}function sc(){return ls.join(Jm.homedir(),".nex","NEX.md")}function Xm(){let t=Oo();Xe.existsSync(t)||Xe.mkdirSync(t,{recursive:!0})}function us(){let t=No();if(!Xe.existsSync(t))return{};try{return JSON.parse(Xe.readFileSync(t,"utf-8"))}catch{return{}}}function oc(t){Xm(),Xe.writeFileSync(No(),JSON.stringify(t,null,2),"utf-8")}function Vm(t,e){let s=us();s[t]={value:e,updatedAt:new Date().toISOString()},oc(s)}function Qm(t){let e=us();return e[t]?e[t].value:null}function Zm(t){let e=us();return t in e?(delete e[t],oc(e),!0):!1}function rc(){let t=us();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function ic(){let t=sc();if(!Xe.existsSync(t))return"";try{return Xe.readFileSync(t,"utf-8").trim()}catch{return""}}function ac(){let t=Ym();if(!Xe.existsSync(t))return"";try{return Xe.readFileSync(t,"utf-8").trim()}catch{return""}}function ep(){let t=[],e=ic();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
297
|
+
${e}`);let s=ac();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
298
|
+
${s}`);let n=rc();if(n.length>0){let o=n.map(i=>` ${i.key}: ${i.value}`).join(`
|
|
290
299
|
`);t.push(`PROJECT MEMORY:
|
|
291
300
|
${o}`)}return t.join(`
|
|
292
301
|
|
|
293
|
-
`)}
|
|
294
|
-
${
|
|
295
|
-
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],
|
|
296
|
-
`)}function
|
|
302
|
+
`)}cc.exports={remember:Vm,recall:Qm,forget:Zm,listMemories:rc,loadGlobalInstructions:ic,loadProjectInstructions:ac,getMemoryContext:ep,_getMemoryDir:Oo,_getMemoryFile:No,_getGlobalNexMdPath:sc}});var $n=L((I$,dc)=>{var xt=require("fs"),Mo=require("path"),{C:L$}=ae(),ds={bash:"ask",read_file:"allow",write_file:"ask",edit_file:"ask",list_directory:"allow",search_files:"allow",glob:"allow",grep:"allow",patch_file:"ask",web_fetch:"allow",web_search:"allow",ask_user:"allow",task_list:"allow",spawn_agents:"ask"},jt={...ds};function lc(){let t=Mo.join(process.cwd(),".nex","config.json");if(xt.existsSync(t))try{let e=JSON.parse(xt.readFileSync(t,"utf-8"));e.permissions&&(jt={...ds,...e.permissions})}catch{}}function tp(){let t=Mo.join(process.cwd(),".nex"),e=Mo.join(t,"config.json"),s={};if(xt.existsSync(e))try{s=JSON.parse(xt.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=jt,xt.existsSync(t)||xt.mkdirSync(t,{recursive:!0}),xt.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function uc(t){return jt[t]||"ask"}function np(t,e){return["allow","ask","deny"].includes(e)?(jt[t]=e,!0):!1}function sp(t){return uc(t)}function op(){return Object.entries(jt).map(([t,e])=>({tool:t,mode:e}))}function rp(){jt={...ds}}lc();dc.exports={getPermission:uc,setPermission:np,checkPermission:sp,listPermissions:op,loadPermissions:lc,savePermissions:tp,resetPermissions:rp,DEFAULT_PERMISSIONS:ds}});var Dt=L((j$,gc)=>{var _t=require("fs"),fs=require("path"),q$=require("readline"),{C:K}=ae(),ce=null,Po=!1,Lo=null,fc=new Set(["read_file","list_directory","search_files","glob","grep","web_search","web_fetch","git_status","git_diff","git_log","git_show","ask_user"]);function ms(){return fs.join(process.cwd(),".nex","plans")}function mc(){let t=ms();_t.existsSync(t)||_t.mkdirSync(t,{recursive:!0})}function ip(t,e=[]){return ce={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(s=>({description:s.description||s,files:s.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},ce}function ap(){return ce}function cp(t){Po=t}function lp(){return Po}function up(){return!ce||ce.status!=="draft"?!1:(ce.status="approved",ce.updatedAt=new Date().toISOString(),!0)}function dp(){return!ce||ce.status!=="approved"?!1:(ce.status="executing",!0)}function fp(t,e){return!ce||t<0||t>=ce.steps.length?!1:(ce.steps[t].status=e,ce.updatedAt=new Date().toISOString(),ce.steps.every(s=>s.status==="done"||s.status==="skipped")&&(ce.status="completed"),!0)}function mp(t){if(!t)return`${K.dim}No active plan${K.reset}`;let e={draft:`${K.yellow}DRAFT${K.reset}`,approved:`${K.green}APPROVED${K.reset}`,executing:`${K.blue}EXECUTING${K.reset}`,completed:`${K.green}COMPLETED${K.reset}`},s=[];s.push(`
|
|
303
|
+
${K.bold}${K.cyan}Plan: ${t.task}${K.reset}`),s.push(`${K.dim}Status: ${e[t.status]||t.status}${K.reset}
|
|
304
|
+
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],i;switch(o.status){case"done":i=`${K.green}\u2713${K.reset}`;break;case"in_progress":i=`${K.blue}\u2192${K.reset}`;break;case"skipped":i=`${K.dim}\u25CB${K.reset}`;break;default:i=`${K.dim} ${K.reset}`}s.push(` ${i} ${K.bold}Step ${n+1}:${K.reset} ${o.description}`),o.files.length>0&&s.push(` ${K.dim}Files: ${o.files.join(", ")}${K.reset}`)}return s.push(""),s.join(`
|
|
305
|
+
`)}function pp(t){if(t||(t=ce),!t)return null;mc();let e=fs.join(ms(),`${t.name}.json`);return _t.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function hp(t){let e=fs.join(ms(),`${t}.json`);if(!_t.existsSync(e))return null;try{let s=JSON.parse(_t.readFileSync(e,"utf-8"));return ce=s,s}catch{return null}}function gp(){mc();let t=ms(),e=_t.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(_t.readFileSync(fs.join(t,n),"utf-8"));s.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return s.sort((n,o)=>(o.createdAt||"").localeCompare(n.createdAt||""))}function $p(t){Lo=t}function yp(){return Lo}function wp(){ce=null,Po=!1,Lo=null}function bp(){return`
|
|
297
306
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
298
307
|
|
|
299
308
|
# Allowed Tools (read-only)
|
|
300
|
-
You may ONLY use these tools: ${[...
|
|
309
|
+
You may ONLY use these tools: ${[...fc].join(", ")}
|
|
301
310
|
Any other tool call will be blocked and returned with an error.
|
|
302
311
|
|
|
303
312
|
# Analysis Phase
|
|
@@ -328,47 +337,46 @@ Bullet list of potential issues and mitigations.
|
|
|
328
337
|
# Important
|
|
329
338
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
330
339
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
331
|
-
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var
|
|
332
|
-
`),s=[],n=!1,o="";for(let
|
|
333
|
-
`)}function
|
|
334
|
-
`)}function
|
|
340
|
+
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var pc=["interactive","semi-auto","autonomous"],hc="interactive";function xp(t){return pc.includes(t)?(hc=t,!0):!1}function _p(){return hc}gc.exports={createPlan:ip,getActivePlan:ap,setPlanMode:cp,isPlanMode:lp,approvePlan:up,startExecution:dp,updateStep:fp,formatPlan:mp,savePlan:pp,loadPlan:hp,listPlans:gp,clearPlan:wp,getPlanModePrompt:bp,setPlanContent:$p,getPlanContent:yp,PLAN_MODE_ALLOWED_TOOLS:fc,setAutonomyLevel:xp,getAutonomyLevel:_p,AUTONOMY_LEVELS:pc}});var Ec=L((D$,Sc)=>{var{C:w}=ae();function kp(t){if(!t)return"";let e=t.split(`
|
|
341
|
+
`),s=[],n=!1,o="";for(let i of e){if(i.trim().startsWith("```")){if(n)s.push(`${w.dim}${"\u2500".repeat(40)}${w.reset}`),n=!1,o="";else{n=!0,o=i.trim().substring(3).trim();let r=o?` ${o} `:"";s.push(`${w.dim}${"\u2500".repeat(3)}${r}${"\u2500".repeat(Math.max(0,37-r.length))}${w.reset}`)}continue}if(n){s.push(` ${qo(i,o)}`);continue}if(i.startsWith("### ")){s.push(`${w.bold}${w.cyan} ${kt(i.substring(4))}${w.reset}`);continue}if(i.startsWith("## ")){s.push(`${w.bold}${w.cyan} ${kt(i.substring(3))}${w.reset}`);continue}if(i.startsWith("# ")){s.push(`${w.bold}${w.cyan}${kt(i.substring(2))}${w.reset}`);continue}if(/^\s*[-*]\s/.test(i)){let r=i.match(/^(\s*)/)[1],c=i.replace(/^\s*[-*]\s/,"");s.push(`${r}${w.cyan}\u2022${w.reset} ${vt(c)}`);continue}if(/^\s*\d+\.\s/.test(i)){let r=i.match(/^(\s*)(\d+)\.\s(.*)/);if(r){s.push(`${r[1]}${w.cyan}${r[2]}.${w.reset} ${vt(r[3])}`);continue}}s.push(vt(i))}return s.join(`
|
|
342
|
+
`)}function kt(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function vt(t){return t?t.replace(/`([^`]+)`/g,`${w.cyan}$1${w.reset}`).replace(/\*\*([^*]+)\*\*/g,`${w.bold}$1${w.reset}`).replace(/\*([^*]+)\*/g,`${w.dim}$1${w.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${w.cyan}$1${w.reset} ${w.dim}($2)${w.reset}`):""}function qo(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?$c(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?yc(t):e==="json"||e==="jsonc"?wc(t):e==="python"||e==="py"?bc(t):e==="go"||e==="golang"?xc(t):e==="rust"||e==="rs"?_c(t):e==="css"||e==="scss"||e==="less"?kc(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?vc(t):t:""}function $c(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(o,`${w.yellow}$1${w.reset}`),i=i.replace(e,`${w.magenta}$1${w.reset}`),i=i.replace(s,`${w.green}$&${w.reset}`),i=i.replace(n,`${w.dim}$1${w.reset}`),i}function yc(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,i=t;return i=i.replace(s,`${w.cyan}$1${w.reset}`),i=i.replace(e,`$1${w.green}$2${w.reset}`),i=i.replace(n,`${w.yellow}$&${w.reset}`),i=i.replace(o,`${w.dim}$1${w.reset}`),i}function wc(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,i=t;return i=i.replace(e,`${w.cyan}$1${w.reset}:`),i=i.replace(s,`: ${w.green}$1${w.reset}`),i=i.replace(n,`: ${w.yellow}$1${w.reset}`),i=i.replace(o,`: ${w.magenta}$1${w.reset}`),i}function bc(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,n=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,i=/^(\s*@\w+)/,r=t;return r=r.replace(o,`${w.yellow}$1${w.reset}`),r=r.replace(e,`${w.magenta}$1${w.reset}`),r=r.replace(i,`${w.cyan}$1${w.reset}`),r=r.replace(s,`${w.green}$&${w.reset}`),r=r.replace(n,`${w.dim}$1${w.reset}`),r}function xc(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,i=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(i,`${w.yellow}$1${w.reset}`),r=r.replace(s,`${w.cyan}$1${w.reset}`),r=r.replace(e,`${w.magenta}$1${w.reset}`),r=r.replace(n,`${w.green}$&${w.reset}`),r=r.replace(o,`${w.dim}$1${w.reset}`),r}function _c(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,i=/\b(\d+\.?\d*)\b/g,r=/\b(\w+!)/g,c=t;return c=c.replace(i,`${w.yellow}$1${w.reset}`),c=c.replace(s,`${w.cyan}$1${w.reset}`),c=c.replace(e,`${w.magenta}$1${w.reset}`),c=c.replace(r,`${w.yellow}$1${w.reset}`),c=c.replace(n,`${w.green}$&${w.reset}`),c=c.replace(o,`${w.dim}$1${w.reset}`),c}function kc(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,n=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,i=/(\/\*.*?\*\/|\/\/.*$)/,r=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(r,`${w.yellow}$1${w.reset}`),c=c.replace(o,`${w.yellow}$1${w.reset}`),c=c.replace(e,`$1${w.cyan}$2${w.reset}:`),c=c.replace(n,`$1${w.magenta}$&${w.reset}`),c=c.replace(i,`${w.dim}$1${w.reset}`),c}function vc(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,i=/(&\w+;)/g,r=t;return r=r.replace(o,`${w.dim}$1${w.reset}`),r=r.replace(n,`${w.green}$&${w.reset}`),r=r.replace(e,`<${w.magenta}$1${w.reset}`),r=r.replace(s,` ${w.cyan}$1${w.reset}=`),r=r.replace(i,`${w.yellow}$1${w.reset}`),r}function vp(t,e){if(!t||t.length===0)return"";let s=t.map((r,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(r.length,l)}),n=s.map(r=>"\u2500".repeat(r+2)).join("\u253C"),o=t.map((r,c)=>` ${w.bold}${r.padEnd(s[c])}${w.reset} `).join("\u2502"),i=[];i.push(`${w.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${w.reset}`),i.push(`${w.dim}\u2502${w.reset}${o}${w.dim}\u2502${w.reset}`),i.push(`${w.dim}\u251C${n}\u2524${w.reset}`);for(let r of e){let c=t.map((l,u)=>` ${(r[u]||"").padEnd(s[u])} `).join(`${w.dim}\u2502${w.reset}`);i.push(`${w.dim}\u2502${w.reset}${c}${w.dim}\u2502${w.reset}`)}return i.push(`${w.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${w.reset}`),i.join(`
|
|
343
|
+
`)}function Sp(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,i=Math.round(o/100*n),r=n-i,c=o>=100?w.green:o>50?w.yellow:w.cyan;return` ${t} ${c}${"\u2588".repeat(i)}${w.dim}${"\u2591".repeat(r)}${w.reset} ${o}% (${e}/${s})`}var Io=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{process.stdout.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}_cursorWrite(e){try{process.stderr.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),80))}_renderCursor(){let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],s=e[this._cursorFrame%e.length];this._cursorWrite(`\x1B[2K\r\x1B[36m${s}\x1B[0m`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let s;for(;(s=this.buffer.indexOf(`
|
|
335
344
|
`))!==-1;){let n=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(n)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),120))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${w.dim}${"\u2500".repeat(40)}${w.reset}
|
|
336
345
|
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${w.dim}${"\u2500".repeat(40)}${w.reset}
|
|
337
346
|
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${w.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${w.reset}
|
|
338
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
339
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${w.bold}${w.cyan} ${
|
|
340
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${w.bold}${w.cyan} ${
|
|
341
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${w.bold}${w.cyan}${
|
|
342
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${w.cyan}\u2022${w.reset} ${
|
|
343
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${w.cyan}${s[2]}.${w.reset} ${
|
|
344
|
-
`);return}}this._safeWrite(`${
|
|
345
|
-
`)}}
|
|
347
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${qo(e,this.codeBlockLang)}
|
|
348
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${w.bold}${w.cyan} ${kt(e.substring(4))}${w.reset}
|
|
349
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${w.bold}${w.cyan} ${kt(e.substring(3))}${w.reset}
|
|
350
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${w.bold}${w.cyan}${kt(e.substring(2))}${w.reset}
|
|
351
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${w.cyan}\u2022${w.reset} ${vt(n)}
|
|
352
|
+
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${w.cyan}${s[2]}.${w.reset} ${vt(s[3])}
|
|
353
|
+
`);return}}this._safeWrite(`${vt(e)}
|
|
354
|
+
`)}};Sc.exports={renderMarkdown:kp,renderInline:vt,stripHeadingMarkers:kt,highlightCode:qo,highlightJS:$c,highlightBash:yc,highlightJSON:wc,highlightPython:bc,highlightGo:xc,highlightRust:_c,highlightCSS:kc,highlightHTML:vc,renderTable:vp,renderProgress:Sp,StreamRenderer:Io}});var Fo=L((F$,Ac)=>{var{execSync:Ep}=require("child_process"),jo=require("path"),yn=require("fs"),Do=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function Tc(){return jo.join(process.cwd(),".nex","hooks")}function Tp(){return jo.join(process.cwd(),".nex","config.json")}function Cc(){let t=Tp();if(!yn.existsSync(t))return{};try{return JSON.parse(yn.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function ps(t){if(!Do.includes(t))return[];let e=[],s=Tc(),n=jo.join(s,t);yn.existsSync(n)&&e.push(n);let o=Cc();if(o[t]){let i=Array.isArray(o[t])?o[t]:[o[t]];e.push(...i)}return e}function Rc(t,e={},s=3e4){try{return{success:!0,output:Ep(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){return{success:!1,error:n.stderr?n.stderr.trim():n.message}}}function Cp(t,e={}){let s=ps(t);if(s.length===0)return[];let n={};for(let[i,r]of Object.entries(e))n[`NEX_${i.toUpperCase()}`]=String(r);let o=[];for(let i of s){let r=Rc(i,n);if(o.push({command:i,...r}),!r.success&&t.startsWith("pre-"))break}return o}function Rp(t){return ps(t).length>0}function Ap(){let t=[];for(let e of Do){let s=ps(e);s.length>0&&t.push({event:e,commands:s})}return t}function Op(){let t=Tc();return yn.existsSync(t)||yn.mkdirSync(t,{recursive:!0}),t}Ac.exports={HOOK_EVENTS:Do,loadHookConfig:Cc,getHooksForEvent:ps,executeHook:Rc,runHooks:Cp,hasHooks:Rp,listHooks:Ap,initHooksDir:Op}});var de=L((B$,Bc)=>{var{C:x,Spinner:Ft,TaskProgress:Np,formatToolCall:Mp,formatResult:Pp,formatToolSummary:Ic,formatSectionHeader:Lp,setActiveTaskProgress:U$}=ae(),{callStream:Ip}=he(),{parseToolArgs:qp}=qn(),{executeTool:jp}=qe(),{gatherProjectContext:Dp}=To(),{fitToContext:Fp,forceCompress:Uo,getUsage:Up,estimateTokens:Wp}=Oe(),{autoSave:rt}=bt(),{getMemoryContext:Bp}=ot(),{checkPermission:Hp,setPermission:Gp,savePermissions:zp}=$n(),{confirm:qc,setAllowAlwaysHandler:Kp}=Ie(),{isPlanMode:ys,getPlanModePrompt:Jp,PLAN_MODE_ALLOWED_TOOLS:jc,setPlanContent:Yp}=Dt(),{StreamRenderer:Xp}=Ec(),{runHooks:Oc}=Fo(),{routeMCPCall:Vp,getMCPToolDefinitions:Qp}=Wn(),{getSkillInstructions:Zp,getSkillToolDefinitions:eh,routeSkillCall:th}=Zt(),{trackUsage:nh}=At(),{validateToolArgs:sh}=Xs(),{filterToolsForModel:Nc,getModelTier:oh,PROVIDER_DEFAULT_TIER:W$}=co(),{getConfiguredProviders:rh,getActiveProviderName:wn,getActiveModelId:Yo,setActiveModel:Mc,MODEL_EQUIVALENTS:ws}=he(),Qo=require("fs"),Zo=require("path"),Pc=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function ih(t){let e=[],s;for(Pc.lastIndex=0;(s=Pc.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):Zo.resolve(n);Qo.existsSync(o)&&e.push({raw:n,abs:o})}return e}function ah(t){let e=Qo.readFileSync(t),s=Zo.extname(t).toLowerCase().replace(".",""),n=s==="jpg"||s==="jpeg"?"image/jpeg":s==="png"?"image/png":s==="gif"?"image/gif":s==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:n}}function Dc(t){let e=ih(t);if(e.length===0)return t;let s=[{type:"text",text:t}];for(let n of e)try{let{data:o,media_type:i}=ah(n.abs);s.push({type:"image",media_type:i,data:o})}catch{}return s.length>1?s:t}var Wo=null,Bo=null,Ho=null;function Ut(){if(Wo===null){let{TOOL_DEFINITIONS:t}=qe();Wo=t}return Bo===null&&(Bo=eh()),Ho===null&&(Ho=Qp()),[...Wo,...Bo,...Ho]}var Xo=50;function ch(t){Number.isFinite(t)&&t>0&&(Xo=t)}var hs=()=>null;function lh(t){hs=t}var bn=null,Vo=null,Wt=null,gs=new Map,uh=1e4,dh=6e3,fh=/\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 mh(t){return!t||typeof t!="string"?t:t.replace(fh,(e,s)=>`${s}=***REDACTED***`)}function ph(t){let e=mh(t);if(Wp(e)>uh)try{let{compressToolResult:n}=Oe();return n(e,dh)}catch{return e}return e}function Fc(t){try{let{getActiveModel:e}=he(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(gs.has(n))return gs.get(n);let o=Nc(t);return gs.set(n,o),o}catch{return Nc(t)}}function hh(){gs.clear()}async function Uc(){try{let t=require("fs").promises,e=require("path"),s=[e.join(process.cwd(),"package.json"),e.join(process.cwd(),".git","HEAD"),e.join(process.cwd(),"README.md"),e.join(process.cwd(),"NEX.md")],o=(await Promise.allSettled(s.map(i=>t.stat(i).then(r=>`${i}:${r.mtimeMs}`)))).filter(i=>i.status==="fulfilled").map(i=>i.value);try{let{getMemoryContextHash:i}=ot(),r=i();r&&o.push(`memory:${r}`)}catch{}try{let i=e.join(process.cwd(),".nex","brain");if(Qo.existsSync(i)){let r=await t.stat(i);o.push(`brain:${r.mtimeMs}`)}}catch{}return o.join("|")}catch{return`fallback:${Date.now()}`}}function gh(){bn=null,Vo=null,Wt=null}var $h=new Set(["spawn_agents"]),Go=5,zo=3,Ko=2,yh=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),wh=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10),bh=process.env.NEX_STALE_AUTO_SWITCH!=="0";function xh(t){try{let e=require("fs"),s=require("path"),n=s.join(process.cwd(),".nex","plans");e.existsSync(n)||e.mkdirSync(n,{recursive:!0});let o=s.join(n,"current-plan.md");e.writeFileSync(o,t,"utf-8")}catch{}}Kp(t=>{Gp(t,"allow"),zp(),console.log(`${x.green} \u2713 ${t}: always allow${x.reset}`)});async function _h(t){let e=t.function.name,s=qp(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let l=Ut().find(d=>d.function.name===e),u=l?JSON.stringify(l.function.parameters,null,2):"unknown";return console.log(`${x.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${x.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
346
355
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
347
356
|
|
|
348
357
|
Expected JSON schema for "${e}":
|
|
349
358
|
${u}
|
|
350
359
|
|
|
351
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=
|
|
352
|
-
`)[0]}${
|
|
353
|
-
...(truncated ${n.length-5e4} chars)`:n,
|
|
354
|
-
`)[0],i
|
|
355
|
-
`)}function
|
|
356
|
-
`];n?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),o.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),o.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),o.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),o.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),o.push(" \u2022 For Makefiles, always display the actual .PHONY declarations and dependency chains"),o.push(" \u2022 For dataclasses, always show the complete class definition with field types and defaults");let
|
|
360
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=sh(e,s);if(!o.valid)return console.log(`${x.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
361
|
+
`)[0]}${x.reset}`),{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:o.error,tool_call_id:n}};let i=o.corrected||s;if(o.corrected){let c=Object.keys(s),l=Object.keys(o.corrected),u=c.filter(d=>!l.includes(d));u.length&&console.log(`${x.dim} \u2713 ${e}: corrected args (${u.join(", ")})${x.reset}`)}if(ys()&&!jc.has(e))return console.log(`${x.yellow} \u2717 ${e}: blocked in plan mode${x.reset}`),{callId:n,fnName:e,args:i,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:n}};let r=Hp(e);if(r==="deny")return console.log(`${x.red} \u2717 ${e}: denied by permissions${x.reset}`),{callId:n,fnName:e,args:i,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(r==="ask"){let c=` Allow ${e}?`;return e==="bash"&&i.command&&(c=` bash: \`${i.command.substring(0,80)}${i.command.length>80?"\u2026":""}\`?`),await qc(c,{toolName:e})?{callId:n,fnName:e,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:n,fnName:e,args:i,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:n}}}return{callId:n,fnName:e,args:i,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function kh(t,e,s={}){let n=await th(t,e);if(n!==null)return n;let o=await Vp(t,e);return o!==null?o:jp(t,e,s)}function vh(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 Jo(t,e=!1){e||console.log(Mp(t.fnName,t.args)),Oc("pre-tool",{tool_name:t.fnName});let s=await kh(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(s??""),o=n.length>5e4?n.substring(0,5e4)+`
|
|
362
|
+
...(truncated ${n.length-5e4} chars)`:n,i=o.split(`
|
|
363
|
+
`)[0],r=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),c=Ic(t.fnName,t.args,o,r);return e||(console.log(Pp(o)),console.log(c)),Oc("post-tool",{tool_name:t.fnName}),{msg:{role:"tool",content:ph(o),tool_call_id:t.callId},summary:c}}async function Sh(t,e=!1,s={}){let n=new Array(t.length),o=[],i=[],r=null;if(e&&!s.skipSpinner){let l=t.filter(u=>u.canExecute);if(l.length>0){let u;if(l.length===1){let d=l[0],f=vh(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}`}r=new Ft(u),r.start()}}async function c(){if(i.length!==0){if(i.length===1){let l=i[0],{msg:u,summary:d}=await Jo(t[l],e);n[l]=u,o.push(d)}else{let l=i.map(d=>Jo(t[d],e)),u=await Promise.all(l);for(let d=0;d<i.length;d++)n[i[d]]=u[d].msg,o.push(u[d].summary)}i=[]}}for(let l=0;l<t.length;l++){let u=t[l];if(!u.canExecute){await c(),n[l]=u.errorResult,o.push(Ic(u.fnName,u.args||{},u.errorResult.content,!0));continue}if($h.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&r&&(r.stop(),r=null);let{msg:d,summary:f}=await Jo(u,e);n[l]=d,o.push(f)}else i.push(l)}if(await c(),r&&r.stop(),e&&o.length>0&&!s.skipSummaries)for(let l of o)console.log(l);return{results:n,summaries:o}}var X=[],Lc=300,$s=[];function Eh(t){$s.push(t.trim())}function Th(){return $s.length===0?null:$s.splice(0,$s.length).join(`
|
|
364
|
+
`)}function Ch(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,n=!t||t==="auto"?null:t,o=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
365
|
+
`];n?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),o.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),o.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),o.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),o.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),o.push(" \u2022 For Makefiles, always display the actual .PHONY declarations and dependency chains"),o.push(" \u2022 For dataclasses, always show the complete class definition with field types and defaults");let i=e||(n?"English":null);i&&o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${i}.`);let r=s||(n?"English":null);return r&&o.push(`COMMIT MESSAGES: Write all git commit messages in ${r}.`),n&&o.push(`
|
|
357
366
|
This is a hard requirement. Do NOT fall back to English or any other language for your responses, even if the user writes in a different language first.`),o.join(`
|
|
358
367
|
`)+`
|
|
359
368
|
|
|
360
|
-
`}function
|
|
369
|
+
`}function Rh(){if(Wt!==null)return Wt;try{let e=rh().flatMap(o=>o.models.map(i=>({spec:`${o.name}:${i.id}`,tier:oh(i.id,o.name),name:i.name})));if(e.length<2)return Wt="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
|
|
361
370
|
# Sub-Agent Model Routing
|
|
362
371
|
|
|
363
372
|
`;n+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',n+=`| Model | Tier | Auto-assigned for |
|
|
364
373
|
|---|---|---|
|
|
365
374
|
`;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
|
|
366
|
-
`;return
|
|
375
|
+
`;return Wt=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Wt="",""}}async function Wc(){let t=await Uc();if(bn!==null&&t===Vo)return bn;let e=await Dp(process.cwd()),s=Bp(),n=Zp(),o=ys()?Jp():"",i=Ch();return bn=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
|
|
367
376
|
|
|
368
377
|
WORKING DIRECTORY: ${process.cwd()}
|
|
369
378
|
All relative paths resolve from this directory.
|
|
370
|
-
|
|
371
|
-
${r}`:""}PROJECT CONTEXT:
|
|
379
|
+
PROJECT CONTEXT:
|
|
372
380
|
${e}
|
|
373
381
|
${s?`
|
|
374
382
|
${s}
|
|
@@ -377,7 +385,8 @@ ${n}
|
|
|
377
385
|
`:""}${o?`
|
|
378
386
|
${o}
|
|
379
387
|
`:""}
|
|
380
|
-
|
|
388
|
+
${i?`${i}
|
|
389
|
+
`:""}# Core Behavior
|
|
381
390
|
|
|
382
391
|
- You can use tools OR respond with text. For simple questions, answer directly.
|
|
383
392
|
- For coding tasks, use tools to read files, make changes, run tests, etc.
|
|
@@ -406,7 +415,7 @@ Response patterns by request type:
|
|
|
406
415
|
- **Questions / analysis / "status" / "explain" / "what is"**: Gather data with tools, then respond with a clear, structured summary. NEVER just run tools and stop.
|
|
407
416
|
- **Coding tasks (implement, fix, refactor)**: Brief confirmation of what you'll do, then use tools. After changes, summarize what you did and any important details.
|
|
408
417
|
- **Simple questions ("what does X do?")**: Answer directly without tools when you have enough context.
|
|
409
|
-
- **Ambiguous requests**: When a request is vague AND lacks sufficient detail to act (e.g. just "optimize this" or "improve performance" with no further context), ask clarifying questions using ask_user. However, if the user's message already contains specific details \u2014 file names, concrete steps, exercises, numbers, examples \u2014 proceed directly without asking. Only block when you genuinely cannot determine what to do without more information.
|
|
418
|
+
- **Ambiguous requests**: When a request is vague AND lacks sufficient detail to act (e.g. just "optimize this" or "improve performance" with no further context), ask clarifying questions using ask_user. However, if the user's message already contains specific details \u2014 file names, concrete steps, exercises, numbers, examples \u2014 proceed directly without asking. Only block when you genuinely cannot determine what to do without more information. When the user's request is ambiguous or could be interpreted in multiple ways, call the ask_user tool BEFORE starting work. Provide 2-3 specific, actionable options that cover the most likely intents. Do NOT ask open-ended questions in chat \u2014 always use ask_user with concrete options.
|
|
410
419
|
- **Server/SSH commands**: After running remote commands, ALWAYS present the results: service status, log errors, findings.
|
|
411
420
|
- **Regex explanations**: Always show the actual regex pattern and test it with examples. For named groups, use the correct syntax format (question mark open angle bracket name close angle bracket pattern), not incorrect variants. Note PCRE-only features like (?&name) backreferences.
|
|
412
421
|
- **Encoding/buffer handling**: When discussing file operations, mention utf8 encoding or buffer considerations. Use correct flags like --zero instead of -0 for null-delimited output.
|
|
@@ -484,7 +493,7 @@ When performing audits, code reviews, bug hunts, or security reviews:
|
|
|
484
493
|
- Good for: reading multiple files, analyzing separate modules.
|
|
485
494
|
- Bad for: tasks that depend on each other or modify the same file.
|
|
486
495
|
- Max 5 parallel agents.
|
|
487
|
-
${
|
|
496
|
+
${Rh()}
|
|
488
497
|
|
|
489
498
|
# Edit Reliability (Critical)
|
|
490
499
|
|
|
@@ -535,20 +544,21 @@ You have access to a persistent knowledge base in .nex/brain/.
|
|
|
535
544
|
- Include tags in frontmatter for better retrieval
|
|
536
545
|
- The user reviews all brain writes via /brain review or git diff
|
|
537
546
|
|
|
538
|
-
`,
|
|
539
|
-
`):[]).filter(f=>{let m=f.split(".").pop();return
|
|
540
|
-
\u{1F4E6} ${h}${p}`}}catch{}return u}function
|
|
541
|
-
${
|
|
542
|
-
`),m==="")return c({action:"quit"});let p=
|
|
543
|
-
`+
|
|
544
|
-
`)}catch(
|
|
545
|
-
${
|
|
546
|
-
|
|
547
|
-
`),await
|
|
548
|
-
`)
|
|
549
|
-
`);process.
|
|
547
|
+
`,Vo=t,bn}function Ah(){X=[]}function Oh(){X.length>Lc&&X.splice(0,X.length-Lc)}function Nh(){return X.length}function Mh(){return X}function Ph(t){X=t}async function Lh(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),n=(f,m)=>new Promise(h=>{t(f,m,{cwd:s,timeout:3e3},(p,g)=>{h(p?"":(g||"").trim())})}),[o]=await Promise.all([n("find",[".","-type","f","-not","-path","*/node_modules/*","-not","-path","*/.git/*","-not","-path","*/dist/*","-not","-path","*/.next/*","-not","-path","*/build/*","-not","-path","*/__pycache__/*","-not","-path","*/vendor/*"])]),i=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),r=(o?o.split(`
|
|
548
|
+
`):[]).filter(f=>{let m=f.split(".").pop();return i.has(m)});if(r.length<3)return null;let c={};for(let f of r){let m=f.split(".").pop();c[m]=(c[m]||0)+1}let u=` \u{1F4C1} ${Object.entries(c).sort((f,m)=>m[1]-f[1]).slice(0,4).map(([f,m])=>`${m} .${f}`).join(" \xB7 ")}`,d=Zo.join(s,"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+=`
|
|
549
|
+
\u{1F4E6} ${h}${p}`}}catch{}return u}function it(t,e,s,n,o){if(t<1)return;let i=[...e.values()].reduce((c,l)=>c+l,0),r=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${i} ${i===1?"tool":"tools"}`;if(s.size>0&&(r+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),o){let c=Date.now()-o,l=Math.round(c/1e3);r+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}r+=" \u2500\u2500",console.log(`
|
|
550
|
+
${x.dim} ${r}${x.reset}`),s.size>0?console.log(`${x.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${x.reset}`):n.size>=5&&s.size===0&&t>=3?console.log(`${x.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${x.reset}`):n.size>0&&t>=2&&console.log(`${x.dim} \u{1F4A1} /save \xB7 /clear${x.reset}`)}async function Ih(){if(!process.stdout.isTTY)return{action:"quit"};let t=wn(),e=Yo(),s=ws.fast?.[t],n=ws.strong?.[t],o=s&&s!==e,i=n&&n!==e&&n!==s,r=[];r.push({key:"r",label:`Retry with current model ${x.dim}(${e})${x.reset}`}),o&&r.push({key:"f",label:`Switch to ${x.bold}${s}${x.reset} ${x.dim}\u2014 fast, low latency${x.reset}`,model:s}),i&&r.push({key:"s",label:`Switch to ${x.bold}${n}${x.reset} ${x.dim}\u2014 reliable tool-calling, medium speed${x.reset}`,model:n}),r.push({key:"q",label:`${x.dim}Quit${x.reset}`}),console.log(),console.log(`${x.yellow} Stream stale \u2014 all retries exhausted.${x.reset} What would you like to do?`);for(let c of r)console.log(` ${x.cyan}[${c.key}]${x.reset} ${c.label}`);return process.stdout.write(` ${x.yellow}> ${x.reset}`),new Promise(c=>{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}
|
|
551
|
+
`),m==="")return c({action:"quit"});let p=r.find(g=>g.key===h);!p||p.key==="q"||!p.model&&p.key!=="r"?c({action:"quit"}):p.key==="r"?c({action:"retry"}):c({action:"switch",model:p.model,provider:t})};l.on("data",f)})}async function qh(t){let e=Dc(t);X.push({role:"user",content:e}),Oh();let{setOnChange:s}=Qn(),n=null,o=0;s((N,j)=>{N==="create"?(n&&n.stop(),n=new Np(j.name,j.tasks),n.setStats({tokens:o}),n.start()):N==="update"&&n?n.updateTask(j.id,j.status):N==="clear"&&n&&(n.stop(),n=null)});let i=await Wc(),r=i;try{let{getBrainContext:N}=fn(),j=await N(t);j&&(r=i+`
|
|
552
|
+
`+j+`
|
|
553
|
+
`)}catch(N){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",N.message)}let c=[{role:"system",content:r},...X],l=new Ft("Thinking...");l.start();let d=X.length===1?Lh().catch(()=>null):Promise.resolve(null),f=Ut(),[{messages:m,compressed:h,compacted:p,tokensRemoved:g},y]=await Promise.all([Fp(c,f),d]),$=Up(c,f);if(l.stop(),y&&console.log(`${x.dim}${y}${x.reset}`),p)console.log(`${x.dim} [context compacted \u2014 summary (~${g} tokens freed)]${x.reset}`);else if(h){let N=$.limit>0?Math.round(g/$.limit*100):0;console.log(`${x.dim} [context compressed \u2014 ~${g} tokens freed (${N}%)]${x.reset}`)}$.percentage>85&&console.log(`${x.yellow} \u26A0 Context ${Math.round($.percentage)}% full \u2014 consider /clear or /save + start fresh${x.reset}`);let _=m,T=0,k=0,v=0,C=0,S=0,A=new Map,B=new Set,q=new Set,Q=Date.now(),ne=new Map,Z=5,me=10,ke,le=Xo,Qe=0,P=10;e:for(;;){for(ke=0;ke<le&&!hs()?.aborted;ke++){let j=!0,U=null;if(n&&n.isActive())n._paused&&n.resume();else if(!n){let E=S>0?`Thinking... (step ${S+1})`:"Thinking...";U=new Ft(E),U.start()}let W=!0,H="",F=new Xp,G,ye=Date.now(),Pe=!1,Be=new AbortController,Re=setInterval(()=>{let E=Date.now()-ye;if(E>=wh)F._clearCursorLine(),console.log(`${x.yellow} \u26A0 Stream stale for ${Math.round(E/1e3)}s \u2014 aborting and retrying${x.reset}`),Be.abort();else if(E>=yh&&!Pe){Pe=!0,F._clearCursorLine();let D=ws.fast?.[wn()];console.log(`${x.yellow} \u26A0 No tokens received for ${Math.round(E/1e3)}s \u2014 waiting...${x.reset}`),D&&console.log(`${x.dim} \u{1F4A1} Ctrl+C \u2192 /model ${D} to switch to a faster model${x.reset}`)}},5e3),ue="",Ae=null;try{let E=Fc(Ut()),D=ys()?E.filter(J=>jc.has(J.function.name)):E,St=hs(),z=new AbortController;St&&St.addEventListener("abort",()=>z.abort(),{once:!0}),Be.signal.addEventListener("abort",()=>z.abort(),{once:!0}),G=await Ip(_,D,{signal:z.signal,onToken:J=>{ye=Date.now(),Pe=!1,ue+=J,process.stdout.isTTY?Ae||(Ae=setTimeout(()=>{ue&&F&&F.push(ue),ue="",Ae=null},50)):(F.push(ue),ue=""),W&&(n&&!n._paused?n.pause():U&&U.stop(),j||(j=!0),F.startCursor(),W=!1),H+=J}})}catch(E){if(clearInterval(Re),Ae&&(clearTimeout(Ae),Ae=null),ue&&F&&(F.push(ue),ue=""),n&&!n._paused&&n.pause(),U&&U.stop(),F.stopCursor(),Be.signal.aborted&&!hs()?.aborted){if(v++,v>Ko){if(C<1){C++,console.log(`${x.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${x.reset}`);let Ze=Ut(),{messages:Kt,tokensRemoved:Et}=Uo(_,Ze);_=Kt,console.log(`${x.dim} [force-compressed \u2014 ~${Et} tokens freed]${x.reset}`),v=0,ke--;continue}n&&(n.stop(),n=null);let ie=await Ih();if(ie.action==="quit"){s(null),it(S,A,B,q,Q),rt(X);break}ie.action==="switch"&&(Mc(`${ie.provider}:${ie.model}`),console.log(`${x.green} \u2713 Switched to ${ie.provider}:${ie.model}${x.reset}`)),v=0,C=0,ke--;continue}let z=v===1?3e3:5e3;if(v>=2&&C<1){C++,console.log(`${x.yellow} \u26A0 Stale retry ${v}/${Ko} \u2014 force-compressing before retry...${x.reset}`);let ie=Ut(),{messages:Ze,tokensRemoved:Kt}=Uo(_,ie);if(_=Ze,console.log(`${x.dim} [force-compressed \u2014 ~${Kt} tokens freed]${x.reset}`),bh){let Et=ws.fast?.[wn()];Et&&Et!==Yo()&&(Mc(`${wn()}:${Et}`),console.log(`${x.cyan} \u26A1 Auto-switched to ${Et} to avoid further stale timeouts${x.reset}`),console.log(`${x.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${x.reset}`))}}else console.log(`${x.yellow} \u26A0 Stale retry ${v}/${Ko} \u2014 retrying in ${z/1e3}s...${x.reset}`);let J=new Ft(`Waiting ${z/1e3}s before retry...`);J.start(),await new Promise(ie=>setTimeout(ie,z)),J.stop(),ke--;continue}if(E.name==="AbortError"||E.name==="CanceledError"||E.message?.includes("canceled")||E.message?.includes("aborted")){n&&(n.stop(),n=null),s(null),it(S,A,B,q,Q),rt(X);break}let D=E.message;if(E.code==="ECONNREFUSED"||E.message.includes("ECONNREFUSED"))D="Connection refused \u2014 please check your internet connection or API endpoint";else if(E.code==="ENOTFOUND"||E.message.includes("ENOTFOUND"))D="Network error \u2014 could not reach the API server. Please check your connection";else if(E.code==="ETIMEDOUT"||E.message.includes("timeout"))D="Request timed out \u2014 the API server took too long to respond. Please try again";else if(E.message.includes("401")||E.message.includes("Unauthorized"))D="Authentication failed \u2014 please check your API key in the .env file";else if(E.message.includes("403")||E.message.includes("Forbidden"))D="Access denied \u2014 your API key may not have permission for this model";else if(E.message.includes("400")){let z=(E.message||"").toLowerCase(),J=z.includes("context")||z.includes("token")||z.includes("length")||z.includes("too long")||z.includes("too many")||z.includes("prompt")||z.includes("size")||z.includes("exceeds")||z.includes("num_ctx")||z.includes("input");if(J&&C<1){C++,console.log(`${x.yellow} \u26A0 Context too long \u2014 force-compressing and retrying...${x.reset}`);let ie=Ut(),{messages:Ze,tokensRemoved:Kt}=Uo(_,ie);_=Ze,console.log(`${x.dim} [force-compressed \u2014 ~${Kt} tokens freed]${x.reset}`),ke--;continue}J?D="Context too long \u2014 force compression exhausted. Use /clear to start fresh":D="Bad request \u2014 the conversation may be too long or contain unsupported content. Try /clear and retry"}else E.message.includes("500")||E.message.includes("502")||E.message.includes("503")||E.message.includes("504")?D="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(E.message.includes("fetch failed")||E.message.includes("fetch"))&&(D="Network request failed \u2014 please check your internet connection");if(console.log(`${x.red} \u2717 ${D}${x.reset}`),E.message.includes("429")){if(T++,T>Go){console.log(`${x.red} Rate limit: max retries (${Go}) exceeded. Try again later or use /budget to check your limits.${x.reset}`),n&&(n.stop(),n=null),s(null),it(S,A,B,q,Q),rt(X);break}let z=Math.min(1e4*Math.pow(2,T-1),12e4),J=new Ft(`Rate limit \u2014 waiting ${Math.round(z/1e3)}s (retry ${T}/${Go})`);J.start(),await new Promise(ie=>setTimeout(ie,z)),J.stop();continue}if(E.message.includes("socket disconnected")||E.message.includes("TLS")||E.message.includes("ECONNRESET")||E.message.includes("ECONNABORTED")||E.message.includes("ETIMEDOUT")||E.code==="ECONNRESET"||E.code==="ECONNABORTED"){if(k++,k>zo){console.log(`${x.red} Network error: max retries (${zo}) exceeded. Check your connection and try again.${x.reset}`),n&&(n.stop(),n=null),s(null),it(S,A,B,q,Q),rt(X);break}let z=Math.min(2e3*Math.pow(2,k-1),3e4),J=new Ft(`Network error \u2014 retrying in ${Math.round(z/1e3)}s (${k}/${zo})`);J.start(),await new Promise(ie=>setTimeout(ie,z)),J.stop(),ke--;continue}n&&(n.stop(),n=null),s(null),it(S,A,B,q,Q),rt(X);break}clearInterval(Re),T=0,k=0,W&&(n&&!n._paused&&n.pause(),U&&U.stop()),Ae&&(clearTimeout(Ae),Ae=null),ue&&F&&(F.push(ue),ue=""),H&&F.flush(),k=0,v=0,G&&G.usage&&(nh(wn(),Yo(),G.usage.prompt_tokens||0,G.usage.completion_tokens||0),o+=(G.usage.prompt_tokens||0)+(G.usage.completion_tokens||0),n&&n.setStats({tokens:o}));let{content:vs,tool_calls:ut}=G,Ss={role:"assistant",content:vs||""};if(ut&&ut.length>0&&(Ss.tool_calls=ut),X.push(Ss),_.push(Ss),!ut||ut.length===0){let E=(vs||"").trim().length>0||H.trim().length>0;if(!E&&S>0&&ke<Xo-1){let D={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."};_.push(D),X.push(D);continue}if(ys()&&E){let D=(vs||H||"").trim();Yp(D),xh(D),console.log(`
|
|
554
|
+
${x.cyan}${x.bold}Plan ready.${x.reset} ${x.dim}Type ${x.reset}${x.cyan}/plan approve${x.reset}${x.dim} to execute, or ask follow-up questions to refine.${x.reset}`)}n&&(n.stop(),n=null),s(null),it(S,A,B,q,Q),rt(X);return}S++,S>1&&(j=!1);for(let E of ut){let D=E.function.name;A.set(D,(A.get(D)||0)+1)}let dt=await Promise.all(ut.map(E=>_h(E))),zt=n?{skipSpinner:!0,skipSummaries:!0}:{},Pl=dt.some(E=>E.fnName==="ask_user"),wr=!zt.skipSummaries&&!j,vn=null;if(wr&&!Pl){if(j=!0,zt.skipSpinner=!0,process.stdout.write(Lp(dt,S,!1)+`
|
|
555
|
+
`),process.stdout.isTTY){let E=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],D=0;process.stdout.write(" \x1B[2m\u280B\x1B[0m"),vn=setInterval(()=>{process.stdout.write(`\r \x1B[2m${E[D++%E.length]}\x1B[0m`)},80)}}else wr&&(j=!0,zt.skipSpinner=!0);n&&n._paused&&n.resume();let{results:br,summaries:xr}=await Sh(dt,!0,{...zt,skipSummaries:!0});if(vn&&(clearInterval(vn),vn=null,process.stdout.write("\r\x1B[2K")),!zt.skipSummaries)for(let E=0;E<xr.length;E++)dt[E]&&dt[E].fnName==="ask_user"||console.log(xr[E]);for(let E=0;E<dt.length;E++){let D=dt[E];if(!D.canExecute)continue;let St=br[E].content,z=!St.startsWith("ERROR")&&!St.includes("CANCELLED");if(z&&["write_file","edit_file","patch_file"].includes(D.fnName)&&D.args&&D.args.path){B.add(D.args.path);let J=(ne.get(D.args.path)||0)+1;ne.set(D.args.path,J);let ie=D.args.path.split("/").slice(-2).join("/");if(J===Z){console.log(`${x.yellow} \u26A0 Loop warning: "${ie}" edited ${J}\xD7 \u2014 possible edit loop${x.reset}`);let Ze={role:"user",content:`[SYSTEM WARNING] You have edited "${D.args.path}" ${J} times in this session. This may indicate an edit loop. STOP editing this file repeatedly. Re-read it once to verify the current state, then make ONE final targeted edit or declare the task complete.`};X.push(Ze),_.push(Ze)}else if(J>=me){console.log(`${x.red} \u2716 Loop abort: "${ie}" edited ${J}\xD7 \u2014 aborting to prevent runaway loop${x.reset}`),n&&(n.stop(),n=null),s(null),it(S,A,B,q,Q),rt(X);return}}z&&D.fnName==="read_file"&&D.args&&D.args.path&&q.add(D.args.path)}for(let E of br)X.push(E),_.push(E);let _r=Th();if(_r){let E={role:"user",content:`[User note mid-run]: ${_r}`};X.push(E),_.push(E),console.log(`${x.cyan} \u270E Kontext hinzugef\xFCgt${x.reset}`)}}if(ke>=le){n&&(n.stop(),n=null),s(null),it(S,A,B,q,Q),rt(X);let{getActiveProviderName:N}=he();if(N()==="ollama"&&Qe<P){Qe++,le=20,console.log(`${x.dim} \u2500\u2500 auto-extending (+20 turns, ext ${Qe}/${P}) \u2500\u2500${x.reset}`);continue e}if(console.log(`
|
|
556
|
+
${x.yellow}\u26A0 Max iterations reached.${x.reset}`),await qc(" Continue for 20 more turns?")){le=20;continue e}console.log(`${x.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${x.reset}`)}break e}}Bc.exports={processInput:qh,clearConversation:Ah,getConversationLength:Nh,getConversationMessages:Mh,setConversationMessages:Ph,setAbortSignalGetter:lh,setMaxIterations:ch,invalidateSystemPromptCache:gh,clearToolFilterCache:hh,getCachedFilteredTools:Fc,buildSystemPrompt:Wc,getProjectContextHash:Uc,buildUserContent:Dc,injectMidRunNote:Eh}});var he=L((H$,Jc)=>{var{OllamaProvider:jh}=Fr(),{OpenAIProvider:Dh}=si(),{AnthropicProvider:Fh}=ai(),{GeminiProvider:Uh}=di(),{LocalProvider:Wh}=pi(),{checkBudget:Bh}=At(),er={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"}},Hc={};for(let[t,e]of Object.entries(er))for(let s of Object.values(e))Hc[s]=t;function Gc(t,e){let s=Hc[t];return s&&er[s][e]||t}var pe={},_e=null,fe=null,xn=[];function Ce(){if(Object.keys(pe).length>0)return;Bt("ollama",new jh),Bt("openai",new Dh),Bt("anthropic",new Fh),Bt("gemini",new Uh),Bt("local",new Wh);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;pe[t]?(_e=t,fe=e||pe[t].defaultModel):(_e="ollama",fe="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(xn=s.split(",").map(n=>n.trim()).filter(Boolean))}function Bt(t,e){pe[t]=e}function Hh(t){return Ce(),pe[t]||null}function tr(){return Ce(),pe[_e]||null}function Gh(){return Ce(),_e}function zh(){return Ce(),fe}function Kh(){Ce();let t=tr();if(!t)return{id:fe,name:fe,provider:_e};let e=t.getModel(fe);return e?{...e,provider:_e}:{id:fe,name:fe,provider:_e}}function zc(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(pe[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function Jh(t){Ce();let{provider:e,model:s}=zc(t);if(e){let o=pe[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(_e=e,fe=s,bs(),!0):!1}let n=tr();if(n&&n.getModel(s))return fe=s,bs(),!0;for(let[o,i]of Object.entries(pe))if(i.getModel(s))return _e=o,fe=s,bs(),!0;return!1}function bs(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=de();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Oe();t()}catch{}}function Yh(){Ce();let t=new Set;for(let e of Object.values(pe))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function Xh(){return Ce(),Object.entries(pe).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===_e&&s.id===fe}))}))}function Vh(){Ce();let t=[];for(let[e,s]of Object.entries(pe)){let n=s.isConfigured();for(let o of Object.values(s.getModels()))t.push({spec:`${e}:${o.id}`,name:o.name,provider:e,configured:n})}return t}function Qh(t){xn=Array.isArray(t)?t:[]}function Zh(){return[...xn]}function eg(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ECONNRESET"||s==="EHOSTUNREACH"||s==="ENETUNREACH"||s==="EPIPE"||s==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function Kc(t){let e=[_e,...xn.filter(i=>i!==_e)],s,n=0,o=0;for(let i=0;i<e.length;i++){let r=e[i],c=pe[r];if(!c||!c.isConfigured())continue;o++;let l=Bh(r);if(!l.allowed){n++,s=new Error(`Budget limit reached for ${r}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=i>0,d=u?Gc(fe,r):fe;return u&&d!==fe&&process.stderr.write(` [fallback: ${r}:${d}]
|
|
557
|
+
`),await t(c,r,d)}catch(u){if(s=u,eg(u)&&i<e.length-1)continue;throw u}}throw n>0&&n===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function tg(t,e,s={}){return Ce(),Kc((n,o,i)=>n.stream(t,e,{model:i,signal:s.signal,...s}))}async function ng(t,e,s={}){if(Ce(),s.provider){let n=pe[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||fe,...s};try{return await n.chat(t,e,o)}catch(i){if(typeof n.stream=="function")try{return await n.stream(t,e,{...o,onToken:()=>{}})}catch{}throw i}}return Kc(async(n,o,i)=>{try{return await n.chat(t,e,{model:i,...s})}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:i,...s,onToken:()=>{}})}catch{}throw r}})}function sg(){Ce();let t=[];for(let[e,s]of Object.entries(pe))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function og(){for(let t of Object.keys(pe))delete pe[t];_e=null,fe=null,xn=[]}Jc.exports={registerProvider:Bt,getProvider:Hh,getActiveProvider:tr,getActiveProviderName:Gh,getActiveModelId:zh,getActiveModel:Kh,setActiveModel:Jh,getModelNames:Yh,parseModelSpec:zc,listProviders:Xh,listAllModels:Vh,callStream:tg,callChat:ng,getConfiguredProviders:sg,setFallbackChain:Qh,getFallbackChain:Zh,resolveModelForProvider:Gc,MODEL_EQUIVALENTS:er,_reset:og}});var Vc=L((G$,Xc)=>{"use strict";var rg="\x1B[2m",ig="\x1B[0m";function Yc(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var nr=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._lastOutputRow=1}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,s=1){return`\x1B[${e};${s}H`}_statusLine(){return rg+"\u2500".repeat(this._cols)+ig}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(){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")}activate(e){if(!process.stdout.isTTY)return;this._rl=e,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let s=this,n=process.stdout.write.bind(process.stdout);this._origWrite=n,process.stdout.write=function(u,...d){if(s._active&&typeof u=="string"){if(s._cursorOnInputRow){let y=u.replace(/\n/g,"");return y?n(y,...d):!0}let f=s._cols||80,m=0,h=u.split(`
|
|
558
|
+
`);for(let y=0;y<h.length;y++){let $=Yc(h[y]);$>0&&(m+=Math.floor($/f))}let g=h.length-1+m;g>0&&(s._lastOutputRow=Math.min(s._lastOutputRow+g,s._scrollEnd))}return n(u,...d)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(u,...d){if(!s._active)return s._origStderrWrite(u,...d);if(typeof u=="string"&&u.includes("\r")){let f=Math.min(s._lastOutputRow+1,s._scrollEnd);s._origWrite(s._goto(f))}return s._origStderrWrite(u,...d)},this._origLog=console.log,this._origError=console.error;function o(...u){if(!s._active){s._origLog(...u);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origLog(...u),s.drawFooter()}function i(...u){if(!s._active){s._origError(...u);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origError(...u),s.drawFooter()}console.log=o,console.error=i,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(u){s._origSetPr(u),s._active&&s.drawFooter(u)},this._origPrompt=e.prompt.bind(e),e.prompt=function(u){if(!s._active)return s._origPrompt(u);e._prevPos=null,s._origWrite(s._goto(s._rowInput)),s._origPrompt(u),s._cursorOnInputRow=!0};let r=e.question.bind(e);e.question=function(u,d){if(!s._active)return r(u,d);s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),e._prevPos=null,s._cursorOnInputRow=!0,r(u,f=>{s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),s._cursorOnInputRow=!1,s.drawFooter(),d(f)})};let c=e._refreshLine?e._refreshLine.bind(e):null;this._origRefreshLine=c,c&&(e._refreshLine=function(){if(!s._active)return c();let u=s._cols,d=Yc(e._prompt||""),f=u-d-1;if(e.line.length<=f)return c();let m=e.line,h=e.cursor,p=Math.max(1,f-1),y=Math.max(0,h-p),$=(y>0?"\xAB":"")+m.slice(y,y+p+(y>0?0:1));e.line=$,e.cursor=$.length,c(),e.line=m,e.cursor=h}),e.on("line",u=>{s._active&&(s._cursorOnInputRow=!1,s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s.drawFooter())});let l=()=>{this._setScrollRegion(),this.drawFooter()};process.stdout.on("resize",l),this._offResize=()=>process.stdout.off("resize",l)}deactivate(){this._active&&(this._active=!1,this._offResize&&(this._offResize(),this._offResize=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&&(this._rl._refreshLine=this._origRefreshLine,this._origRefreshLine=null)),this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null)}};Xc.exports={StickyFooter:nr}});var el=L((z$,Zc)=>{var{C:V}=ae(),{listProviders:ag,getActiveProviderName:cg,getActiveModelId:lg,setActiveModel:ug}=he();function Qc(t,e,s={}){let{title:n="Select",hint:o="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=s;return new Promise(i=>{let r=e.map(($,_)=>$.isHeader?-1:_).filter($=>$>=0);if(r.length===0){i(null);return}let c=e.findIndex($=>$.isCurrent),l=c>=0?r.indexOf(c):0;l<0&&(l=0);let u=process.stdout.rows?Math.max(process.stdout.rows-6,5):20,d=0;function f(){let $=r[l];return $<d?d=$:$>=d+u&&(d=$-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 v=0;v<m;v++)process.stdout.write(`\x1B[2K
|
|
559
|
+
`);process.stdout.write(`\x1B[${m}A`)}let $=[];$.push(` ${V.bold}${V.cyan}${n}${V.reset}`),$.push(` ${V.dim}${o}${V.reset}`),$.push("");let{start:_,end:T}=f();_>0&&$.push(` ${V.dim}\u2191 more${V.reset}`);for(let v=_;v<T;v++){let C=e[v];if(C.isHeader){$.push(` ${V.bold}${V.dim}${C.label}${V.reset}`);continue}let S=r[l]===v,A=S?`${V.cyan}> `:" ",B=C.isCurrent?` ${V.yellow}<current>${V.reset}`:"";S?$.push(`${A}${V.bold}${C.label}${V.reset}${B}`):$.push(`${A}${V.dim}${C.label}${V.reset}${B}`)}T<e.length&&$.push(` ${V.dim}\u2193 more${V.reset}`);let k=$.join(`
|
|
550
560
|
`);process.stdout.write(k+`
|
|
551
|
-
`),m=$.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($,
|
|
561
|
+
`),m=$.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($,_){if(_){if(_.name==="up"||_.ctrl&&_.name==="p"){l>0&&(l--,h());return}if(_.name==="down"||_.ctrl&&_.name==="n"){l<r.length-1&&(l++,h());return}if(_.name==="return"){let T=e[r[l]];g(),i(T?T.value:null);return}if(_.name==="escape"||_.ctrl&&_.name==="c"){g(),i(null);return}}}process.stdin.on("keypress",y),h()})}async function dg(t){let e=ag(),s=cg(),n=lg(),o=[];for(let r of e)if(r.models.length!==0){o.push({label:r.provider,value:null,isHeader:!0});for(let c of r.models){let l=r.provider===s&&c.id===n;o.push({label:` ${c.name} (${r.provider}:${c.id})`,value:`${r.provider}:${c.id}`,isCurrent:l})}}let i=await Qc(t,o,{title:"Select Model"});return i?(ug(i),console.log(`${V.green}Switched to ${i}${V.reset}`),!0):(console.log(`${V.dim}Cancelled${V.reset}`),!1)}Zc.exports={pickFromList:Qc,showModelPicker:dg}});var rr=L((J$,al)=>{var sr=require("fs"),fg=require("path"),{callChat:tl}=he(),{remember:mg,listMemories:K$,recall:pg}=ot(),or=4,hg=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
552
562
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
553
563
|
|
|
554
564
|
Return ONLY valid JSON in this exact format:
|
|
@@ -574,15 +584,15 @@ Rules:
|
|
|
574
584
|
- value: concise actionable instruction, max 120 chars
|
|
575
585
|
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
576
586
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
577
|
-
- Return ONLY the JSON, no markdown, no explanation`;function
|
|
587
|
+
- Return ONLY the JSON, no markdown, no explanation`;function nl(t){return t.filter(e=>(e.role==="user"||e.role==="assistant")&&typeof e.content=="string"&&e.content.trim().length>10).slice(-40).map(e=>`[${e.role.toUpperCase()}]: ${e.content.substring(0,700)}`).join(`
|
|
578
588
|
|
|
579
|
-
`)}async function
|
|
589
|
+
`)}async function sl(t){if(t.filter(o=>o.role==="user").length<or)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=nl(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=[{role:"system",content:hg},{role:"user",content:`Conversation to analyze:
|
|
580
590
|
|
|
581
|
-
${s}`}];try{let
|
|
582
|
-
`)?o+
|
|
583
|
-
`+
|
|
591
|
+
${s}`}];try{let r=((await tl(n,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!r)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let c=JSON.parse(r[0]);return{memories:Array.isArray(c.memories)?c.memories:[],nex_additions:Array.isArray(c.nex_additions)?c.nex_additions:[],summary:typeof c.summary=="string"?c.summary:null}}catch(o){return{memories:[],nex_additions:[],summary:null,error:o.message}}}function ol(t){let e=[];for(let{key:s,value:n}of t||[]){if(!s||!n||typeof s!="string"||typeof n!="string")continue;let o=s.trim().replace(/\s+/g,"-").substring(0,60),i=n.trim().substring(0,200);if(!o||!i)continue;let r=pg(o);r!==i&&(mg(o,i),e.push({key:o,value:i,action:r?"updated":"added"}))}return e}function rl(t){if(!t||t.length===0)return[];let e=fg.join(process.cwd(),"NEX.md"),s="";try{sr.existsSync(e)&&(s=sr.readFileSync(e,"utf-8"))}catch{}let n=[],o=s;for(let i of t){if(!i||typeof i!="string")continue;let r=i.trim();if(!r)continue;let c=r.substring(0,35).toLowerCase();s.toLowerCase().includes(c)||(n.push(r),o=o?o.endsWith(`
|
|
592
|
+
`)?o+r:o+`
|
|
593
|
+
`+r:r)}return n.length>0&&(o.endsWith(`
|
|
584
594
|
`)||(o+=`
|
|
585
|
-
`),
|
|
595
|
+
`),sr.writeFileSync(e,o,"utf-8")),n}async function gg(t){let e=await sl(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=ol(e.memories),n=rl(e.nex_additions);return{applied:s,nexAdded:n,summary:e.summary}}var $g=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
586
596
|
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
587
597
|
|
|
588
598
|
Return ONLY valid JSON in this exact format:
|
|
@@ -616,37 +626,37 @@ Rules:
|
|
|
616
626
|
---
|
|
617
627
|
- Maximum 3 documents per session. Quality over quantity.
|
|
618
628
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
619
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function
|
|
629
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function il(t){if(t.filter(o=>o.role==="user").length<or)return{documents:[],skip_reason:"Session too short"};let s=nl(t);if(!s.trim())return{documents:[],skip_reason:"No usable content"};let n=[{role:"system",content:$g},{role:"user",content:`Conversation to analyze:
|
|
620
630
|
|
|
621
|
-
${s}`}];try{let
|
|
631
|
+
${s}`}];try{let r=((await tl(n,[],{temperature:0,maxTokens:2e3})).content||"").trim().match(/\{[\s\S]*\}/);if(!r)return{documents:[],error:"No JSON in response"};let c=JSON.parse(r[0]);return{documents:Array.isArray(c.documents)?c.documents:[],skip_reason:c.skip_reason}}catch(o){return{documents:[],error:o.message}}}async function yg(t){let e=await il(t);if(e.error)return{written:[],skipped:[],error:e.error};if(!e.documents||e.documents.length===0)return{written:[],skipped:[],skip_reason:e.skip_reason};let{writeDocument:s,readDocument:n}=fn(),o=[],i=[];for(let r of e.documents){if(!r.name||!r.content)continue;let c=r.name.trim().replace(/\.md$/,"").replace(/[^a-z0-9-]/g,"-").substring(0,60);if(!c)continue;let l=n(c);if(l.content){let d=`
|
|
622
632
|
|
|
623
633
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
624
634
|
|
|
625
|
-
${
|
|
626
|
-
${
|
|
627
|
-
`);let n=Object.keys(s);if(n.length>0&&(console.log(`${
|
|
628
|
-
`);return}let o={...s},
|
|
629
|
-
${
|
|
630
|
-
${
|
|
631
|
-
Add another server?`,!1)}
|
|
635
|
+
${r.content}`;s(c,l.content+d),o.push({name:c,reason:r.reason||"",action:"updated"})}else s(c,r.content),o.push({name:c,reason:r.reason||"",action:"created"})}return{written:o,skipped:i}}al.exports={learnFromSession:gg,learnBrainFromSession:yg,reflectOnSession:sl,reflectBrain:il,applyMemories:ol,applyNexAdditions:rl,LEARN_MIN_MESSAGES:or}});var fl=L((X$,dl)=>{var $e=require("fs"),Gt=require("path"),Y$=require("os"),wg=require("readline"),{C:O}=ae(),cl=".nex",ir=null;function bg(t){ir=t}function Se(t,e=""){let s=e?` ${O.dim}[${e}]${O.reset}`:"",n=` ${O.cyan}${t}${s}${O.reset}: `;return new Promise(o=>{let i=r=>{let c=r.trim()||e;o(c)};if(ir)ir.question(n,i);else{let r=wg.createInterface({input:process.stdin,output:process.stdout});r.question(n,c=>{r.close(),i(c)})}})}function Ht(t,e=!0){return Se(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(n=>n.toLowerCase()!=="n"&&n.toLowerCase()!=="no")}async function ll(t,e,s){let n=e.map((c,l)=>`${O.dim}${l+1})${O.reset} ${c}`).join(" ");console.log(` ${O.cyan}${t}${O.reset}`),console.log(` ${n}`);let o=s?e.indexOf(s)+1:1,i=await Se("Enter number",String(o)),r=parseInt(i,10)-1;return e[Math.max(0,Math.min(r,e.length-1))]}async function xg(){let t=Gt.join(process.cwd(),cl),e=Gt.join(t,"servers.json"),s={};if($e.existsSync(e))try{s=JSON.parse($e.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
636
|
+
${O.bold}${O.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${O.reset}`),console.log(`${O.bold}${O.cyan}\u2551 nex-code Server Setup Wizard \u2551${O.reset}`),console.log(`${O.bold}${O.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${O.reset}
|
|
637
|
+
`);let n=Object.keys(s);if(n.length>0&&(console.log(`${O.dim}Existing profiles: ${n.join(", ")}${O.reset}`),!await Ht("Add or update a server profile?",!0))){console.log(`${O.dim}No changes made.${O.reset}
|
|
638
|
+
`);return}let o={...s},i=!0;for(;i;){console.log(`
|
|
639
|
+
${O.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${O.reset}`);let l=await Se("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${O.red} Name is required.${O.reset}`);continue}let u=await Se("Host / IP address");if(!u){console.log(`${O.red} Host is required.${O.reset}`);continue}let d=await Se("SSH user","root"),f=await Se("SSH port","22"),m=parseInt(f,10)||22,h=await Se("SSH key path (leave empty for SSH agent)",""),p=await ll("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await Ht("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),o[l]=y,console.log(`
|
|
640
|
+
${O.green}\u2713${O.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${p!=="other"?` [${p}]`:""}`),i=await Ht(`
|
|
641
|
+
Add another server?`,!1)}$e.existsSync(t)||$e.mkdirSync(t,{recursive:!0}),$e.writeFileSync(e,JSON.stringify(o,null,2)+`
|
|
632
642
|
`,"utf-8"),console.log(`
|
|
633
|
-
${
|
|
643
|
+
${O.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${O.reset}`);let r=Gt.join(process.cwd(),".gitignore");$e.existsSync(r)&&($e.readFileSync(r,"utf-8").includes(".nex/")||await Ht("Add .nex/ to .gitignore?",!0)&&($e.appendFileSync(r,`
|
|
634
644
|
# nex-code server profiles
|
|
635
645
|
.nex/
|
|
636
|
-
`),console.log(`${
|
|
637
|
-
Set up deploy configs (.nex/deploy.json)?`,!1)&&await
|
|
638
|
-
${
|
|
639
|
-
`)}async function
|
|
640
|
-
${
|
|
641
|
-
`);let
|
|
642
|
-
${
|
|
643
|
-
${
|
|
644
|
-
Add another deploy config?`,!1)}
|
|
646
|
+
`),console.log(`${O.green}\u2713 Added .nex/ to .gitignore${O.reset}`))),await Ht(`
|
|
647
|
+
Set up deploy configs (.nex/deploy.json)?`,!1)&&await ul(o,t),console.log(`
|
|
648
|
+
${O.dim}Use /servers to list profiles, /servers ping to check connectivity.${O.reset}
|
|
649
|
+
`)}async function ul(t,e){let s=e||Gt.join(process.cwd(),cl),n=Gt.join(s,"deploy.json"),o={};if($e.existsSync(n))try{o=JSON.parse($e.readFileSync(n,"utf-8"))}catch{}if(!t){let u=Gt.join(s,"servers.json");if($e.existsSync(u))try{t=JSON.parse($e.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let i=Object.keys(t);console.log(`
|
|
650
|
+
${O.bold}${O.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${O.reset}`),console.log(`${O.bold}${O.cyan}\u2551 Deploy Config Wizard \u2551${O.reset}`),console.log(`${O.bold}${O.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${O.reset}
|
|
651
|
+
`);let r=Object.keys(o);r.length>0&&console.log(`${O.dim}Existing deploy configs: ${r.join(", ")}${O.reset}`);let c={...o},l=!0;for(;l;){console.log(`
|
|
652
|
+
${O.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${O.reset}`);let u=await Se("Config name (e.g. prod, staging)");if(!u){console.log(`${O.red} Name is required.${O.reset}`);continue}let d;i.length>0?d=await ll("Target server",i,i[0]):d=await Se("Target server (profile name or user@host)");let f=await Se("Local path to sync (e.g. dist/ or ./build)","dist/"),m=await Se("Remote destination path (e.g. /var/www/app)");if(!m){console.log(`${O.red} Remote path is required.${O.reset}`);continue}let h=await Se("Deploy script to run after sync (leave empty to skip)",""),p=await Se("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env"),g=p?p.split(",").map(_=>_.trim()).filter(Boolean):[],y={server:d,local_path:f,remote_path:m};h&&(y.deploy_script=h),g.length>0&&(y.exclude=g),c[u]=y;let $=f.endsWith("/")?f:`${f}/`;console.log(`
|
|
653
|
+
${O.green}\u2713${O.reset} Deploy config "${u}": ${$} \u2192 ${d}:${m}`),h&&console.log(` ${O.dim} Then: ${h}${O.reset}`),l=await Ht(`
|
|
654
|
+
Add another deploy config?`,!1)}$e.existsSync(s)||$e.mkdirSync(s,{recursive:!0}),$e.writeFileSync(n,JSON.stringify(c,null,2)+`
|
|
645
655
|
`,"utf-8"),console.log(`
|
|
646
|
-
${
|
|
647
|
-
`)}
|
|
656
|
+
${O.green}\u2713 Saved .nex/deploy.json (${Object.keys(c).length} config${Object.keys(c).length!==1?"s":""})${O.reset}`),console.log(`${O.dim}Use: deploy prod (or with explicit params)${O.reset}
|
|
657
|
+
`)}dl.exports={runServerWizard:xg,runDeployWizard:ul,setWizardRL:bg}});var hl=L((V$,pl)=>{var _g=require("axios"),_n=require("fs"),ml=require("path"),kg="nex-code",ar=ml.join(process.cwd(),".nex"),cr=ml.join(ar,"last-version-check");_n.existsSync(ar)||_n.mkdirSync(ar,{recursive:!0});async function vg(){try{let t=Eg(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};Tg(e);let s=Sg(),o=(await _g.get(`https://registry.npmjs.org/${kg}/latest`,{timeout:5e3})).data.version,i=Cg(o,s);return{hasNewVersion:i,latestVersion:i?o:void 0,currentVersion:i?s:void 0}}catch{return{hasNewVersion:!1}}}function Sg(){return Sn().version}function Eg(){try{if(_n.existsSync(cr)){let t=_n.readFileSync(cr,"utf8");return parseInt(t,10)}}catch{}return null}function Tg(t){try{_n.writeFileSync(cr,t.toString())}catch{}}function Cg(t,e){try{let s=t.split(".").map(Number),n=e.split(".").map(Number);return s[0]>n[0]?!0:s[0]<n[0]?!1:s[1]>n[1]?!0:s[1]<n[1]?!1:s[2]>n[2]}catch{return!1}}pl.exports={checkForNewVersion:vg}});var Al=L((Z$,Rl)=>{var Rg=require("readline"),lt=require("fs"),We=require("path"),{C:a,banner:Ag,cleanupTerminal:gl}=ae(),{listProviders:ur,getActiveProviderName:at,listAllModels:Q$,setFallbackChain:Og,getFallbackChain:Ng,getProvider:Mg}=he(),{flushAutoSave:$l}=bt(),{getActiveModel:ct,setActiveModel:yl}=qn(),{printContext:wl}=To(),{loadAllSkills:Pg,getSkillCommands:dr,handleSkillCommand:Lg}=Zt(),{setReadlineInterface:Ig,setAutoConfirm:qg,getAutoConfirm:bl}=Ie(),{StickyFooter:jg}=Vc(),_s=process.cwd(),Ve=null;function xl(){return Ve?.signal??null}var ks=[{cmd:"/help",desc:"Show full help"},{cmd:"/model",desc:"Show/switch model"},{cmd:"/providers",desc:"List providers and models"},{cmd:"/fallback",desc:"Show/set fallback chain"},{cmd:"/tokens",desc:"Token usage and context budget"},{cmd:"/costs",desc:"Session token costs"},{cmd:"/budget",desc:"Show/set cost limits per provider"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/context",desc:"Show project context"},{cmd:"/autoconfirm",desc:"Toggle auto-confirm"},{cmd:"/save",desc:"Save session"},{cmd:"/load",desc:"Load a saved session"},{cmd:"/sessions",desc:"List saved sessions"},{cmd:"/resume",desc:"Resume last session"},{cmd:"/remember",desc:"Save a memory"},{cmd:"/forget",desc:"Delete a memory"},{cmd:"/memory",desc:"Show all memories"},{cmd:"/brain",desc:"Manage knowledge base"},{cmd:"/brain add",desc:"Add document: /brain add <name> [content]"},{cmd:"/brain list",desc:"List all brain documents"},{cmd:"/brain search",desc:"Search brain: /brain search <query>"},{cmd:"/brain show",desc:"Show document: /brain show <name>"},{cmd:"/brain remove",desc:"Remove document: /brain remove <name>"},{cmd:"/brain rebuild",desc:"Rebuild keyword index"},{cmd:"/brain embed",desc:"Build/rebuild embedding index"},{cmd:"/brain status",desc:"Show brain status (docs, index, embeddings)"},{cmd:"/brain review",desc:"Review pending brain changes (git diff)"},{cmd:"/brain undo",desc:"Undo last brain write"},{cmd:"/learn",desc:"Reflect on session and update memory"},{cmd:"/optimize",desc:"Show optimization opportunities"},{cmd:"/permissions",desc:"Show tool permissions"},{cmd:"/allow",desc:"Auto-allow a tool"},{cmd:"/deny",desc:"Block a tool"},{cmd:"/plan",desc:"Plan mode (analyze before executing)"},{cmd:"/plans",desc:"List saved plans"},{cmd:"/auto",desc:"Set autonomy level"},{cmd:"/commit",desc:"Smart commit (diff + message)"},{cmd:"/diff",desc:"Show current diff"},{cmd:"/review [--strict] [file]",desc:"Deep code review with score table and diff suggestions (--strict: force \u22653 critical findings)"},{cmd:"/branch",desc:"Create feature branch"},{cmd:"/mcp",desc:"MCP servers and tools"},{cmd:"/hooks",desc:"Show configured hooks"},{cmd:"/skills",desc:"List, enable, disable skills"},{cmd:"/tasks",desc:"Show task list"},{cmd:"/servers",desc:"List server profiles / ping"},{cmd:"/docker",desc:"List containers across all servers"},{cmd:"/deploy",desc:"List deploy configs / run named deploy"},{cmd:"/init",desc:"Interactive setup wizard (.nex/)"},{cmd:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function _l(){let t=dr(),e=[...ks,...t],s=Math.max(...e.map(n=>n.cmd.length));console.log("");for(let{cmd:n,desc:o}of ks)console.log(` ${a.cyan}${n.padEnd(s+2)}${a.reset}${a.dim}${o}${a.reset}`);for(let{cmd:n,desc:o}of t)console.log(` ${a.cyan}${n.padEnd(s+2)}${a.reset}${a.dim}${o} ${a.yellow}[skill]${a.reset}`);console.log(`
|
|
648
658
|
${a.dim}Type /help for detailed usage${a.reset}
|
|
649
|
-
`)}function
|
|
659
|
+
`)}function kl(t){try{let e,s;t.endsWith("/")||t.endsWith(We.sep)?(e=t,s=""):(e=We.dirname(t),s=We.basename(t)),e.startsWith("~")&&(e=We.join(require("os").homedir(),e.slice(1)));let n=We.isAbsolute(e)?e:We.resolve(_s,e);if(!lt.existsSync(n)||!lt.statSync(n).isDirectory())return[];let o=lt.readdirSync(n,{withFileTypes:!0}),i=[];for(let r of o){if(r.name.startsWith(".")||r.name==="node_modules"||s&&!r.name.startsWith(s))continue;let c=t.endsWith("/")||t.endsWith(We.sep)?t:We.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?r.name:c+r.name;i.push(r.isDirectory()?l+"/":l)}return i}catch{return[]}}function vl(t){if(t.startsWith("/")){let n=[...ks,...dr()],o=n.map(i=>i.cmd).filter(i=>i.startsWith(t));return[o.length?o:n.map(i=>i.cmd),t]}let e=t.split(/\s+/),s=e[e.length-1]||"";return s&&(s.includes("/")||s.startsWith("./")||s.startsWith("../")||s.startsWith("~"))?[kl(s),s]:[[],t]}function Sl(){console.log(`
|
|
650
660
|
${a.bold}${a.cyan}Commands:${a.reset}
|
|
651
661
|
${a.cyan}/help${a.reset} ${a.dim}Show this help${a.reset}
|
|
652
662
|
${a.cyan}/model [spec]${a.reset} ${a.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${a.reset}
|
|
@@ -707,48 +717,48 @@ ${a.bold}${a.cyan}Undo / Redo:${a.reset}
|
|
|
707
717
|
${a.cyan}/history${a.reset} ${a.dim}Show file change history${a.reset}
|
|
708
718
|
|
|
709
719
|
${a.cyan}/exit${a.reset} ${a.dim}Quit${a.reset}
|
|
710
|
-
`)}function
|
|
711
|
-
${a.bold}${a.cyan}Providers:${a.reset}`);for(let n of t){let o=n.provider===e,
|
|
712
|
-
${a.bold}${a.cyan}Token Usage:${a.reset}`),console.log(` ${a.dim}Model:${a.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${a.dim}Used:${a.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f=
|
|
713
|
-
${a.dim}Breakdown:${a.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:
|
|
720
|
+
`)}function El(t){let s=Math.round(t/100*30),n=30-s;return` ${t>80?a.red:t>50?a.yellow:a.green}${"\u2588".repeat(s)}${a.dim}${"\u2591".repeat(n)}${a.reset} ${t}%`}function lr(){let t=ur(),e=at(),s=ct();console.log(`
|
|
721
|
+
${a.bold}${a.cyan}Providers:${a.reset}`);for(let n of t){let o=n.provider===e,i=n.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,r=o?` ${a.cyan}(active)${a.reset}`:"";console.log(` ${i} ${a.bold}${n.provider}${a.reset}${r}`);for(let c of n.models){let l=c.id===s.id&&o?` ${a.yellow}\u25C4${a.reset}`:"";console.log(` ${a.dim}${c.id}${a.reset} \u2014 ${c.name}${l}`)}}console.log()}async function Tl(t,e){let[s,...n]=t.split(/\s+/);switch(s){case"/help":return Sl(),!0;case"/model":{let o=n.join(" ").trim();if(!o){if(e){let{showModelPicker:i}=el();await i(e)}else{let i=ct(),r=at();console.log(`${a.bold}${a.cyan}Active model:${a.reset} ${a.dim}${r}:${i.id} (${i.name})${a.reset}`),console.log(`${a.gray}Use /model <provider:model> to switch. /providers to see all.${a.reset}`)}return!0}if(o==="list")return lr(),!0;if(yl(o)){let i=ct(),r=at();console.log(`${a.green}Switched to ${r}:${i.id} (${i.name})${a.reset}`)}else console.log(`${a.red}Unknown model: ${o}${a.reset}`),console.log(`${a.gray}Use /providers to see available models${a.reset}`);return!0}case"/providers":return lr(),!0;case"/fallback":{let o=n.join(" ").trim();if(!o){let r=Ng();return r.length===0?(console.log(`${a.dim}No fallback chain configured${a.reset}`),console.log(`${a.dim}Use /fallback anthropic,openai,local to set${a.reset}`)):console.log(`${a.bold}${a.cyan}Fallback chain:${a.reset} ${r.join(" \u2192 ")}`),!0}let i=o.split(",").map(r=>r.trim()).filter(Boolean);return Og(i),console.log(`${a.green}Fallback chain: ${i.join(" \u2192 ")}${a.reset}`),!0}case"/tokens":{let{getConversationMessages:o}=de(),{getUsage:i}=Oe(),{TOOL_DEFINITIONS:r}=qe(),c=o(),l=i(c,r),u=ct(),d=at();console.log(`
|
|
722
|
+
${a.bold}${a.cyan}Token Usage:${a.reset}`),console.log(` ${a.dim}Model:${a.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${a.dim}Used:${a.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f=El(l.percentage);return console.log(` ${f}`),console.log(`
|
|
723
|
+
${a.dim}Breakdown:${a.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:i}=At();return n.join(" ").trim()==="reset"?(i(),console.log(`${a.green}Cost tracking reset${a.reset}`),!0):(console.log(`
|
|
714
724
|
${o()}
|
|
715
|
-
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:
|
|
716
|
-
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let y of p){let $=
|
|
725
|
+
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:i,checkBudget:r,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=At(),d=n[0];if(!d){let h=o(),p=ur();console.log(`
|
|
726
|
+
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let y of p){let $=i(y.provider),_=h[y.provider];if(_!==void 0){g=!0;let T=Math.min(100,Math.round($/_*100)),k=10,v=Math.round(T/100*k),C=k-v,A=`${T>=100?a.red:T>=80?a.yellow:a.green}${"\u2588".repeat(v)}${a.dim}${"\u2591".repeat(C)}${a.reset}`;console.log(` ${a.bold}${y.provider}:${a.reset} $${$.toFixed(2)} / $${_.toFixed(2)} (${T}%) ${A}`)}else y.provider==="ollama"||y.provider==="local"?console.log(` ${a.bold}${y.provider}:${a.reset} ${a.dim}free (no limit)${a.reset}`):$>0&&console.log(` ${a.bold}${y.provider}:${a.reset} $${$.toFixed(2)} ${a.dim}(no limit)${a.reset}`)}return g||console.log(` ${a.dim}No limits set. Use /budget <provider> <amount> to set one.${a.reset}`),console.log(),!0}let f=n[1];if(!f){let h=r(d);return h.limit!==null?console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} ${a.dim}(no limit)${a.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return c(d),l(),console.log(`${a.green}Removed cost limit for ${d}${a.reset}`),!0;let m=parseFloat(f);return isNaN(m)||m<=0?(console.log(`${a.red}Invalid amount: ${f}. Use a positive number or 'off'.${a.reset}`),!0):(u(d,m),l(),console.log(`${a.green}Set ${d} budget limit: $${m.toFixed(2)}${a.reset}`),!0)}case"/clear":{let{clearConversation:o,getConversationMessages:i}=de(),{clearHistory:r}=Nt(),c=i();if(c.filter(u=>u.role==="user").length>=4){process.stdout.write(`${a.dim}Reflecting on session...${a.reset} `);let{learnFromSession:u}=rr();u(c).then(d=>{if(!d.skipped&&!d.error&&(d.applied.length>0||d.nexAdded.length>0)){let f=d.applied.length+d.nexAdded.length;process.stdout.write(`${a.green}${f} learning(s) saved${a.reset}
|
|
717
727
|
`)}else process.stdout.write(`${a.dim}nothing new${a.reset}
|
|
718
728
|
`)}).catch(()=>process.stdout.write(`
|
|
719
|
-
`))}return o(),
|
|
720
|
-
${a.bold}${a.cyan}Sessions:${a.reset}`);for(let
|
|
721
|
-
${a.bold}${a.cyan}Memory:${a.reset}`);for(let
|
|
729
|
+
`))}return o(),r(),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/context":return await wl(_s),!0;case"/autoconfirm":{let o=!bl();return qg(o),console.log(`${a.green}Auto-confirm: ${o?"ON":"OFF"}${a.reset}`),o&&console.log(`${a.yellow} \u26A0 File changes will be applied without confirmation${a.reset}`),!0}case"/save":{let{saveSession:o}=bt(),{getConversationMessages:i}=de(),r=n.join(" ").trim()||`session-${Date.now()}`,c=i();if(c.length===0)return console.log(`${a.yellow}No conversation to save${a.reset}`),!0;let l=ct(),u=at();return o(r,c,{model:l.id,provider:u}),console.log(`${a.green}Session saved: ${r} (${c.length} messages)${a.reset}`),!0}case"/load":{let{loadSession:o}=bt(),{setConversationMessages:i}=de(),r=n.join(" ").trim();if(!r)return console.log(`${a.red}Usage: /load <name>${a.reset}`),!0;let c=o(r);return c?(i(c.messages),console.log(`${a.green}Loaded session: ${c.name} (${c.messageCount} messages)${a.reset}`),!0):(console.log(`${a.red}Session not found: ${r}${a.reset}`),!0)}case"/sessions":{let{listSessions:o}=bt(),i=o();if(i.length===0)return console.log(`${a.dim}No saved sessions${a.reset}`),!0;console.log(`
|
|
730
|
+
${a.bold}${a.cyan}Sessions:${a.reset}`);for(let r of i){let c=r.updatedAt?new Date(r.updatedAt).toLocaleString():"?",l=r.name==="_autosave"?` ${a.dim}(auto)${a.reset}`:"";console.log(` ${a.cyan}${r.name}${a.reset}${l} \u2014 ${r.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=bt(),{setConversationMessages:i}=de(),r=o();return r?(i(r.messages),console.log(`${a.green}Resumed: ${r.name} (${r.messageCount} messages)${a.reset}`),!0):(console.log(`${a.yellow}No session to resume${a.reset}`),!0)}case"/remember":{let{remember:o}=ot(),i=n.join(" ").trim();if(!i)return console.log(`${a.red}Usage: /remember <key>=<value> or /remember <text>${a.reset}`),!0;let r=i.indexOf("="),c,l;return r>0?(c=i.substring(0,r).trim(),l=i.substring(r+1).trim()):(c=i.substring(0,40).replace(/\s+/g,"-"),l=i),o(c,l),console.log(`${a.green}Remembered: ${c}${a.reset}`),!0}case"/forget":{let{forget:o}=ot(),i=n.join(" ").trim();return i?(o(i)?console.log(`${a.green}Forgotten: ${i}${a.reset}`):console.log(`${a.red}Memory not found: ${i}${a.reset}`),!0):(console.log(`${a.red}Usage: /forget <key>${a.reset}`),!0)}case"/memory":{let{listMemories:o}=ot(),i=o();if(i.length===0)return console.log(`${a.dim}No memories saved${a.reset}`),!0;console.log(`
|
|
731
|
+
${a.bold}${a.cyan}Memory:${a.reset}`);for(let r of i)console.log(` ${a.cyan}${r.key}${a.reset} = ${r.value}`);return console.log(),!0}case"/brain":{let{listDocuments:o,readDocument:i,writeDocument:r,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=fn(),m=n[0],h=n.slice(1).join(" ").trim();switch(m){case"add":{if(!h)return console.log(`${a.red}Usage: /brain add <name> [content]${a.reset}`),console.log(`${a.dim} /brain add api-notes \u2014 creates empty file${a.reset}`),console.log(`${a.dim} /brain add api-notes This is content \u2014 writes directly${a.reset}`),!0;let p=h.indexOf(" ");if(p<0){r(h,`# ${h}
|
|
722
732
|
|
|
723
|
-
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${a.green}Created .nex/brain/${h}.md${a.reset}`),console.log(`${a.dim}Edit it directly at: ${g}${a.reset}`)}else{let g=h.substring(0,p),y=h.substring(p+1);
|
|
724
|
-
${a.bold}${a.cyan}Brain Documents:${a.reset}`);let g=Math.max(8,...p.map($=>$.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 $ of p){let{frontmatter:
|
|
733
|
+
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${a.green}Created .nex/brain/${h}.md${a.reset}`),console.log(`${a.dim}Edit it directly at: ${g}${a.reset}`)}else{let g=h.substring(0,p),y=h.substring(p+1);r(g,y),console.log(`${a.green}Added to brain: ${g}${a.reset}`)}return!0}case"list":{let p=o();if(p.length===0)return console.log(`${a.dim}No brain documents yet. Use /brain add <name> to create one.${a.reset}`),!0;console.log(`
|
|
734
|
+
${a.bold}${a.cyan}Brain Documents:${a.reset}`);let g=Math.max(8,...p.map($=>$.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 $ of p){let{frontmatter:_}=i($.name),T=Array.isArray(_.tags)?_.tags.join(", "):"",k=$.size<1024?`${$.size}B`:`${($.size/1024).toFixed(1)}K`,v=$.modified.toLocaleDateString();console.log(` ${a.cyan}${$.name.padEnd(g+2)}${a.reset}${a.dim}${T.substring(0,y-1).padEnd(y)}${k.padStart(7)} ${v}${a.reset}`)}return console.log(),!0}case"search":{if(!h)return console.log(`${a.red}Usage: /brain search <query>${a.reset}`),!0;let p=await f(h,{topK:5});if(p.length===0)return console.log(`${a.dim}No matching brain documents for: ${h}${a.reset}`),!0;console.log(`
|
|
725
735
|
${a.bold}${a.cyan}Brain Search: "${h}"${a.reset}`);for(let g of p){let y=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
|
|
726
|
-
${a.cyan}${g.name}${a.reset} ${a.dim}(score: ${y})${a.reset}`),console.log(` ${a.dim}${g.excerpt||""}${a.reset}`)}return console.log(),!0}case"show":{if(!h)return console.log(`${a.red}Usage: /brain show <name>${a.reset}`),!0;let p=
|
|
736
|
+
${a.cyan}${g.name}${a.reset} ${a.dim}(score: ${y})${a.reset}`),console.log(` ${a.dim}${g.excerpt||""}${a.reset}`)}return console.log(),!0}case"show":{if(!h)return console.log(`${a.red}Usage: /brain show <name>${a.reset}`),!0;let p=i(h);return p.content?(console.log(`
|
|
727
737
|
${a.bold}${a.cyan}${h}.md${a.reset}
|
|
728
|
-
`),console.log(p.content),!0):(console.log(`${a.red}Document not found: ${h}${a.reset}`),!0)}case"remove":{if(!h)return console.log(`${a.red}Usage: /brain remove <name>${a.reset}`),!0;let{confirm:p}=
|
|
729
|
-
${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync($)?a.green+"present"+a.reset:a.dim+"not built"+a.reset}`),console.log(` Embeddings: ${g.existsSync(
|
|
738
|
+
`),console.log(p.content),!0):(console.log(`${a.red}Document not found: ${h}${a.reset}`),!0)}case"remove":{if(!h)return console.log(`${a.red}Usage: /brain remove <name>${a.reset}`),!0;let{confirm:p}=Ie();if(!await p(`Remove brain document "${h}"?`))return console.log(`${a.dim}Cancelled${a.reset}`),!0;let y=c(h);return console.log(y?`${a.green}Removed: ${h}.md${a.reset}`:`${a.red}Document not found: ${h}${a.reset}`),!0}case"rebuild":{let p=l(),g=Object.keys(p.documents).length;return console.log(`${a.green}Index rebuilt: ${g} document(s)${a.reset}`),!0}case"embed":{if(!await d())return console.log(`${a.yellow}Ollama embedding model not available.${a.reset}`),console.log(`${a.dim}Set NEX_EMBED_MODEL env var (default: nomic-embed-text) and ensure Ollama is running.${a.reset}`),!0;console.log(`${a.dim}Building embedding index...${a.reset}`);try{let g=await u(),y=Object.keys(g.documents||{}).length;console.log(`${a.green}Embedding index built: ${y} document(s)${a.reset}`)}catch(g){console.log(`${a.red}Embedding failed: ${g.message}${a.reset}`)}return!0}case"status":{let p=o(),g=require("fs"),y=require("path"),$=y.join(process.cwd(),".nex","brain",".brain-index.json"),_=y.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
|
|
739
|
+
${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync($)?a.green+"present"+a.reset:a.dim+"not built"+a.reset}`),console.log(` Embeddings: ${g.existsSync(_)?a.green+"present"+a.reset:a.dim+"not built (run /brain embed)"+a.reset}`),p.length>0){let T=p.reduce((k,v)=>k+v.size,0);console.log(` Total size: ${T<1024?T+"B":(T/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:$}=await y("git diff .nex/brain/",{cwd:process.cwd()});$.trim()?(console.log(`
|
|
730
740
|
${a.bold}${a.cyan}Brain Changes (git diff):${a.reset}
|
|
731
|
-
`),console.log($)):console.log(`${a.dim}No pending brain changes (clean git state)${a.reset}`)}catch{console.log(`${a.dim}Not a git repo or no brain dir${a.reset}`)}return!0}case"undo":{let p=require("fs"),y=require("path").join(process.cwd(),".nex","brain");if(!p.existsSync(y))return console.log(`${a.dim}No brain directory found${a.reset}`),!0;let $=o();if($.length===0)return console.log(`${a.dim}No brain documents to undo${a.reset}`),!0;let
|
|
741
|
+
`),console.log($)):console.log(`${a.dim}No pending brain changes (clean git state)${a.reset}`)}catch{console.log(`${a.dim}Not a git repo or no brain dir${a.reset}`)}return!0}case"undo":{let p=require("fs"),y=require("path").join(process.cwd(),".nex","brain");if(!p.existsSync(y))return console.log(`${a.dim}No brain directory found${a.reset}`),!0;let $=o();if($.length===0)return console.log(`${a.dim}No brain documents to undo${a.reset}`),!0;let _=$[0],{exec:T}=require("child_process"),{promisify:k}=require("util"),v=k(T);try{await v(`git checkout -- ".nex/brain/${_.name}.md"`,{cwd:process.cwd()}),l(),console.log(`${a.green}Undone: restored ${_.name}.md from git${a.reset}`)}catch{console.log(`${a.red}Could not undo \u2014 not tracked in git or no prior version${a.reset}`)}return!0}default:{let p=o();if(p.length===0)console.log(`
|
|
732
742
|
${a.bold}${a.cyan}Brain Knowledge Base${a.reset}`),console.log(`${a.dim}No documents yet. Create with /brain add <name>${a.reset}`),console.log(`
|
|
733
743
|
${a.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${a.reset}
|
|
734
744
|
`);else{console.log(`
|
|
735
|
-
${a.bold}${a.cyan}Brain: ${p.length} document(s)${a.reset}`);for(let g of p){let{frontmatter:y}=
|
|
745
|
+
${a.bold}${a.cyan}Brain: ${p.length} document(s)${a.reset}`);for(let g of p){let{frontmatter:y}=i(g.name),$=Array.isArray(y.tags)?` [${y.tags.join(", ")}]`:"";console.log(` ${a.cyan}${g.name}${a.reset}${a.dim}${$}${a.reset}`)}console.log(`
|
|
736
746
|
${a.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${a.reset}
|
|
737
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:
|
|
747
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:i}=rr(),{getConversationMessages:r}=de(),c=r(),l=c.filter(u=>u.role==="user").length;if(l<4)return console.log(`${a.yellow}Session too short to learn from (need 4+ user messages, have ${l})${a.reset}`),!0;console.log(`${a.dim}Analyzing session for learnings...${a.reset}`);try{let[u,d]=await Promise.all([o(c),i(c)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${a.dim}Session too short${a.reset}`),!0;u.error&&console.log(`${a.red}Reflection error: ${u.error}${a.reset}`),console.log(""),u.summary&&(console.log(`${a.bold}Session:${a.reset} ${a.dim}${u.summary}${a.reset}`),console.log(""));let f=u.applied&&u.applied.length>0,m=u.nexAdded&&u.nexAdded.length>0,h=d.written&&d.written.length>0;if(!f&&!m&&!h)console.log(`${a.dim}No new learnings extracted from this session${a.reset}`);else{if(f){console.log(`${a.bold}${a.cyan}Memory updates:${a.reset}`);for(let{key:p,value:g,action:y}of u.applied){let $=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${$} ${a.bold}${p}${a.reset} = ${g}`)}}if(m){console.log(`${a.bold}${a.cyan}Added to NEX.md:${a.reset}`);for(let p of u.nexAdded)console.log(` ${a.green}+${a.reset} ${p}`)}if(h){console.log(`${a.bold}${a.cyan}Brain documents:${a.reset}`);for(let{name:p,reason:g,action:y}of d.written){let $=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${$} ${a.bold}${p}.md${a.reset}${g?a.dim+" \u2014 "+g+a.reset:""}`)}}}console.log("")}catch(u){console.log(`${a.red}Learn failed: ${u.message}${a.reset}`)}return!0}case"/optimize":{let{getConversationMessages:o}=de(),{getUsage:i}=Oe(),{TOOL_DEFINITIONS:r}=qe(),{listMemories:c}=ot(),l=o(),u=i(l,r),d=ct(),f=at(),m=c();console.log(`
|
|
738
748
|
${a.bold}${a.cyan}Optimization Report${a.reset}
|
|
739
749
|
`);let h=u.percentage>80?a.red:u.percentage>50?a.yellow:a.green;if(console.log(`${a.bold}Context Window:${a.reset} ${h}${u.percentage}%${a.reset} used (${u.used.toLocaleString()} / ${u.limit.toLocaleString()} tokens)`),u.percentage>75?console.log(` ${a.yellow}\u2192 Tip: Use /clear to free context (auto-learns first)${a.reset}`):u.percentage>50?console.log(` ${a.dim}\u2192 Context is filling up, consider /clear soon${a.reset}`):console.log(` ${a.green}\u2192 Context healthy${a.reset}`),console.log(`
|
|
740
|
-
${a.bold}Memory:${a.reset} ${m.length} entries`),m.length===0)console.log(` ${a.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${a.reset}`);else{let
|
|
741
|
-
${a.bold}Active Model:${a.reset} ${f}:${d.id}`);let p=d.contextWindow||d.maxTokens||0;p>0&&p<32e3&&l.length>10?console.log(` ${a.yellow}\u2192 Small context window (${(p/1e3).toFixed(0)}k). Consider /model for larger context${a.reset}`):p>=128e3&&console.log(` ${a.green}\u2192 Large context window (${(p/1e3).toFixed(0)}k) \u2014 good for long sessions${a.reset}`);let g=l.filter(
|
|
750
|
+
${a.bold}Memory:${a.reset} ${m.length} entries`),m.length===0)console.log(` ${a.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${a.reset}`);else{let T=[...m].sort((C,S)=>new Date(S.updatedAt)-new Date(C.updatedAt))[0],k=T?Math.round((Date.now()-new Date(T.updatedAt))/6e4):null,v=k!==null?k<60?`${k}m ago`:`${Math.round(k/60)}h ago`:"?";console.log(` ${a.dim}Latest update: ${v}${a.reset}`),m.length>30&&console.log(` ${a.yellow}\u2192 Many memories (${m.length}) \u2014 consider pruning with /forget${a.reset}`)}console.log(`
|
|
751
|
+
${a.bold}Active Model:${a.reset} ${f}:${d.id}`);let p=d.contextWindow||d.maxTokens||0;p>0&&p<32e3&&l.length>10?console.log(` ${a.yellow}\u2192 Small context window (${(p/1e3).toFixed(0)}k). Consider /model for larger context${a.reset}`):p>=128e3&&console.log(` ${a.green}\u2192 Large context window (${(p/1e3).toFixed(0)}k) \u2014 good for long sessions${a.reset}`);let g=l.filter(_=>_.role==="user").length;console.log(`
|
|
742
752
|
${a.bold}Session:${a.reset} ${g} turns, ${l.length} messages total`),g>=4&&g%10===0&&console.log(` ${a.cyan}\u2192 Good time to /learn and capture session insights${a.reset}`);let y=[],$=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync($)||y.push("Create NEX.md in project root to give nex-code project-specific instructions"),y.length>0){console.log(`
|
|
743
|
-
${a.bold}Quick Wins:${a.reset}`);for(let
|
|
753
|
+
${a.bold}Quick Wins:${a.reset}`);for(let _ of y)console.log(` ${a.cyan}\u2192${a.reset} ${_}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:i,startExecution:r,setPlanMode:c,getPlanContent:l,formatPlan:u}=Dt(),{invalidateSystemPromptCache:d}=de(),f=n.join(" ").trim();if(f==="status"){let m=o();return console.log(u(m)),!0}if(f==="approve"){if(i()){r(),c(!1),d();let m=!!l();console.log(`${a.green}${a.bold}Plan approved!${a.reset} ${m?"Executing the planned steps...":"Starting execution..."}`),console.log(`${a.dim}Plan mode disabled \u2014 all tools now available.${a.reset}`)}else console.log(`${a.red}No plan to approve. Enter plan mode first with /plan${a.reset}`);return!0}return c(!0),d(),console.log(`
|
|
744
754
|
${a.cyan}${a.bold}\u250C\u2500 PLAN MODE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510${a.reset}
|
|
745
755
|
${a.cyan}${a.bold}\u2502${a.reset} Analysis only \u2014 no file changes until approved ${a.cyan}${a.bold}\u2502${a.reset}
|
|
746
756
|
${a.cyan}${a.bold}\u2502${a.reset} ${a.dim}Read-only tools only \xB7 /plan approve to execute${a.reset} ${a.cyan}${a.bold}\u2502${a.reset}
|
|
747
|
-
${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),f&&console.log(`${a.dim}Task: ${f}${a.reset}`),!0}case"/plans":{let{listPlans:o}=
|
|
748
|
-
${a.bold}${a.cyan}Plans:${a.reset}`);for(let
|
|
749
|
-
${a.bold}${a.cyan}Tool Permissions:${a.reset}`);for(let
|
|
757
|
+
${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),f&&console.log(`${a.dim}Task: ${f}${a.reset}`),!0}case"/plans":{let{listPlans:o}=Dt(),i=o();if(i.length===0)return console.log(`${a.dim}No saved plans${a.reset}`),!0;console.log(`
|
|
758
|
+
${a.bold}${a.cyan}Plans:${a.reset}`);for(let r of i){let c=r.status==="completed"?`${a.green}\u2713`:r.status==="executing"?`${a.blue}\u2192`:`${a.dim}\u25CB`;console.log(` ${c} ${a.reset}${a.bold}${r.name}${a.reset} \u2014 ${r.task||"?"} (${r.steps} steps, ${r.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:o,setAutonomyLevel:i,AUTONOMY_LEVELS:r}=Dt(),c=n.join(" ").trim();return c?(i(c)?console.log(`${a.green}Autonomy: ${c}${a.reset}`):console.log(`${a.red}Unknown level: ${c}. Use: ${r.join(", ")}${a.reset}`),!0):(console.log(`${a.bold}${a.cyan}Autonomy:${a.reset} ${o()}`),console.log(`${a.dim}Levels: ${r.join(", ")}${a.reset}`),!0)}case"/permissions":{let{listPermissions:o}=$n(),i=o();console.log(`
|
|
759
|
+
${a.bold}${a.cyan}Tool Permissions:${a.reset}`);for(let r of i){let c=r.mode==="allow"?`${a.green}\u2713`:r.mode==="deny"?`${a.red}\u2717`:`${a.yellow}?`;console.log(` ${c} ${a.reset}${a.bold}${r.tool}${a.reset} ${a.dim}(${r.mode})${a.reset}`)}return console.log(`
|
|
750
760
|
${a.dim}Use /allow <tool> or /deny <tool> to change${a.reset}
|
|
751
|
-
`),!0}case"/allow":{let{setPermission:o,savePermissions:
|
|
761
|
+
`),!0}case"/allow":{let{setPermission:o,savePermissions:i}=$n(),r=n.join(" ").trim();return r?(o(r,"allow"),i(),console.log(`${a.green}${r}: allow${a.reset}`),!0):(console.log(`${a.red}Usage: /allow <tool>${a.reset}`),!0)}case"/deny":{let{setPermission:o,savePermissions:i}=$n(),r=n.join(" ").trim();return r?(o(r,"deny"),i(),console.log(`${a.red}${r}: deny${a.reset}`),!0):(console.log(`${a.red}Usage: /deny <tool>${a.reset}`),!0)}case"/commit":{let{isGitRepo:o,commit:i,analyzeDiff:r,formatDiffSummary:c}=gt(),{confirm:l}=Ie();if(!o())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let u=n.join(" ").trim();if(u){let p=await i(u);return console.log(p?`${a.green}Committed: ${p} \u2014 ${u}${a.reset}`:`${a.red}Commit failed${a.reset}`),!0}if(!r())return console.log(`${a.yellow}No changes to commit${a.reset}`),!0;let f=await c();if(console.log(f),!await l(" Commit changes?"))return!0;let h=await i("nex-code update");return h&&console.log(`${a.green} \u2713 Committed: ${h}${a.reset}`),!0}case"/diff":{let{isGitRepo:o,formatDiffSummary:i}=gt();return o()?(console.log(i()),!0):(console.log(`${a.red}Not a git repository${a.reset}`),!0)}case"/review":{let{isGitRepo:o,getDiff:i}=gt(),{processInput:r}=de(),c=n.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),f=`## Review Protocol
|
|
752
762
|
|
|
753
763
|
**Phase 1 \u2014 Broad Scan:** Read the target code and identify all issues at a high level.
|
|
754
764
|
|
|
@@ -785,26 +795,26 @@ For each issue, include:
|
|
|
785
795
|
|
|
786
796
|
\u26A0 STRICT MODE: You MUST identify at least 3 critical weaknesses. If the code appears clean, dig deeper \u2014 look for subtle error-swallowing, race conditions, missing validation, or architecture risks. Do not give a passing score without identifying at least 3 critical issues.`:""}`,m;if(u)m=`Do a thorough code review of \`${u}\`.
|
|
787
797
|
|
|
788
|
-
${f}`;else{if(!o())return console.log(`${a.red}Not a git repository \u2014 try /review <file>${a.reset}`),!0;let[h,p]=await Promise.all([
|
|
798
|
+
${f}`;else{if(!o())return console.log(`${a.red}Not a git repository \u2014 try /review <file>${a.reset}`),!0;let[h,p]=await Promise.all([i(!1),i(!0)]),g=p||h;if(!g||!g.trim())return console.log(`${a.yellow}No changes to review \u2014 commit something or specify a file: /review <file>${a.reset}`),!0;m=`Review the following code diff.
|
|
789
799
|
|
|
790
800
|
${f}
|
|
791
801
|
|
|
792
802
|
\`\`\`diff
|
|
793
803
|
${g.substring(0,2e4)}
|
|
794
|
-
\`\`\``}return await
|
|
804
|
+
\`\`\``}return await r(m),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:i,createBranch:r}=gt();if(!o())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let c=n.join(" ").trim();if(!c){let u=i();return console.log(`${a.bold}${a.cyan}Branch:${a.reset} ${u||"(detached)"}`),!0}let l=r(c);return console.log(l?`${a.green}Created and switched to: ${l}${a.reset}`:`${a.red}Failed to create branch${a.reset}`),!0}case"/mcp":{let{listServers:o,connectAll:i,disconnectAll:r}=Wn(),c=n.join(" ").trim();if(c==="connect")return console.log(`${a.dim}Connecting MCP servers...${a.reset}`),i().then(u=>{for(let d of u)d.error?console.log(` ${a.red}\u2717${a.reset} ${d.name}: ${d.error}`):console.log(` ${a.green}\u2713${a.reset} ${d.name}: ${d.tools} tools`);u.length===0&&console.log(`${a.dim}No MCP servers configured in .nex/config.json${a.reset}`)}).catch(u=>{console.log(`${a.red}MCP connection error: ${u.message}${a.reset}`)}),!0;if(c==="disconnect")return r(),console.log(`${a.green}All MCP servers disconnected${a.reset}`),!0;let l=o();if(l.length===0)return console.log(`${a.dim}No MCP servers configured${a.reset}`),console.log(`${a.dim}Add servers to .nex/config.json under "mcpServers"${a.reset}`),!0;console.log(`
|
|
795
805
|
${a.bold}${a.cyan}MCP Servers:${a.reset}`);for(let u of l){let d=u.connected?`${a.green}\u2713 connected${a.reset}`:`${a.dim}\u25CB disconnected${a.reset}`;console.log(` ${d} ${a.bold}${u.name}${a.reset} (${u.command}) \u2014 ${u.toolCount} tools`)}return console.log(`
|
|
796
806
|
${a.dim}Use /mcp connect to connect all servers${a.reset}
|
|
797
|
-
`),!0}case"/hooks":{let{listHooks:o}=
|
|
798
|
-
${a.bold}${a.cyan}Hooks:${a.reset}`);for(let
|
|
807
|
+
`),!0}case"/hooks":{let{listHooks:o}=Fo(),i=o();if(i.length===0)return console.log(`${a.dim}No hooks configured${a.reset}`),console.log(`${a.dim}Add hooks to .nex/config.json or .nex/hooks/${a.reset}`),!0;console.log(`
|
|
808
|
+
${a.bold}${a.cyan}Hooks:${a.reset}`);for(let r of i){console.log(` ${a.cyan}${r.event}${a.reset}`);for(let c of r.commands)console.log(` ${a.dim}\u2192 ${c}${a.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:o,enableSkill:i,disableSkill:r}=Zt(),c=n.join(" ").trim();if(c.startsWith("enable ")){let u=c.substring(7).trim();return i(u)?console.log(`${a.green}Skill enabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}if(c.startsWith("disable ")){let u=c.substring(8).trim();return r(u)?console.log(`${a.yellow}Skill disabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}let l=o();if(l.length===0)return console.log(`${a.dim}No skills loaded${a.reset}`),console.log(`${a.dim}Add .md or .js files to .nex/skills/${a.reset}`),!0;console.log(`
|
|
799
809
|
${a.bold}${a.cyan}Skills:${a.reset}`);for(let u of l){let d=u.enabled?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,f=u.type==="prompt"?`${a.dim}(prompt)${a.reset}`:`${a.dim}(script)${a.reset}`,m=[];u.commands>0&&m.push(`${u.commands} cmd`),u.tools>0&&m.push(`${u.tools} tools`);let h=m.length>0?` \u2014 ${m.join(", ")}`:"";console.log(` ${d} ${a.bold}${u.name}${a.reset} ${f}${h}`)}return console.log(`
|
|
800
810
|
${a.dim}Use /skills enable <name> or /skills disable <name>${a.reset}
|
|
801
|
-
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:
|
|
811
|
+
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:i}=Qn();return n.join(" ").trim()==="clear"?(i(),console.log(`${a.green}Tasks cleared${a.reset}`),!0):(console.log(`
|
|
802
812
|
`+o()+`
|
|
803
|
-
`),!0)}case"/undo":{let{undo:o,getUndoCount:
|
|
813
|
+
`),!0)}case"/undo":{let{undo:o,getUndoCount:i}=Nt(),r=o();if(!r)return console.log(`${a.yellow}Nothing to undo${a.reset}`),!0;r.wasCreated?console.log(`${a.green}Undone: deleted ${r.filePath} (was created by ${r.tool})${a.reset}`):console.log(`${a.green}Undone: restored ${r.filePath} (${r.tool})${a.reset}`);let c=i();return c>0&&console.log(`${a.dim}${c} more change(s) to undo${a.reset}`),!0}case"/redo":{let{redo:o,getRedoCount:i}=Nt(),r=o();if(!r)return console.log(`${a.yellow}Nothing to redo${a.reset}`),!0;console.log(`${a.green}Redone: ${r.filePath} (${r.tool})${a.reset}`);let c=i();return c>0&&console.log(`${a.dim}${c} more change(s) to redo${a.reset}`),!0}case"/history":{let{getHistory:o,getUndoCount:i,getRedoCount:r}=Nt(),c=o(20);if(c.length===0)return console.log(`${a.dim}No file changes in this session${a.reset}`),!0;console.log(`
|
|
804
814
|
${a.bold}File Change History${a.reset}
|
|
805
815
|
`);for(let l of c){let u=new Date(l.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${a.dim}${u}${a.reset} ${a.yellow}${l.tool}${a.reset} ${l.filePath}`)}return console.log(`
|
|
806
|
-
${a.dim}${
|
|
807
|
-
`),!0}case"/k8s":{let o=n.join(" ").trim(),{exec:
|
|
816
|
+
${a.dim}${i()} undo / ${r()} redo available${a.reset}
|
|
817
|
+
`),!0}case"/k8s":{let o=n.join(" ").trim(),{exec:i}=require("child_process"),{promisify:r}=require("util"),c=r(i),l=o||null,u=l?`ssh -o ConnectTimeout=10 -o BatchMode=yes ${l.replace(/[^a-zA-Z0-9@._-]/g,"")} `:"",d=f=>l?`${u}"${f.replace(/"/g,'\\"')}"`:f;console.log(`
|
|
808
818
|
${a.bold}${a.cyan}Kubernetes Overview${a.reset}${l?a.dim+" (remote: "+l+")"+a.reset:""}
|
|
809
819
|
`);try{let{stdout:f}=await c(d("kubectl get namespaces --no-headers -o custom-columns=NAME:.metadata.name"),{timeout:15e3}),m=f.trim().split(`
|
|
810
820
|
`).filter(Boolean);console.log(`${a.bold}Namespaces (${m.length}):${a.reset}`);for(let h of m)console.log(` ${a.cyan}${h}${a.reset}`);console.log()}catch{return console.log(`${a.dim}Could not reach cluster \u2014 is kubectl configured?${a.reset}
|
|
@@ -812,45 +822,57 @@ ${a.bold}${a.cyan}Kubernetes Overview${a.reset}${l?a.dim+" (remote: "+l+")"+a.re
|
|
|
812
822
|
`).filter(Boolean),h=m.filter($=>$.includes("Running")).length,p=m.filter($=>$.includes("Pending")).length,g=m.filter($=>$.includes("Failed")||$.includes("Error")||$.includes("CrashLoop")).length;console.log(`${a.bold}Pods: ${m.length} total ${a.green}${h} running${a.reset} ${a.yellow}${p} pending${a.reset} ${a.red}${g} unhealthy${a.reset}
|
|
813
823
|
`);let y=m.filter($=>!$.includes("Running")&&!$.includes("<none>"));if(y.length>0){console.log(`${a.bold}${a.red}Unhealthy Pods:${a.reset}`);for(let $ of y)console.log(` ${a.red}${$}${a.reset}`);console.log()}console.log(`${a.dim}Use k8s_pods / k8s_logs / k8s_exec tools for details${a.reset}`),console.log(`${a.dim}Or: /k8s user@host to query a remote cluster${a.reset}
|
|
814
824
|
`)}catch(f){console.log(`${a.dim}Could not list pods: ${f.message}${a.reset}
|
|
815
|
-
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:
|
|
825
|
+
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:i,sshExec:r}=Lt(),c=o(),l=Object.keys(c);if(l.length===0)return console.log(`
|
|
816
826
|
${a.dim}No servers configured. Create .nex/servers.json:${a.reset}`),console.log(`${a.dim} { "prod": { "host": "1.2.3.4", "user": "jarvis", "os": "almalinux9" } }${a.reset}
|
|
817
827
|
`),!0;if(n[0]==="ping"){let f=n[1]?[n[1]]:l;return console.log(`
|
|
818
|
-
${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(f.map(async m=>{if(!c[m]){console.log(` ${a.red}\u2717${a.reset} ${m} \u2014 unknown profile`);return}try{let h={...c[m],_name:m},{exitCode:p}=await
|
|
828
|
+
${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(f.map(async m=>{if(!c[m]){console.log(` ${a.red}\u2717${a.reset} ${m} \u2014 unknown profile`);return}try{let h={...c[m],_name:m},{exitCode:p}=await r(h,"echo ok",{timeout:8e3});console.log(p===0?` ${a.green}\u2713${a.reset} ${m} (${h.user?h.user+"@":""}${h.host})`:` ${a.red}\u2717${a.reset} ${m} (${h.host}) \u2014 SSH failed (exit ${p})`)}catch(h){console.log(` ${a.red}\u2717${a.reset} ${m} \u2014 ${h.message}`)}})),console.log(""),!0}let{formatProfile:d}=Lt();console.log(`
|
|
819
829
|
${a.bold}${a.cyan}Configured servers (${l.length}):${a.reset}`);for(let f of l)console.log(` ${a.green}${f}${a.reset} ${a.dim}${d(f,c[f])}${a.reset}`);return console.log(`
|
|
820
830
|
${a.dim}/servers ping \u2014 check SSH connectivity for all servers${a.reset}`),console.log(`${a.dim}/servers ping <name> \u2014 check a specific server${a.reset}
|
|
821
|
-
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:
|
|
822
|
-
${a.bold}${a.cyan}Docker Containers:${a.reset}`);for(let[m,h]of f){let p=m==="local"?`${a.dim}local${a.reset}`:`${a.cyan}${m}${a.reset}`;try{let g;if(m==="local"){let{stdout:y}=await l(u,{timeout:8e3});g=(y||"").trim()}else{let y=await
|
|
823
|
-
`).forEach(y=>console.log(` ${a.dim}${y}${a.reset}`)))}catch(g){console.log(` ${p}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=
|
|
824
|
-
${a.bold}Running deploy: ${c}${l?" (dry run)":""}${a.reset}`);let f=await d("deploy",{...u,dry_run:l});return console.log(f),!0}if(
|
|
831
|
+
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:i}=Lt(),{exec:r}=require("child_process"),{promisify:c}=require("util"),l=c(r),u=n[0]==="-a"||n[0]==="--all"?'docker ps -a --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"':'docker ps --format "table {{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"',d=o(),f=[["local",null],...Object.entries(d)];console.log(`
|
|
832
|
+
${a.bold}${a.cyan}Docker Containers:${a.reset}`);for(let[m,h]of f){let p=m==="local"?`${a.dim}local${a.reset}`:`${a.cyan}${m}${a.reset}`;try{let g;if(m==="local"){let{stdout:y}=await l(u,{timeout:8e3});g=(y||"").trim()}else{let y=await i(h,u,{timeout:1e4});if(g=[y.stdout,y.stderr].filter(Boolean).join("").trim(),y.exitCode!==0){console.log(` ${p}: ${a.red}SSH error (${y.exitCode})${a.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${p}: ${a.dim}(no containers)${a.reset}`):(console.log(` ${p}:`),g.split(`
|
|
833
|
+
`).forEach(y=>console.log(` ${a.dim}${y}${a.reset}`)))}catch(g){console.log(` ${p}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=ro(),i=o(),r=Object.keys(i),c=n[0];if(c&&r.includes(c)){let l=n.includes("--dry-run")||n.includes("-n"),u=i[c],{executeTool:d}=qe();console.log(`
|
|
834
|
+
${a.bold}Running deploy: ${c}${l?" (dry run)":""}${a.reset}`);let f=await d("deploy",{...u,dry_run:l});return console.log(f),!0}if(r.length===0)return console.log(`
|
|
825
835
|
${a.dim}No deploy configs. Run /init to create .nex/deploy.json${a.reset}
|
|
826
836
|
`),!0;console.log(`
|
|
827
|
-
${a.bold}${a.cyan}Deploy configs (${
|
|
837
|
+
${a.bold}${a.cyan}Deploy configs (${r.length}):${a.reset}`);for(let[l,u]of Object.entries(i)){let d=u.local_path||"",f=`${u.server}:${u.remote_path}`,m=u.deploy_script?` ${a.dim}\u2192 ${u.deploy_script}${a.reset}`:"";console.log(` ${a.green}${l}${a.reset} ${a.dim}${d} \u2192 ${f}${a.reset}${m}`)}return console.log(`
|
|
828
838
|
${a.dim}/deploy <name> \u2014 run a named deploy${a.reset}`),console.log(`${a.dim}/deploy <name> --dry-run \u2014 preview without syncing${a.reset}
|
|
829
|
-
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:
|
|
830
|
-
`).filter(Boolean).slice(-
|
|
831
|
-
`)}catch{}}function Ee(){let{isPlanMode:t,getAutonomyLevel:e}=
|
|
832
|
-
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:
|
|
839
|
+
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:i,setWizardRL:r}=fl();return r(e),n[0]==="deploy"?await i():await o(),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:return Lg(t)||console.log(`${a.red}Unknown command: ${s}. Type /help${a.reset}`),!0}}var fr=1e3;function mr(){return We.join(process.cwd(),".nex","repl_history")}function Cl(){try{let t=mr();if(lt.existsSync(t))return lt.readFileSync(t,"utf-8").split(`
|
|
840
|
+
`).filter(Boolean).slice(-fr)}catch{}return[]}function xs(t){try{let e=mr(),s=We.dirname(e);lt.existsSync(s)||lt.mkdirSync(s,{recursive:!0}),lt.appendFileSync(e,t+`
|
|
841
|
+
`)}catch{}}function Ee(){let{isPlanMode:t,getAutonomyLevel:e}=Dt(),s=[];t()&&s.push("plan");let n=e();n!=="interactive"&&s.push(n);let o=at(),i=ct(),r=o==="ollama"?i.id:`${o}:${i.id}`;return s.push(r),`${s.length>0?`${a.dim}[${s.join(" \xB7 ")}]${a.reset} `:""}${a.bold}${a.cyan}>${a.reset} `}var pr="\x1B[200~",hr="\x1B[201~";function Dg(t){return typeof t=="string"&&t.includes(pr)}function Fg(t){return typeof t=="string"&&t.includes(hr)}function kn(t){return typeof t!="string"?t:t.split(pr).join("").split(hr).join("")}async function Ug(){if(!Mg("local"))return!1;try{let{exec:e}=require("child_process"),{promisify:s}=require("util");return await s(e)("curl -s --max-time 1 http://localhost:11434/api/tags"),yl("local:llama3"),!0}catch{return!1}}async function Wg(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=de();t(xl);let o=ur().some(P=>P.configured),i=(async()=>{Pg();let P=ct(),N=at();return{model:P,providerName:N}})(),r=(async()=>o?!0:await Ug()?(console.log(`${a.green}\u2713 Local Ollama detected \u2014 using local models${a.reset}`),console.log(`${a.dim}Tip: Set API keys for cloud providers for more model options (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${a.reset}
|
|
842
|
+
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:P}=hl();return await P()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([i,r,c]);!u&&!o&&(console.error(`
|
|
833
843
|
${a.red}\u2717 No provider configured and no local Ollama detected.${a.reset}
|
|
834
|
-
`),process.exit(1));let f=
|
|
835
|
-
|
|
836
|
-
|
|
844
|
+
`),process.exit(1));let f=Cl(),m=Rg.createInterface({input:process.stdin,output:process.stdout,prompt:Ee(),completer:vl,history:f,historySize:fr});Ig(m);let{setAskUserHandler:h}=qe();h(async(P,N)=>{let j="\x1B[0m",U="\x1B[1m",W="\x1B[2m",H="\x1B[36m";return process.stdout.write(`
|
|
845
|
+
${U}\x1B[33m\u2753${j} ${U}${P}${j}
|
|
846
|
+
|
|
847
|
+
`),N.forEach((G,ye)=>{process.stdout.write(` ${H}${ye+1}${j} ${G}
|
|
848
|
+
`)}),process.stdout.write(` ${W}${N.length+1}${j} ${W}Eigene Antwort\u2026${j}
|
|
849
|
+
`),process.stdout.write(`
|
|
850
|
+
${H}[1-${N.length+1}]${j} \u203A `),new Promise(G=>{m.pause(),process.stdin.isTTY&&process.stdin.setRawMode(!0);let ye=Be=>{let Re=Be.toString();if(Re===""){process.stdout.write(`
|
|
851
|
+
`),Pe(),G("");return}let ue=parseInt(Re);ue>=1&&ue<=N.length?(process.stdout.write(`${U}${N[ue-1]}${j}
|
|
852
|
+
|
|
853
|
+
`),Pe(),G(N[ue-1])):(ue===N.length+1||Re==="\r"||Re===`
|
|
854
|
+
`)&&(process.stdout.write(`
|
|
855
|
+
`),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",ye),process.stdout.write(` ${H}\u203A${j} `),m.resume(),m.once("line",Ae=>{process.stdout.write(`
|
|
856
|
+
`),G(Ae.trim()||"")}))};function Pe(){process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",ye),m.resume()}process.stdin.on("data",ye)})});let p=new jg;p.activate(m);let g=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;Ag(g,_s,{yolo:bl()}),d.hasNewVersion&&console.log(`${a.yellow}\u{1F4A1} New version available!${a.reset} Run ${a.cyan}npm update -g nex-code${a.reset} to upgrade from ${a.dim}${d.currentVersion}${a.reset} to ${a.green}${d.latestVersion}${a.reset}
|
|
857
|
+
`),await wl(_s);let y=!1,$=0,_=!1,T=null;function k(){$l(),p.deactivate(),gl(),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",k),process.on("exit",()=>{$l()}),m.on("SIGINT",()=>{if(gl(),$++,$>=2){k();return}if(y){Ve&&Ve.abort();let{cancelPendingAskUser:P}=qe();P(),console.log(`
|
|
858
|
+
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),y=!1,m.setPrompt(Ee()),m.prompt()}else process.stdout.write(`
|
|
837
859
|
${a.dim} (Press Ctrl+C again to exit)${a.reset}
|
|
838
|
-
`),m.setPrompt(Ee()),m.prompt(),
|
|
839
|
-
`).replace(/\r/g,"").trim();if(
|
|
840
|
-
`).length,
|
|
841
|
-
`)),
|
|
842
|
-
`)),!0}if(
|
|
843
|
-
`)),
|
|
844
|
-
`)),!0}return
|
|
845
|
-
\x1B[2K ${a.cyan}${
|
|
846
|
-
\x1B[2K ${a.dim}\u2026 +${
|
|
847
|
-
`)}return}if(
|
|
848
|
-
`).trim();if(
|
|
849
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${
|
|
850
|
-
`).trim();if(
|
|
851
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${
|
|
852
|
-
`).forEach((
|
|
853
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${
|
|
860
|
+
`),m.setPrompt(Ee()),m.prompt(),T&&clearTimeout(T),T=setTimeout(()=>{$=0,T=null},2e3)}),process.on("SIGINT",()=>{process.stdin.isTTY?($++,$>=2&&k()):k()});let v=!1,C=[],S=0,A={},B=!1;function q(){let P=C.join(`
|
|
861
|
+
`).replace(/\r/g,"").trim();if(C=[],v=!1,!P)return!0;S++,B=!0;let N=S;A[N]=P;let j=P.split(`
|
|
862
|
+
`).length,U=j>1?`[Pasted content #${N} \u2014 ${j} lines]`:`[Pasted content #${N}]`,W=m.line||"",H=W&&!W.endsWith(" ")?" ":"",F=W+H+U;return m.setPrompt(Ee()),m.prompt(),m.line=F,m.cursor=F.length,m._refreshLine(),!0}function Q(P){return P.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(N,j)=>A[Number(j)]||"")}function ne(){S=0,A={},B=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let P=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(N,...j){if(N!=="data")return P.call(process.stdin,N,...j);let U=j[0];if(Buffer.isBuffer(U)&&(U=U.toString("utf8")),typeof U!="string")return P.call(process.stdin,N,...j);let W=U.includes(pr),H=U.includes(hr);if(W&&H){let F=kn(U);return F&&C.push(...F.split(`
|
|
863
|
+
`)),q()}if(W){v=!0,C=[];let F=kn(U);return F&&C.push(...F.split(`
|
|
864
|
+
`)),!0}if(H){let F=kn(U);return F&&C.push(...F.split(`
|
|
865
|
+
`)),q()}if(v){let F=kn(U);return F&&C.push(...F.split(`
|
|
866
|
+
`)),!0}return P.call(process.stdin,N,...j)}}let Z=0;function me(){if(Z>0){let P="";for(let N=0;N<Z;N++)P+="\x1B[1B\x1B[2K";P+=`\x1B[${Z}A`,process.stdout.write(P),Z=0}}function ke(P){let N=[...ks,...dr()].filter(G=>G.cmd.startsWith(P));if(!N.length||N.length===1&&N[0].cmd===P)return;let j=10,U=N.slice(0,j),W=Math.max(...U.map(G=>G.cmd.length)),H="";for(let{cmd:G,desc:ye}of U){let Pe=G.substring(0,P.length),Be=G.substring(P.length),Re=" ".repeat(Math.max(0,W-G.length+2));H+=`
|
|
867
|
+
\x1B[2K ${a.cyan}${Pe}${a.reset}${a.dim}${Be}${Re}${ye}${a.reset}`}Z=U.length,N.length>j&&(H+=`
|
|
868
|
+
\x1B[2K ${a.dim}\u2026 +${N.length-j} more${a.reset}`,Z++);let F=m._prompt.replace(/\x1b\[[0-9;]*m/g,"").length;H+=`\x1B[${Z}A\x1B[${F+m.cursor+1}G`,process.stdout.write(H)}process.stdin.isTTY&&process.stdin.on("keypress",(P,N)=>{me(),!(N&&(N.name==="tab"||N.name==="return"))&&setImmediate(()=>{m.line&&m.line.startsWith("/")&&ke(m.line)})});let le=null,Qe=`${a.dim}...${a.reset} `;m.setPrompt(Ee()),m.prompt(),m.on("line",async P=>{if(me(),Object.keys(A).length>0&&(P=Q(P),ne(),m.setPrompt(Ee())),y){let W=P.trim();if(W){let{injectMidRunNote:H}=de();H(W),process.stdout.write(`${a.cyan} \u270E Wird im n\xE4chsten Schritt ber\xFCcksichtigt${a.reset}
|
|
869
|
+
`)}return}if(le!==null){if(le._mode==="triple"){if(P.trim()==='"""'){let W=le.join(`
|
|
870
|
+
`).trim();if(le=null,W){xs(W.replace(/\n/g,"\\n")),y=!0,$=0,_=!1,T&&(clearTimeout(T),T=null),Ve=new AbortController;try{await s(W)}catch(F){if(!Ve?.signal?.aborted){let G=F.message?.split(`
|
|
871
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${G}${a.reset}`)}}y=!1;let H=j();H>0&&process.stdout.write(`${a.gray}[${H} messages] ${a.reset}`)}m.setPrompt(Ee()),m.prompt();return}le.push(P),m.setPrompt(Qe),m.prompt();return}if(P.endsWith("\\"))le.push(P.slice(0,-1));else{le.push(P);let W=le.join(`
|
|
872
|
+
`).trim();if(le=null,W){xs(W.replace(/\n/g,"\\n")),y=!0,$=0,_=!1,T&&(clearTimeout(T),T=null),Ve=new AbortController;try{await s(W)}catch(G){if(!Ve?.signal?.aborted){let ye=G.message?.split(`
|
|
873
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${ye}${a.reset}`)}}let{getConversationLength:H}=de();y=!1;let F=H();F>0&&process.stdout.write(`${a.gray}[${F} messages] ${a.reset}`)}m.setPrompt(Ee()),m.prompt();return}m.setPrompt(Qe),m.prompt();return}if(P.trim()==='"""'||P.trim().startsWith('"""')){let W=P.trim().substring(3);le=W?[W]:[],le._mode="triple",m.setPrompt(Qe),m.prompt();return}if(P.endsWith("\\")){le=[P.slice(0,-1)],le._mode="backslash",m.setPrompt(Qe),m.prompt();return}let N=P.trim();if(!N){m.setPrompt(Ee()),m.prompt();return}if(xs(N),N==="/"){_l(),m.setPrompt(Ee()),m.prompt();return}if(N.startsWith("/")){await Tl(N,m),m.setPrompt(Ee()),m.prompt();return}{let W="\x1B[48;5;237m",H=process.stdout.columns||80;N.split(`
|
|
874
|
+
`).forEach((G,ye)=>{let Pe=ye===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",Be=2+G.length,Re=" ".repeat(Math.max(0,H-Be));console.log(`${W}${Pe} ${G}${Re}\x1B[0m`)})}y=!0,$=0,_=!1,T&&(clearTimeout(T),T=null),Ve=new AbortController;try{await s(N)}catch(W){if(!Ve?.signal?.aborted){let H=W.message?.split(`
|
|
875
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${H}${a.reset}`)}}y=!1;let{getConversationLength:j}=de(),U=j();U>0&&process.stdout.write(`${a.gray}[${U} messages] ${a.reset}`),m.setPrompt(Ee()),m.prompt()}),m.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}Rl.exports={startREPL:Wg,getPrompt:Ee,loadHistory:Cl,appendHistory:xs,getHistoryPath:mr,HISTORY_MAX:fr,showCommandList:_l,completer:vl,completeFilePath:kl,handleSlashCommand:Tl,showProviders:lr,showHelp:Sl,renderBar:El,hasPasteStart:Dg,hasPasteEnd:Fg,stripPasteSequences:kn,getAbortSignal:xl}});var Ml=require("path");require("dotenv").config({path:Ml.join(__dirname,"..",".env")});require("dotenv").config();var re=process.argv.slice(2);(re.includes("--help")||re.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
854
876
|
|
|
855
877
|
Options:
|
|
856
878
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -863,4 +885,4 @@ Options:
|
|
|
863
885
|
--json Output result as JSON (for CI parsing)
|
|
864
886
|
-h, --help Show this help
|
|
865
887
|
-v, --version Show version
|
|
866
|
-
`),process.exit(0));if(
|
|
888
|
+
`),process.exit(0));if(re.includes("-v")||re.includes("--version")){let t=Sn();console.log(t.version),process.exit(0)}var Bg=re.includes("--yolo")||re.includes("-yolo");if(Bg){let{setAutoConfirm:t}=Ie();t(!0)}var gr=re.indexOf("--model");if(gr!==-1&&re[gr+1]){let{setActiveModel:t}=he();t(re[gr+1])}var $r=re.indexOf("--max-turns");if($r!==-1&&re[$r+1]){let t=parseInt(re[$r+1],10);if(t>0){let{setMaxIterations:e}=de();e(t)}}else try{let t=require("fs"),e=Ml.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let s=JSON.parse(t.readFileSync(e,"utf-8")),n=parseInt(s.maxIterations,10);if(n>0){let{setMaxIterations:o}=de();o(n)}}}catch{}function yr(){if(process.platform==="darwin")try{let{spawn:t}=require("child_process"),e=t("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});e.unref();let s=()=>{try{e.kill()}catch{}};process.on("exit",s),process.on("SIGINT",s),process.on("SIGTERM",s)}catch{}}function Ol(t){if(re.includes("--auto")){let{setAutoConfirm:o}=Ie();o(!0)}if(!re.includes("--model")){let{setActiveModel:o}=he(),i=process.env.HEADLESS_MODEL||"devstral-small-2:24b";o(i)}let{processInput:s,getConversationMessages:n}=de();s(t).then(()=>{if(re.includes("--json")){let i=n().filter(r=>r.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:i?.content||""}))}process.exit(0)}).catch(o=>{re.includes("--json")?console.log(JSON.stringify({success:!1,error:o.message})):console.error(o.message),process.exit(1)})}var Nl=re.indexOf("--prompt-file");if(Nl!==-1){let t=re[Nl+1];(!t||t.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let e=require("fs"),s;try{s=e.readFileSync(t,"utf-8").trim()}catch(n){console.error(`--prompt-file: cannot read file: ${n.message}`),process.exit(1)}if(s||(console.error("--prompt-file: file is empty"),process.exit(1)),re.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}yr(),Ol(s)}else{let t=re.indexOf("--task");if(t!==-1){let e=re[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),yr(),Ol(e)}else{yr();let{startREPL:e}=Al();e()}}
|