nex-code 0.3.24 → 0.3.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/nex-code.js +279 -238
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var N=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var
|
|
2
|
+
var N=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var $n=N((Ng,Sl)=>{Sl.exports={name:"nex-code",version:"0.3.25",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 hr=N((Pg,pr)=>{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"},dr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],fr=["\u273D","\u2726","\u2727","\u2726"],ws=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=dr[this.frame%dr.length],s="";if(this.startTime){let n=Math.floor((Date.now()-this.startTime)/1e3);if(n>=60){let o=Math.floor(n/60),r=n%60;s=` ${M.dim}${o}m ${String(r).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}},mr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],bs=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=mr[this.frame%mr.length],s=this._formatElapsed(),n=s?` ${M.dim}${s}${M.reset}`:"",o="";for(let r=0;r<this.labels.length;r++){let a,c;switch(this.statuses[r]){case"done":a=`${M.green}\u2713${M.reset}`,c=M.dim;break;case"error":a=`${M.red}\u2717${M.reset}`,c=M.dim;break;default:a=`${M.cyan}${e}${M.reset}`,c=""}let l=r===this.labels.length-1?n:"";o+=`\x1B[2K ${a} ${c}${this.labels[r]}${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
|
|
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 r;switch(this.statuses[o]){case"done":r=`${M.green}\u2713${M.reset}`;break;case"error":r=`${M.red}\u2717${M.reset}`;break;default:r=`${M.yellow}\u25CB${M.reset}`}let a=o===this.labels.length-1?s:"";n+=`\x1B[2K ${r} ${M.dim}${this.labels[o]}${M.reset}${a}
|
|
5
|
+
`}process.stderr.write(n)}},yn={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},wn={done:M.green,in_progress:M.cyan,pending:M.dim,failed:M.red},Ke=null,xs=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=fr[this.frame%fr.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${M.dim}(${o})${M.reset}`:"",a=`\x1B[2K${M.cyan}${e}${M.reset} ${this.name}\u2026${r}
|
|
6
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=yn[l.status]||yn.pending,f=wn[l.status]||wn.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;a+=`\x1B[2K ${M.dim}${u}${M.reset} ${f}${d}${M.reset} ${m}
|
|
7
7
|
`}a+=`\x1B[${this.lineCount}A`,process.stderr.write(a),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
8
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Ke=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,Ke===this&&(Ke=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,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,a=`\x1B[2K${
|
|
11
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d
|
|
12
|
-
`}process.stderr.write(a)}};function
|
|
13
|
-
`),n=s.slice(0,e),o=s.length-e,r=`${
|
|
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,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,a=`\x1B[2K${M.green}\u2714${M.reset} ${this.name} ${M.dim}(${e} \xB7 ${r})${M.reset}
|
|
11
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=yn[l.status]||yn.pending,f=wn[l.status]||wn.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;a+=`\x1B[2K ${M.dim}${u}${M.reset} ${f}${d}${M.reset} ${M.dim}${m}${M.reset}
|
|
12
|
+
`}process.stderr.write(a)}};function El(t){Ke=t}function Cl(){return Ke}function Tl(){Ke&&(Ke.stop(),Ke=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}pr.exports={C:M,Spinner:ws,MultiProgress:bs,TaskProgress:xs,setActiveTaskProgress:El,getActiveTaskProgress:Cl,cleanupTerminal:Tl}});var $r=N((Lg,gr)=>{var G={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"},Rl={read_file:"Read file",write_file:"Write file",edit_file:"Edit file",patch_file:"Patch file",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"},Al={read_file:"Reading file",write_file:"Writing file",edit_file:"Editing file",patch_file:"Patching file",list_directory:"Listing directory",bash:"Running command",grep:"Searching code",search_files:"Searching files",glob:"Finding files",web_fetch:"Fetching content",web_search:"Searching the web",git_status:"Checking repository",git_diff:"Analyzing changes",git_log:"Reading git history",git_commit:"Creating commit",git_push:"Pushing changes",git_pull:"Pulling changes",git_branch:"Managing branches",git_stash:"Stashing changes",task_list:"Managing tasks",spawn_agents:"Delegating to agents",ask_user:"Awaiting input",switch_model:"Switching model",gh_run_list:"GitHub Actions",gh_run_view:"GitHub Actions",gh_workflow_trigger:"Triggering workflow",browser_open:"Opening browser",browser_screenshot:"Taking screenshot",browser_click:"Clicking element",browser_fill:"Filling form",ssh_exec:"Running on server",ssh_upload:"Uploading to server",ssh_download:"Downloading from server",service_manage:"Managing service",service_logs:"Reading service logs",container_list:"Listing containers",container_logs:"Reading container logs",container_exec:"Running in container",brain_write:"Saving to memory",deploy:"Deploying"};function Ol(t,e){let s=(t||[]).filter(r=>r&&r.canExecute!==!1);if(s.length===0)return`${G.cyan} \u25C6 Step ${e}${G.reset}`;let n=[...new Set(s.map(r=>Al[r.fnName]||r.fnName))],o;if(n.length===1&&s.length===1){o=n[0];let a=s[0].args||{},c=` ${G.reset}${G.dim}`;a.path?o+=`${c}${a.path.split("/").pop()}`:a.command?o+=`${c}${String(a.command).substring(0,50)}`:a.query?o+=`${c}${String(a.query).substring(0,50)}`:a.pattern&&(o+=`${c}${String(a.pattern).substring(0,50)}`)}else n.length===1?o=`${n[0]} (${s.length})`:n.length<=3?o=n.join(" \xB7 "):o=`${s.length} actions`;return`${G.cyan} \u25C6 ${o}${G.reset}`}function Ml(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=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=Rl[t]||t.replace(/_/g," "),o=s?` ${G.dim}${s}${G.reset}`:"";return`${G.cyan} \u23FA${G.reset} ${G.bold}${n}${G.reset}${o}`}function Nl(t,e=8){let s=t.split(`
|
|
13
|
+
`),n=s.slice(0,e),o=s.length-e,r=`${G.dim} \u23BF ${G.reset}`,a=" ",c=n.map((l,u)=>`${u===0?r:a}${G.green}${l}${G.reset}`).join(`
|
|
14
14
|
`);return o>0&&(c+=`
|
|
15
|
-
${
|
|
15
|
+
${G.gray} \u2026+${o} more lines${G.reset}`),c}function Pl(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 Ll(t,e,s,n){let o=String(s||"");if(n){let a=o.split(`
|
|
16
16
|
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80),c=o.match(/\nHINT: (.+)/),l=c?`
|
|
17
|
-
${
|
|
17
|
+
${G.dim}${c[1].substring(0,100)}${G.reset}`:"";return` ${G.red}\u23BF ${a}${G.reset}${l}`}let r;switch(t){case"read_file":{let a=o.split(`
|
|
18
18
|
`).filter(Boolean),c=a.length,l=a[a.length-1],u=l?parseInt(l.match(/^(\d+):/)?.[1]||"0"):0;(e.line_start||e.line_end)&&u>c?r=`Read lines ${e.line_start||1}\u2013${u}`:r=`Read ${c} line${c!==1?"s":""}`;break}case"write_file":{let a=(e.content||"").split(`
|
|
19
19
|
`).length;r=`Wrote ${a} line${a!==1?"s":""}`;break}case"edit_file":r="Edited successfully";break;case"patch_file":{let a=(e.patches||[]).length;r=`Applied ${a} patch${a!==1?"es":""}`;break}case"bash":{let a=o.match(/^EXIT (\d+)/);if(a){let c=a[1],l=o.match(/\nHINT: (.+)/);if(l)r=`Exit ${c} \u2014 ${l[1].substring(0,60)}`;else{let u=o.split(`
|
|
20
20
|
`).filter(f=>f&&!f.startsWith("EXIT ")),d=u[0]?` \xB7 ${u[0].substring(0,60)}`:"";r=`Exit ${c}${d}`}}else{let c=o.split(`
|
|
@@ -25,110 +25,110 @@ ${J.gray} \u2026+${o} more lines${J.reset}`),c}function Al(t,e){switch(t){ca
|
|
|
25
25
|
`).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;r=a?`${a[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let a=(o.match(/^\+[^+]/gm)||[]).length,c=(o.match(/^-[^-]/gm)||[]).length;r=a||c?`+${a} \u2212${c} lines`:"No diff";break}case"git_log":{let a=o.split(`
|
|
26
26
|
`).filter(c=>/^commit\s+[0-9a-f]{7}/.test(c)).length;r=a>0?`${a} commit${a!==1?"s":""}`:"Log retrieved";break}case"web_fetch":r="Fetched";break;case"web_search":{let a=o.split(`
|
|
27
27
|
|
|
28
|
-
`).filter(Boolean).length;r=`${a} result${a!==1?"s":""}`;break}case"task_list":r="Done";break;case"spawn_agents":{let a=(o.match(/✓ Agent/g)||[]).length,c=(o.match(/✗ Agent/g)||[]).length;r=c>0?`${a} done, ${c} failed`:`${a} agent${a!==1?"s":""} done`;break}case"switch_model":{let a=o.match(/Switched to (.+)/);r=a?`\u2192 ${a[1]}`:"Done";break}default:r="Done"}return` ${
|
|
29
|
-
`),u=s.yolo?` ${n}${
|
|
28
|
+
`).filter(Boolean).length;r=`${a} result${a!==1?"s":""}`;break}case"task_list":r="Done";break;case"spawn_agents":{let a=(o.match(/✓ Agent/g)||[]).length,c=(o.match(/✗ Agent/g)||[]).length;r=c>0?`${a} done, ${c} failed`:`${a} agent${a!==1?"s":""} done`;break}case"switch_model":{let a=o.match(/Switched to (.+)/);r=a?`\u2192 ${a[1]}`:"Done";break}default:r="Done"}return` ${G.dim}\u23BF ${r}${G.reset}`}gr.exports={C:G,formatToolCall:Ml,formatResult:Nl,getToolSpinnerText:Pl,formatToolSummary:Ll,formatSectionHeader:Ol}});var oe=N((Ig,yr)=>{var $t={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 Il(t,e){return[...t].map(s=>s===" "?s:`\x1B[38;2;${e[0]};${e[1]};${e[2]}m${s}`).join("")+$t.reset}function ql(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 jl(t,e,s={}){let n=$t.bold,o=$t.dim,r=$t.reset,a=["\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=a.map((d,f)=>{let m=f/(a.length-1||1);return Il(d,ql(c,m))}).join(`
|
|
29
|
+
`),u=s.yolo?` ${n}${$t.yellow}\u26A1 YOLO${r}`:"";console.log(`
|
|
30
30
|
${l}
|
|
31
|
-
${o}Agentic Coding CLI v${
|
|
31
|
+
${o}Agentic Coding CLI v${$n().version}${r}
|
|
32
32
|
${o}Model: ${t}${r} ${o}\xB7 /help${r}${u}
|
|
33
|
-
`)}var{Spinner:
|
|
34
|
-
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||16384,c=await
|
|
35
|
-
`);h=g.pop()||"";for(let w of g){if(!w.trim())continue;let $;try{$=JSON.parse(w)}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||{}}}))}};
|
|
33
|
+
`)}var{Spinner:Dl,MultiProgress:Fl,TaskProgress:Ul,setActiveTaskProgress:Wl,getActiveTaskProgress:Bl,cleanupTerminal:Hl}=hr(),{formatToolCall:Gl,formatResult:zl,getToolSpinnerText:Kl,formatToolSummary:Jl,formatSectionHeader:Yl}=$r();yr.exports={C:$t,banner:jl,Spinner:Dl,MultiProgress:Fl,TaskProgress:Ul,setActiveTaskProgress:Wl,getActiveTaskProgress:Bl,cleanupTerminal:Hl,formatToolCall:Gl,formatResult:zl,getToolSpinnerText:Kl,formatToolSummary:Jl,formatSectionHeader:Yl}});var Oe=N((qg,vr)=>{var Xl=require("readline"),{C:bn}=oe(),wr=[/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/],_s=[/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 br(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,r=>r.replace(/;/g,"\0")).replace(/\bwhile\s[\s\S]*?\bdone\b/g,r=>r.replace(/;/g,"\0")).split(/\s*(?:&&|;)\s*/).map(r=>r.replace(/\x00/g,";").trim()).filter(Boolean);if(n.length===0)return!1;let o=r=>{let a=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(a))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let c=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return c?c.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>o(u)):_s.some(l=>l.test(r))}return/^\w+=\$?\(/.test(a)||/^\w+=["']/.test(a)||/^\w+=\S/.test(a)?!0:_s.some(c=>c.test(a))};return n.every(o)}var vs=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],xr=[/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/],_r=[...vs,...xr],Ss=!1,ks=null;function Vl(t){Ss=t}function Ql(){return Ss}function Zl(t){ks=t}function eu(t){for(let e of wr)if(e.test(t))return e;return null}function tu(t){if(/ssh\s/.test(t)&&br(t))return!1;for(let e of _r)if(e.test(t))return!0;return!1}function nu(t){for(let e of vs)if(e.test(t))return!0;return!1}function su(t,e={}){if(Ss)return Promise.resolve(!0);let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=r=>{let a=r.trim().toLowerCase();a==="a"&&e.toolName?(kr(e.toolName),n(!0)):n(a!=="n")};if(ks)ks.question(`${bn.yellow}${t} ${s}${bn.reset}`,o);else{let r=Xl.createInterface({input:process.stdin,output:process.stdout});r.question(`${bn.yellow}${t} ${s}${bn.reset}`,a=>{r.close(),o(a)})}})}var kr=()=>{};function ou(t){kr=t}vr.exports={FORBIDDEN_PATTERNS:wr,SSH_SAFE_PATTERNS:_s,isSSHReadOnly:br,DANGEROUS_BASH:_r,CRITICAL_BASH:vs,NOTABLE_BASH:xr,isForbidden:eu,isDangerous:tu,isCritical:nu,confirm:su,setAutoConfirm:Vl,getAutoConfirm:Ql,setReadlineInterface:Zl,setAllowAlwaysHandler:ou}});var yt=N((jg,Sr)=>{var Es=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`)}};Sr.exports={BaseProvider:Es}});var Tr=N((Dg,Cr)=>{var xn=require("axios"),ru=require("http"),iu=require("https"),{BaseProvider:au}=yt(),_n=new ru.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),kn=new iu.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Er={"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}},Cs=class extends au{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Er,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){xn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:_n,httpsAgent:kn}).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 xn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:_n,httpsAgent:kn})).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 a of s.content)a.type==="text"?n.push(a.text??""):a.type==="image"&&a.data&&o.push(a.data);let r={role:"user",content:n.join(`
|
|
34
|
+
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||16384,c=await xn.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:a}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:_n,httpsAgent:kn});return this.normalizeResponse(c.data)}async stream(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||16384,c=n.onToken||(()=>{}),l;try{l=await xn.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:a}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:_n,httpsAgent:kn})}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(`
|
|
35
|
+
`);h=g.pop()||"";for(let w of g){if(!w.trim())continue;let $;try{$=JSON.parse(w)}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||{}}}))}};Cr.exports={OllamaProvider:Cs,OLLAMA_MODELS:Er}});var Pr=N((Fg,Nr)=>{var{callChat:cu}=fe(),{estimateTokens:Ts}=Te(),Rr=process.env.NEX_COMPACTION!=="false",Ar=6,Or=500,lu=`Summarize this conversation history concisely. Focus on:
|
|
36
36
|
- What files were read, created, or modified
|
|
37
37
|
- Key decisions made and their rationale
|
|
38
38
|
- Current state of the task (what's done, what's pending)
|
|
39
39
|
- Any errors encountered and how they were resolved
|
|
40
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
41
|
-
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function
|
|
40
|
+
Be factual and brief. Use bullet points. Max 300 words.`;async function uu(t){if(!Rr||t.length<Ar)return null;let e=[{role:"system",content:lu},{role:"user",content:Mr(t)}];try{let n=((await cu(e,[],{temperature:0,maxTokens:Or})).content||"").trim();if(!n)return null;let o=t.reduce((a,c)=>a+Ts(c.content||"")+(c.tool_calls?Ts(JSON.stringify(c.tool_calls)):0),0),r=Ts(n);return r>=o*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
41
|
+
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function Mr(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(r=>r.function?.name).join(", ");return`[${s}] ${n}
|
|
42
42
|
tools: ${o}`}return`[${s}] ${n}`}).join(`
|
|
43
43
|
|
|
44
|
-
`)}
|
|
44
|
+
`)}Nr.exports={compactMessages:uu,formatMessagesForSummary:Mr,COMPACTION_ENABLED:Rr,COMPACTION_MIN_MESSAGES:Ar,COMPACTION_SUMMARY_BUDGET:Or}});var Te=N((Ug,Br)=>{function qr(){return fe().getActiveModel()}var du={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},Dt=new Map,Lr=1e3,vn=new WeakMap,wt=new Map,Ir=500,Ft=null;function fu(){if(Ft!==null)return Ft;try{let e=qr()?.provider||"ollama";return Ft=du[e]||4,Ft}catch{return 4}}function mu(){Ft=null}function ot(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=Dt.get(e);if(s!==void 0)return s;let n=Math.ceil(t.length/fu());if(Dt.size>=Lr){let o=Lr>>1,r=Dt.keys();for(let a=0;a<o;a++)Dt.delete(r.next().value)}return Dt.set(e,n),n}function pu(t){if(vn.has(t))return vn.get(t);let e=jr(t);if(wt.has(e)){let n=wt.get(e);return vn.set(t,n),n}let s=JSON.stringify(t);if(wt.size>=Ir){let n=Ir>>1,o=wt.keys();for(let r=0;r<n;r++)wt.delete(o.next().value)}return wt.set(e,s),vn.set(t,s),s}function jr(t){let e=t.role||"",s=typeof t.content=="string"?t.content.substring(0,100):"",n=t.tool_calls?t.tool_calls.length:0;return`${e}:${s.length}:${n}`}function bt(t){let s=4;if(t.content&&(s+=ot(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=ot(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=ot(o):o&&(s+=ot(JSON.stringify(o)))}return s}function Re(t){let e=0;for(let s of t)e+=bt(s);return e}function hu(t,e){if(t&&t.length===e.length){let r=!1;for(let a=0;a<e.length;a++)if(t[a]!==e[a]){r=!0;break}if(!r)return 0}let s=t?t.length:0,n=e.length,o=0;for(let r=s;r<n;r++)o+=bt(e[r]);return o}function Sn(t){return!t||t.length===0?0:ot(JSON.stringify(t))}function En(){return qr()?.contextWindow||32768}function gu(t,e){let s=Re(t),n=Sn(e),o=s+n,r=En(),a=r>0?o/r*100:0,c=0,l=0,u=0;for(let d of t){let f=bt(d);d.role==="system"?c+=f:d.role==="tool"?u+=f:l+=f}return{used:o,limit:r,percentage:Math.round(a*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:n},messageCount:t.length}}var Dr=.75,Fr=.1,Ur=10,$u=200,yu=500;function Wr(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(`
|
|
45
45
|
`);if(o.length<=10){let p=Math.floor(n*.6),g=Math.floor(n*.4),w=t.substring(0,p),$=t.substring(t.length-g);return w+`
|
|
46
46
|
...(${t.length} chars total)...
|
|
47
47
|
`+$}let r=Math.floor(o.length*.4),a=Math.floor(o.length*.4),c=[],l=0,u=Math.floor(n*.4);for(let p=0;p<r&&l<u;p++)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-a&&f<m;p--)d.unshift(o[p]),f+=o[p].length+1;let h=o.length-c.length-d.length;return c.join(`
|
|
48
48
|
`)+`
|
|
49
49
|
...(${h} lines omitted, ${o.length} total)...
|
|
50
50
|
`+d.join(`
|
|
51
|
-
`)}function Ut(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:
|
|
52
|
-
...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),o}return t}async function
|
|
51
|
+
`)}function Ut(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:yu,n=e==="aggressive"?50:e==="medium"?100:$u;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:Wr(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
|
|
52
|
+
...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),o}return t}async function wu(t,e,s={}){let n=s.threshold??Dr,o=s.safetyMargin??Fr,r=s.keepRecent??Ur,a=En(),c=Sn(e),l=Math.floor(a*(n-o)),u=l-c,d=Re(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-r),w=t.slice(p,g),$=t.slice(g),x=w.filter(v=>!v._compacted);if(x.length>=6)try{let{compactMessages:v}=Pr(),T=await v(x);if(T){let q=[...w.filter(Y=>Y._compacted),T.message],Q=st(h,q,$),j=Re(Q);if(j+c<=l)return{messages:Q,compressed:!0,compacted:!0,tokensRemoved:m-j};w=q}}catch(v){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",v.message)}let O=(f-l)/l,_=w.map(v=>Ut(v,"light")),k=st(h,_,$),C=Re(k);if(C+c<=l)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-C};if(_=w.map(v=>Ut(v,"medium")),k=st(h,_,$),C=Re(k),C+c<=l)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-C};if(_=w.map(v=>Ut(v,"aggressive")),k=st(h,_,$),C=Re(k),C+c<=l)return{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-C};for(;_.length>0&&C+c>u;){let v=_.shift();C-=bt(v)}return k=st(h,_,$),C=Re(k),{messages:k,compressed:!0,compacted:!1,tokensRemoved:m-C}}function st(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function bu(t,e){if(!t)return"";if(ot(t)<=e)return t;let n=e*4,o=t.split(`
|
|
53
53
|
`),r=Math.floor(n*.6),a=Math.floor(n*.4),c="",l=0;for(let h of o){if(c.length+h.length+1>r)break;c+=(c?`
|
|
54
54
|
`:"")+h,l++}let u="",d=0;for(let h=o.length-1;h>=l;h--){let p=o[h]+(u?`
|
|
55
55
|
`:"")+u;if(p.length>a)break;u=p,d++}let m=`
|
|
56
56
|
|
|
57
57
|
... (${o.length-l-d} lines omitted, ${o.length} total) ...
|
|
58
58
|
|
|
59
|
-
`;return c+m+u}var
|
|
60
|
-
`);g=$.pop()||"";for(let x of $){let
|
|
61
|
-
|
|
62
|
-
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let a=this._getMessageCacheKey(o);this._messageStringCache.set(a,r),this._messageFormatCache.set(o,r)}n.push(r)}}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,r=this._resolveModelId(o),a=this.getModel(o),c=n.maxTokens||a?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:r,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
|
|
63
|
-
`);
|
|
64
|
-
`);g=$.pop()||"";for(let x of $){let
|
|
65
|
-
`)};return o.length>0&&(r.images=o),r}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 r=await
|
|
66
|
-
`);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let g;try{g=JSON.parse(p)}catch{continue}if(g.message?.content&&(r(g.message.content),u+=g.message.content),g.message?.tool_calls&&(d=d.concat(g.message.tool_calls)),g.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),a.data.on("error",m=>{n.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),a.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(r(m.message.content),u+=m.message.content),m.message?.tool_calls&&(d=d.concat(m.message.tool_calls))}catch{}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||{}}}))}};
|
|
67
|
-
`)}}function
|
|
68
|
-
`)}function
|
|
69
|
-
`),c}catch(c){throw o.stop(),c}}async function
|
|
59
|
+
`;return c+m+u}var xu=6;function _u(t,e){let s=En(),n=Sn(e),o=Math.floor(s*.5)-n,r=Re(t),a=null,c=0;t.length>0&&t[0].role==="system"&&(a=t[0],c=1);let l=Math.max(c,t.length-xu),u=t.slice(c,l),d=t.slice(l),f=u.map(p=>Ut(p,"aggressive")),m=st(a,f,d),h=Re(m);for(;f.length>0&&h>o;){let p=f.shift();h-=bt(p)}return m=st(a,f,d),h=Re(m),{messages:m,tokensRemoved:r-h}}Br.exports={estimateTokens:ot,estimateMessageTokens:bt,estimateMessagesTokens:Re,estimateDeltaTokens:hu,estimateToolsTokens:Sn,serializeMessage:pu,getMessageCacheKey:jr,getContextWindow:En,getUsage:gu,compressMessage:Ut,compressToolResult:Wr,fitToContext:wu,forceCompress:_u,truncateFileContent:bu,invalidateTokenRatioCache:mu,COMPRESSION_THRESHOLD:Dr,SAFETY_MARGIN:Fr,KEEP_RECENT:Ur}});var Kr=N((Bg,zr)=>{var Hr=require("axios"),{BaseProvider:ku}=yt(),{serializeMessage:Wg}=Te(),Gr={"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}},Rs=class extends ku{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Gr,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 a=this._messageStringCache.get(o);this._messageFormatCache.set(n,a),s.push(a);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}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,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||16384,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:a,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await Hr.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,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||16384,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:a,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await Hr.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",w=>{g+=w.toString();let $=g.split(`
|
|
60
|
+
`);g=$.pop()||"";for(let x of $){let O=x.trim();if(!O||!O.startsWith("data: "))continue;let _=O.slice(6);if(_==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let k;try{k=JSON.parse(_)}catch{continue}let C=k.choices?.[0]?.delta;if(C&&(C.content&&(c(C.content),h+=C.content),C.tool_calls))for(let v of C.tool_calls){let T=v.index??0;p[T]||(p[T]={id:v.id||"",name:"",arguments:""}),v.id&&(p[T].id=v.id),v.function?.name&&(p[T].name+=v.function.name),v.function?.arguments&&(p[T].arguments+=v.function.arguments)}}}),d.data.on("error",w=>{n.signal?.aborted||m(new Error(`Stream error: ${w.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}}))}};zr.exports={OpenAIProvider:Rs,OPENAI_MODELS:Gr}});var Vr=N((Gg,Xr)=>{var Jr=require("axios"),{BaseProvider:vu}=yt(),{serializeMessage:Hg}=Te(),Yr={"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}},Su="2023-06-01",As=class extends vu{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Yr,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Su}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?`
|
|
61
|
+
|
|
62
|
+
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let a=this._getMessageCacheKey(o);this._messageStringCache.set(a,r),this._messageFormatCache.set(o,r)}n.push(r)}}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,r=this._resolveModelId(o),a=this.getModel(o),c=n.maxTokens||a?.maxTokens||8192,{messages:l,system:u}=this.formatMessages(e),d={model:r,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 Jr.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,r=this._resolveModelId(o),a=this.getModel(o),c=n.maxTokens||a?.maxTokens||8192,l=n.onToken||(()=>{}),{messages:u,system:d}=this.formatMessages(e),f={model:r,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 Jr.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 w="",$=[],x=-1,O="";n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",_=>{O+=_.toString();let k=O.split(`
|
|
63
|
+
`);O=k.pop()||"";for(let C of k){let v=C.trim();if(v.startsWith("data: ")){let T=v.slice(6),F;try{F=JSON.parse(T)}catch{continue}switch(F.type){case"content_block_start":{let q=F.content_block;q?.type==="tool_use"&&(x=$.length,$.push({id:q.id,name:q.name,inputJson:""}));break}case"content_block_delta":{let q=F.delta;q?.type==="text_delta"&&q.text&&(l(q.text),w+=q.text),q?.type==="input_json_delta"&&q.partial_json!==void 0&&x>=0&&($[x].inputJson+=q.partial_json);break}case"content_block_stop":x=-1;break;case"message_stop":p({content:w,tool_calls:this._buildToolCalls($)});return}}}}),h.data.on("error",_=>{n.signal?.aborted||g(new Error(`Stream error: ${_.message}`))}),h.data.on("end",()=>{p({content:w,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}}})}};Xr.exports={AnthropicProvider:As,ANTHROPIC_MODELS:Yr}});var ti=N((Kg,ei)=>{var Qr=require("axios"),{BaseProvider:Eu}=yt(),{serializeMessage:zg}=Te(),Zr={"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}},Os=class extends Eu{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Zr,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 a=this._messageStringCache.get(o);this._messageFormatCache.set(n,a),s.push(a);continue}let r=this._formatSingleMessage(n);this._messageStringCache.size<this._maxCacheSize&&this._messageStringCache.set(o,r),this._messageFormatCache.set(n,r),s.push(r)}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,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:a,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await Qr.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,r=this.getModel(o),a=n.maxTokens||r?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:a,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await Qr.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",w=>{g+=w.toString();let $=g.split(`
|
|
64
|
+
`);g=$.pop()||"";for(let x of $){let O=x.trim();if(!O||!O.startsWith("data: "))continue;let _=O.slice(6);if(_==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let k;try{k=JSON.parse(_)}catch{continue}let C=k.choices?.[0]?.delta;if(C&&(C.content&&(c(C.content),h+=C.content),C.tool_calls))for(let v of C.tool_calls){let T=v.index??0;p[T]||(p[T]={id:v.id||"",name:"",arguments:""}),v.id&&(p[T].id=v.id),v.function?.name&&(p[T].name+=v.function.name),v.function?.arguments&&(p[T].arguments+=v.function.arguments)}}}),d.data.on("error",w=>{n.signal?.aborted||m(new Error(`Stream error: ${w.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}}))}};ei.exports={GeminiProvider:Os,GEMINI_MODELS:Zr}});var oi=N((Jg,si)=>{var Cn=require("axios"),{BaseProvider:Cu}=yt(),ni="http://localhost:11434",Ms=class extends Cu{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||ni,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 Cn.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 r=o.replace(/:latest$/,""),a=32768;try{let c=await Cn.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=c.data?.model_info||c.data?.details||{};a=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(c.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(a*.1)),contextWindow:a}}!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 a of s.content)a.type==="text"?n.push(a.text??""):a.type==="image"&&a.data&&o.push(a.data);let r={role:"user",content:n.join(`
|
|
65
|
+
`)};return o.length>0&&(r.images=o),r}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 r=await Cn.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(r.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 r=n.onToken||(()=>{}),a;try{a=await Cn.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",()=>{a.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),a.data.on("data",m=>{f+=m.toString();let h=f.split(`
|
|
66
|
+
`);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let g;try{g=JSON.parse(p)}catch{continue}if(g.message?.content&&(r(g.message.content),u+=g.message.content),g.message?.tool_calls&&(d=d.concat(g.message.tool_calls)),g.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),a.data.on("error",m=>{n.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),a.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(r(m.message.content),u+=m.message.content),m.message?.tool_calls&&(d=d.concat(m.message.tool_calls))}catch{}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||{}}}))}};si.exports={LocalProvider:Ms,DEFAULT_LOCAL_URL:ni}});var xt=N((Yg,di)=>{var rt=require("fs"),Ns=require("path"),ri={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:{}},Tn=[],Je={};function Tu(t,e,s,n){if(Tn.push({provider:t,model:e,input:s,output:n}),Je[t]!==void 0){let o=li(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
|
|
67
|
+
`)}}function Ps(t,e){let s=ri[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function ii(t){let e=Ps(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function ai(){let t={};for(let r of Tn){let a=`${r.provider}:${r.model}`;t[a]||(t[a]={provider:r.provider,model:r.model,input:0,output:0}),t[a].input+=r.input,t[a].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:ii(r)})),s=e.reduce((r,a)=>r+a.cost,0),n=e.reduce((r,a)=>r+a.input,0),o=e.reduce((r,a)=>r+a.output,0);return{totalCost:s,totalInput:n,totalOutput:o,breakdown:e}}function Ru(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=ai();if(n.length===0)return"No token usage recorded this session.";let o=[];o.push("Session Token Usage:"),o.push("");for(let r of n){let a=r.cost>0?`$${r.cost.toFixed(4)}`:"free";o.push(` ${r.provider}:${r.model}`),o.push(` Input: ${r.input.toLocaleString()} tokens`),o.push(` Output: ${r.output.toLocaleString()} tokens`),o.push(` Cost: ${a}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
|
|
68
|
+
`)}function Au(t,e,s,n){let o=Ps(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Ou(){Tn=[]}function Mu(t,e){Je[t]=e}function Nu(t){delete Je[t]}function Pu(){return{...Je}}function ci(t){let e=0;for(let s of Tn)s.provider===t&&(e+=ii(s));return e}function li(t){let e=ci(t),s=Je[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 ui(){let t=Ns.join(process.cwd(),".nex","config.json");if(rt.existsSync(t))try{let e=JSON.parse(rt.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Je={...e.costLimits})}catch{}}function Lu(){let t=Ns.join(process.cwd(),".nex"),e=Ns.join(t,"config.json"),s={};if(rt.existsSync(e))try{s=JSON.parse(rt.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Je,rt.existsSync(t)||rt.mkdirSync(t,{recursive:!0}),rt.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function Iu(){Je={}}ui();di.exports={PRICING:ri,trackUsage:Tu,getSessionCosts:ai,formatCosts:Ru,formatCostHint:Au,resetCosts:Ou,getPricing:Ps,setCostLimit:Mu,removeCostLimit:Nu,getCostLimits:Pu,getProviderSpend:ci,checkBudget:li,loadCostLimits:ui,saveCostLimits:Lu,resetCostLimits:Iu}});var Rn=N((Xg,fi)=>{var Wt=fe(),qu={"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 Wt.getActiveModel()}function Du(t){return Wt.setActiveModel(t)}function Fu(){return Wt.getModelNames()}function Uu(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 Wu(t,e){let{C:s}=oe(),{Spinner:n}=oe(),o=new n("Thinking...");o.start();let r=!0,a="";try{let c=await Wt.callStream(t,e,{onToken:l=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(l),a+=l}});return r?o.stop():process.stdout.write(`${s.reset}
|
|
69
|
+
`),c}catch(c){throw o.stop(),c}}async function Bu(t,e){return Wt.callChat(t,e)}fi.exports={MODELS:qu,getActiveModel:ju,setActiveModel:Du,getModelNames:Fu,callOllamaStream:Wu,callOllama:Bu,parseToolArgs:Uu}});var hi=N((Vg,pi)=>{var An=require("path"),{C:b}=oe(),{confirm:Hu,getAutoConfirm:Gu}=Oe(),mi=2e3;function Bt(t,e){let s=t.split(`
|
|
70
70
|
`),n=e.split(`
|
|
71
|
-
`),o=[],r=s.length,a=n.length;if(r>
|
|
72
|
-
${b.bold}${b.cyan} Diff: ${t}${b.reset}`);let o=Bt(e,s),r=[];if(o.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${b.gray} (no changes)${b.reset}`);return}let a=Math.max(0,r[0]-n),c=Math.min(o.length,r[r.length-1]+n+1);a>0&&console.log(`${b.gray} ...${b.reset}`);for(let l=a;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
|
|
73
|
-
${b.bold}${b.cyan} File exists \u2014 showing changes: ${t}${b.reset}`);let n=Bt(e,s),o=0;for(let a of n)a.type!=="same"&&o++;if(o===0){console.log(`${b.gray} (identical content)${b.reset}`);return}let r=0;for(let a of n){if(r>=30){console.log(`${b.gray} ...(${o-r} more changes)${b.reset}`);break}switch(a.type){case"remove":console.log(`${b.red} - ${a.line}${b.reset}`),r++;break;case"add":console.log(`${b.green} + ${a.line}${b.reset}`),r++;break;default:r>0&&console.log(`${b.gray} ${a.line}${b.reset}`)}}console.log()}function
|
|
71
|
+
`),o=[],r=s.length,a=n.length;if(r>mi||a>mi){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:r+1},()=>new Array(a+1).fill(0));for(let f=1;f<=r;f++)for(let m=1;m<=a;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=r,u=a,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 zu(t,e,s,n=3){console.log(`
|
|
72
|
+
${b.bold}${b.cyan} Diff: ${t}${b.reset}`);let o=Bt(e,s),r=[];if(o.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${b.gray} (no changes)${b.reset}`);return}let a=Math.max(0,r[0]-n),c=Math.min(o.length,r[r.length-1]+n+1);a>0&&console.log(`${b.gray} ...${b.reset}`);for(let l=a;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 Ku(t,e,s){console.log(`
|
|
73
|
+
${b.bold}${b.cyan} File exists \u2014 showing changes: ${t}${b.reset}`);let n=Bt(e,s),o=0;for(let a of n)a.type!=="same"&&o++;if(o===0){console.log(`${b.gray} (identical content)${b.reset}`);return}let r=0;for(let a of n){if(r>=30){console.log(`${b.gray} ...(${o-r} more changes)${b.reset}`);break}switch(a.type){case"remove":console.log(`${b.red} - ${a.line}${b.reset}`),r++;break;case"add":console.log(`${b.green} + ${a.line}${b.reset}`),r++;break;default:r>0&&console.log(`${b.gray} ${a.line}${b.reset}`)}}console.log()}function Ju(t,e){console.log(`
|
|
74
74
|
${b.bold}${b.cyan} New file: ${t}${b.reset}`);let s=e.split(`
|
|
75
|
-
`),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
|
|
75
|
+
`),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 Yu(t){return Gu()?!0:Hu(` ${t}?`)}function Xu(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
|
|
76
76
|
${b.bold}${b.cyan} Side-by-side: ${t}${b.reset}`),console.log(` ${b.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${b.reset}`);let a=Bt(e,s),c=[],l=0;for(;l<a.length;)if(a[l].type==="same")c.push({left:a[l].line,right:a[l].line,type:"same"}),l++;else if(a[l].type==="remove"){let h=[];for(;l<a.length&&a[l].type==="remove";)h.push(a[l].line),l++;let p=[];for(;l<a.length&&a[l].type==="add";)p.push(a[l].line),l++;let g=Math.max(h.length,p.length);for(let w=0;w<g;w++)c.push({left:w<h.length?h[w]:"",right:w<p.length?p[w]:"",type:"changed"})}else a[l].type==="add"&&(c.push({left:"",right:a[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(r)}\u250A${"\xB7".repeat(r)}${b.reset}`);for(let h=d;h<f;h++){let p=c[h];if(p.type==="same")console.log(` ${b.gray}${m(p.left,r)}${b.reset}\u2502${b.gray}${m(p.right,r)}${b.reset}`);else{let g=p.left?`${b.red}${m(p.left,r)}${b.reset}`:`${m("",r)}`,w=p.right?`${b.green}${m(p.right,r)}${b.reset}`:`${m("",r)}`;console.log(` ${g}\u2502${w}`)}}f<c.length&&console.log(` ${b.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${b.reset}`),console.log(` ${b.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${b.reset}
|
|
77
|
-
`)}function
|
|
77
|
+
`)}function Vu(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,a=n.annotations||[],c=An.isAbsolute(t)?An.relative(process.cwd(),t):t,l=Bt(e,s),u=1,d=1;for(let _ of l)_.type==="same"?(_.oldLine=u++,_.newLine=d++):_.type==="remove"?(_.oldLine=u++,_.newLine=null):(_.oldLine=null,_.newLine=d++);let f=0,m=0;for(let _ of l)_.type==="add"?f++:_.type==="remove"&&m++;if(console.log(`
|
|
78
78
|
${b.cyan}\u23FA${b.reset} ${b.bold}${o}(${c})${b.reset}`),f===0&&m===0){console.log(` ${b.dim}\u23BF (no changes)${b.reset}
|
|
79
|
-
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),a.length>0){let _=a.filter(
|
|
79
|
+
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),a.length>0){let _=a.filter(T=>T.severity==="error").length,k=a.filter(T=>T.severity==="warn").length,C=a.filter(T=>T.severity==="info").length,v=[];_>0&&v.push(`${b.red}${_} error${_!==1?"s":""}${b.dim}`),k>0&&v.push(`${b.yellow}${k} warning${k!==1?"s":""}${b.dim}`),C>0&&v.push(`${b.cyan}${C} info${C!==1?"s":""}${b.dim}`),h.push(`found ${v.join(", ")}`)}console.log(` ${b.dim}\u23BF ${h.join(", ")}${b.reset}`);let g=[];l.forEach((_,k)=>{_.type!=="same"&&g.push(k)});let w=[],$=null,x=null;for(let _ of g){let k=Math.max(0,_-r),C=Math.min(l.length-1,_+r);$===null?($=k,x=C):(k<=x+1||(w.push([$,x]),$=k),x=C)}$!==null&&w.push([$,x]);let O=" ";for(let _=0;_<w.length;_++){_>0&&console.log(`${O}${b.dim}\xB7\xB7\xB7${b.reset}`);let[k,C]=w[_];for(let v=k;v<=C;v++){let T=l[v],F=T.newLine!=null?T.newLine:T.oldLine,q=String(F).padStart(4),Q=T.type!=="remove"?a.filter(j=>j.line===T.newLine):[];T.type==="remove"?console.log(`${O}${b.red}${q} -${T.line}${b.reset}`):T.type==="add"?console.log(`${O}${b.green}${q} +${T.line}${b.reset}`):console.log(`${O}${b.dim}${q}${b.reset} ${T.line}`);for(let j of Q){let Y=b.cyan,qe="\u2139";j.severity==="error"?(Y=b.red,qe="\u2716"):j.severity==="warn"&&(Y=b.yellow,qe="\u26A0"),console.log(`${O} ${Y}${qe} ${j.message}${b.reset}`)}}}console.log()}function Qu(t,e,s={}){let n=An.isAbsolute(t)?An.relative(process.cwd(),t):t,o=e.split(`
|
|
80
80
|
`),r=s.annotations||[];console.log(`
|
|
81
|
-
${b.cyan}\u23FA${b.reset} ${b.bold}Create(${n})${b.reset}`);let a=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(p=>p.severity==="error").length,f=r.filter(p=>p.severity==="warn").length,m=r.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}`),a.push(`found ${h.join(", ")}`)}console.log(` ${b.dim}\u23BF ${a.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=r.filter(p=>p.line===m);console.log(`${l}${b.green}${f} +${o[d]}${b.reset}`);for(let p of h){let g=b.cyan,w="\u2139";p.severity==="error"?(g=b.red,w="\u2716"):p.severity==="warn"&&(g=b.yellow,w="\u26A0"),console.log(`${l} ${g}${w} ${p.message}${b.reset}`)}}o.length>20&&console.log(`${l}${b.dim} ...+${o.length-20} more lines${b.reset}`),console.log()}
|
|
82
|
-
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function
|
|
83
|
-
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&r++}else o=t.length;let a="chore",c=t.join(" ").toLowerCase();c.includes("test")?a="test":c.includes("readme")||c.includes("doc")?a="docs":o>r*2?a="feat":r>o?a="refactor":a="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${a}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:a,files:t,stats:{additions:o,deletions:r}}}async function
|
|
84
|
-
${
|
|
85
|
-
${
|
|
86
|
-
${
|
|
81
|
+
${b.cyan}\u23FA${b.reset} ${b.bold}Create(${n})${b.reset}`);let a=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(p=>p.severity==="error").length,f=r.filter(p=>p.severity==="warn").length,m=r.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}`),a.push(`found ${h.join(", ")}`)}console.log(` ${b.dim}\u23BF ${a.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=r.filter(p=>p.line===m);console.log(`${l}${b.green}${f} +${o[d]}${b.reset}`);for(let p of h){let g=b.cyan,w="\u2139";p.severity==="error"?(g=b.red,w="\u2716"):p.severity==="warn"&&(g=b.yellow,w="\u26A0"),console.log(`${l} ${g}${w} ${p.message}${b.reset}`)}}o.length>20&&console.log(`${l}${b.dim} ...+${o.length-20} more lines${b.reset}`),console.log()}pi.exports={diffLines:Bt,showEditDiff:zu,showWriteDiff:Ku,showNewFilePreview:Ju,confirmFileChange:Yu,showSideBySideDiff:Xu,showClaudeDiff:Vu,showClaudeNewFile:Qu}});var it=N((Qg,yi)=>{var gi=require("util").promisify(require("child_process").exec),Zu=require("util").promisify(require("child_process").execFile),{C:Z}=oe();async function Ls(t){try{let{stdout:e}=await gi(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function On(...t){try{let{stdout:e}=await Zu("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function ed(){return await Ls("git rev-parse --is-inside-work-tree")==="true"}async function td(){return await Ls("git branch --show-current")}async function Is(){try{let{stdout:t}=await gi("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
82
|
+
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function Mn(t=!1){return await Ls(`git diff ${t?"--cached":""}`)||""}async function qs(){return(await Is()).map(e=>e.file)}async function $i(){let t=await qs();if(t.length===0)return null;let e=await Mn(),n=await Mn(!0)||e,o=0,r=0;if(n){let d=n.split(`
|
|
83
|
+
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&r++}else o=t.length;let a="chore",c=t.join(" ").toLowerCase();c.includes("test")?a="test":c.includes("readme")||c.includes("doc")?a="docs":o>r*2?a="feat":r>o?a="refactor":a="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${a}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:a,files:t,stats:{additions:o,deletions:r}}}async function nd(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await On("checkout","-b",s)!==null?s:null}async function sd(t){return await On("add","-A"),await On("commit","-m",t)?await On("rev-parse","--short","HEAD"):null}async function od(){let t=await $i();if(!t)return`${Z.dim}No changes${Z.reset}`;let e=[];e.push(`
|
|
84
|
+
${Z.bold}${Z.cyan}Git Diff Summary:${Z.reset}`),e.push(` ${Z.green}+${t.stats.additions}${Z.reset} ${Z.red}-${t.stats.deletions}${Z.reset} in ${t.files.length} file(s)`),e.push(`
|
|
85
|
+
${Z.bold}${Z.cyan}Files:${Z.reset}`);for(let s of t.files.slice(0,20))e.push(` ${Z.dim}${s}${Z.reset}`);return t.files.length>20&&e.push(` ${Z.dim}...+${t.files.length-20} more${Z.reset}`),e.push(`
|
|
86
|
+
${Z.bold}${Z.cyan}Suggested message:${Z.reset}`),e.push(` ${Z.cyan}${t.summary}${Z.reset}
|
|
87
87
|
`),e.join(`
|
|
88
|
-
`)}async function
|
|
88
|
+
`)}async function rd(){return(await Is()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function id(){let t=await qs();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 Mn();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
|
|
89
89
|
...(truncated)`:s;e.push(`
|
|
90
90
|
DIFF:
|
|
91
91
|
${n}`)}return e.join(`
|
|
92
|
-
`)}
|
|
92
|
+
`)}yi.exports={isGitRepo:ed,getCurrentBranch:td,getStatus:Is,getDiff:Mn,getChangedFiles:qs,analyzeDiff:$i,createBranch:nd,commit:sd,formatDiffSummary:od,getDiffContext:id,getMergeConflicts:rd}});var kt=N((Zg,wi)=>{var js=require("fs").promises,ad=50,je=[],_t=[];function cd(t,e,s,n){for(je.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});je.length>ad;)je.shift();_t.length=0}async function ld(){if(je.length===0)return null;let t=je.pop();if(t.oldContent===null)try{await js.unlink(t.filePath)}catch{}else await js.writeFile(t.filePath,t.oldContent,"utf-8");return _t.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function ud(){if(_t.length===0)return null;let t=_t.pop();return await js.writeFile(t.filePath,t.newContent,"utf-8"),je.push(t),{tool:t.tool,filePath:t.filePath}}function dd(t=10){return je.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function fd(){return je.length}function md(){return _t.length}function pd(){je.length=0,_t.length=0}wi.exports={recordChange:cd,undo:ld,redo:ud,getHistory:dd,getUndoCount:fd,getRedoCount:md,clearHistory:pd}});var Ht=N((e$,Si)=>{var xe=require("fs"),vt=require("path"),$e=[];function Ds(){return vt.join(process.cwd(),".nex","skills")}function bi(){return vt.join(process.cwd(),".nex","config.json")}function hd(){let t=Ds();return xe.existsSync(t)||xe.mkdirSync(t,{recursive:!0}),t}function Fs(){let t=bi();if(!xe.existsSync(t))return[];try{let e=JSON.parse(xe.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function xi(t){let e=bi(),s={};if(xe.existsSync(e))try{s=JSON.parse(xe.readFileSync(e,"utf-8"))}catch{s={}}s.skills||(s.skills={}),s.skills.disabled=t;let n=vt.dirname(e);xe.existsSync(n)||xe.mkdirSync(n,{recursive:!0}),xe.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function _i(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 ki(t){try{let e=xe.readFileSync(t,"utf-8").trim();return e?{name:vt.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function vi(t){try{let e=require(t),{valid:s,errors:n}=_i(e,t);return s?{name:e.name||vt.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(r=>({cmd:r.cmd.startsWith("/")?r.cmd:`/${r.cmd}`,desc:r.desc||r.description||"",handler:r.handler||null})),tools:(e.tools||[]).map(r=>({type:r.type||"function",function:{name:r.function.name,description:r.function.description||"",parameters:r.function.parameters||{type:"object",properties:{}}},execute:r.execute||null}))}:(console.error(`Skill validation failed: ${t}
|
|
93
93
|
${n.join(`
|
|
94
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
94
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function gd(){$e=[];let t=Ds();if(!xe.existsSync(t))return $e;let e=Fs(),s;try{s=xe.readdirSync(t)}catch{return $e}for(let n of s){let o=vt.join(t,n),r;try{r=xe.statSync(o)}catch{continue}if(!r.isFile())continue;let a=null;n.endsWith(".md")?a=ki(o):n.endsWith(".js")&&(a=vi(o)),a&&(a.enabled=!e.includes(a.name),$e.push(a))}return $e}function $d(){let t=[];for(let e of $e)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
95
95
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
96
96
|
${t.join(`
|
|
97
97
|
|
|
98
|
-
`)}`}function
|
|
98
|
+
`)}`}function yd(){let t=[];for(let e of $e)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function wd(){let t=[];for(let e of $e)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 bd(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of $e)if(n.enabled){for(let o of n.tools)if(o.function.name===s&&o.execute)try{let r=await o.execute(e);return typeof r=="string"?r:JSON.stringify(r)}catch(r){return`ERROR: Skill tool '${s}' failed: ${r.message}`}}return`ERROR: Skill tool '${s}' not found`}function xd(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of $e)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{r.handler(n)}catch(a){console.error(`Skill command error (${e}): ${a.message}`)}return!0}}return!1}function _d(){return $e.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 kd(t){let e=$e.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Fs().filter(n=>n!==t);return xi(s),!0}function vd(t){let e=$e.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Fs();return s.includes(t)||(s.push(t),xi(s)),!0}function Sd(){return $e}Si.exports={initSkillsDir:hd,loadAllSkills:gd,getSkillInstructions:$d,getSkillCommands:yd,getSkillToolDefinitions:wd,routeSkillCall:bd,handleSkillCommand:xd,listSkills:_d,enableSkill:kd,disableSkill:vd,getLoadedSkills:Sd,_getSkillsDir:Ds,_validateScriptSkill:_i,_loadMarkdownSkill:ki,_loadScriptSkill:vi}});var Pn=N((t$,Oi)=>{var{spawn:Ed}=require("child_process"),Cd=require("path"),Ei=require("fs"),De=new Map;function Td(){return Cd.join(process.cwd(),".nex","config.json")}function Us(){let t=Td();if(!Ei.existsSync(t))return{};try{return JSON.parse(Ei.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Nn(t,e,s={},n=1e4){return new Promise((o,r)=>{let a=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:a,method:e,params:s})+`
|
|
99
99
|
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},n);function d(m){l+=m.toString();let h=l.split(`
|
|
100
|
-
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===a){f(),g.error?r(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(),r(new Error(`MCP write failed: ${m.message}`))}})}async function
|
|
101
|
-
`):JSON.stringify(o)}function
|
|
102
|
-
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),a=[],c={...e},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=
|
|
100
|
+
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===a){f(),g.error?r(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(),r(new Error(`MCP write failed: ${m.message}`))}})}async function Ci(t,e){if(De.has(t))return De.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let a of s)process.env[a]&&(n[a]=process.env[a]);let o=Ed(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await Nn(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let a=await Nn(o,"tools/list",{});return r.tools=a&&a.tools||[],De.set(t,r),r}catch(a){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${a.message}`)}}function Ti(t){let e=De.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return De.delete(t),!0}function Rd(){for(let[t]of De)Ti(t)}async function Ri(t,e,s={}){let n=De.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await Nn(n.proc,"tools/call",{name:e,arguments:s});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
101
|
+
`):JSON.stringify(o)}function Ai(){let t=[];for(let[e,s]of De)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 Ad(){return Ai().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Od(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 Ri(n,o,e)}function Md(){let t=Us();return Object.entries(t).map(([e,s])=>{let n=De.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function Nd(){let t=Us(),e=[];for(let[s,n]of Object.entries(t))try{let o=await Ci(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Oi.exports={loadMCPConfig:Us,sendRequest:Nn,connectServer:Ci,disconnectServer:Ti,disconnectAll:Rd,callTool:Ri,getAllTools:Ai,getMCPToolDefinitions:Ad,routeMCPCall:Od,listServers:Md,connectAll:Nd}});var Ws=N((n$,Li)=>{var{getSkillToolDefinitions:Pd}=Ht(),{getMCPToolDefinitions:Ld}=Pn(),Ln=new Map;function Mi(){let{TOOL_DEFINITIONS:t}=Fe();return[...t,...Pd(),...Ld()]}function Ni(t){if(Ln.has(t))return Ln.get(t);let s=Mi().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return Ln.set(t,n),n}function Id(){Ln.clear()}function In(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=Pi(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Pi(t,e){let s=t.length,n=e.length,o=Array.from({length:s+1},()=>Array(n+1).fill(0));for(let r=0;r<=s;r++)o[r][0]=r;for(let r=0;r<=n;r++)o[0][r]=r;for(let r=1;r<=s;r++)for(let a=1;a<=n;a++)o[r][a]=t[r-1]===e[a-1]?o[r-1][a-1]:1+Math.min(o[r-1][a],o[r][a-1],o[r-1][a-1]);return o[s][n]}function qd(t,e){let s=Ni(t);if(s===null){let d=Mi().map(m=>m.function.name),f=In(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
102
|
+
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),a=[],c={...e},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=In(u,r);d&&!o.includes(d)?(c[u]=e[d],delete c[d],l=!0):a.push(`Missing required parameter "${u}" (${s.properties[u]?.description||s.properties[u]?.type||"unknown"})`)}for(let u of r)if(!o.includes(u)){let d=In(u,o);d&&!(d in c)?(c[d]=e[u],delete c[u],l=!0):l||a.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 a.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
|
|
103
103
|
`+a.map(u=>` - ${u}`).join(`
|
|
104
104
|
`)+`
|
|
105
105
|
|
|
106
|
-
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}
|
|
106
|
+
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}Li.exports={validateToolArgs:qd,closestMatch:In,levenshtein:Pi,getCachedSchema:Ni,clearSchemaCache:Id}});var Di=N((s$,ji)=>{var{levenshtein:qn}=Ws(),jd=200,Dd=.3,Fd=2;function Bs(t){return t.replace(/\r\n/g,`
|
|
107
107
|
`).replace(/\r/g,`
|
|
108
|
-
`).replace(/\t/g," ".repeat(
|
|
108
|
+
`).replace(/\t/g," ".repeat(Fd)).split(`
|
|
109
109
|
`).map(e=>{let s=e.replace(/\s+$/,""),n=s.match(/^(\s*)(.*)/);if(!n)return s;let[,o,r]=n;return o+r.replace(/ {2,}/g," ")}).join(`
|
|
110
|
-
`)}function
|
|
110
|
+
`)}function Ud(t,e){if(t.includes(e))return e;let s=Bs(t),n=Bs(e);if(!s.includes(n))return null;let o=t.split(`
|
|
111
111
|
`),r=s.split(`
|
|
112
112
|
`),a=n.split(`
|
|
113
113
|
`),c=a[0],l=a[a.length-1];for(let u=0;u<=r.length-a.length;u++){let d=!0;for(let f=0;f<a.length;f++)if(r[u+f]!==a[f]){d=!1;break}if(d)return o.slice(u,u+a.length).join(`
|
|
114
|
-
`)}if(a.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(n)!==-1)return o[u]}return null}function
|
|
114
|
+
`)}if(a.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(n)!==-1)return o[u]}return null}function Wd(t,e){if(!t||!e)return null;let s=t.split(`
|
|
115
115
|
`),o=e.split(`
|
|
116
|
-
`).length;return s.length===0||o===0?null:o===1?
|
|
117
|
-
`),u=qn(l,e);u<a&&(a=u,r={text:l,distance:u,line:c+1})}return r&&o>1&&(r=
|
|
118
|
-
`),h=qn(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}
|
|
119
|
-
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let a=s[r],c=r+1;for(let l of
|
|
120
|
-
`).filter(Boolean),
|
|
116
|
+
`).length;return s.length===0||o===0?null:o===1?Bd(s,e):Gd(s,e,o)}function Ii(t){return Math.max(1,Math.floor(t/jd))}function qi(t,e){return t<=Math.ceil(e*Dd)}function Bd(t,e){let s=e.trim(),n=Ii(t.length),o=null,r=1/0;for(let a=0;a<t.length;a+=n){let c=t[a];if(!c.trim())continue;let l=qn(c.trim(),s);l<r&&(r=l,o={text:c,distance:l,line:a+1})}return o&&n>1&&(o=Hd(t,s,o,n)||o,r=o.distance),qi(r,e.length)?o:null}function Hd(t,e,s,n){let o=s.line-1,r=Math.max(0,o-n),a=Math.min(t.length-1,o+n),c=s.distance,l=null;for(let u=r;u<=a;u++){let d=t[u];if(!d.trim())continue;let f=qn(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function Gd(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Ii(n),r=null,a=1/0;for(let c=0;c<n;c+=o){let l=t.slice(c,c+s).join(`
|
|
117
|
+
`),u=qn(l,e);u<a&&(a=u,r={text:l,distance:u,line:c+1})}return r&&o>1&&(r=zd(t,e,r,o,s,n)||r,a=r.distance),qi(a,e.length)?r:null}function zd(t,e,s,n,o,r){let a=s.line-1,c=Math.max(0,a-n),l=Math.min(r-1,a+n),u=s.distance,d=null;for(let f=c;f<=l;f++){let m=t.slice(f,f+o).join(`
|
|
118
|
+
`),h=qn(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}ji.exports={normalizeWhitespace:Bs,fuzzyFindText:Ud,findMostSimilar:Wd}});var Ui=N((r$,Fi)=>{var{C:o$}=oe(),Kd=[{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}],Jd=[{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 Yd(t,e){let s=e.split(`
|
|
119
|
+
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let a=s[r],c=r+1;for(let l of Kd)l.regex.test(a)&&n.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of Jd)l.ext&&!l.ext.includes(o)||l.regex.test(a)&&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}Fi.exports={runDiagnostics:Yd}});var zs=N((i$,Hi)=>{var Xd=require("fs").promises,Wi=require("path"),{exec:Vd}=require("util").promisify(require("child_process").exec),St=[],Gs=null,jn=!1,Hs=0,Qd=6e4;function Bi(t){return!(St.length===0||Gs!==t||Date.now()-Hs>Qd)}async function Zd(t){if(!jn&&!Bi(t)){jn=!0,Gs=t;try{try{let{stdout:n}=await Vd("rg --files",{cwd:t,timeout:5e3});St=n.split(`
|
|
120
|
+
`).filter(Boolean),Hs=Date.now(),jn=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await Xd.readdir(n,{withFileTypes:!0})}catch{return}for(let a of r){if(a.name==="node_modules"||a.name===".git"||a.name.startsWith("."))continue;let c=o?`${o}/${a.name}`:a.name;a.isDirectory()?await s(Wi.join(n,a.name),c):e.push(c)}};await s(t,""),St=e,Hs=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{jn=!1}}}function ef(){return St}function tf(){return Gs}function nf(t){return St.filter(e=>Wi.basename(e)===t)}function sf(t){let e=t.toLowerCase();return St.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}Hi.exports={refreshIndex:Zd,getFileIndex:ef,getIndexedCwd:tf,findFileInIndex:nf,searchIndex:sf,isIndexValid:Bi}});var Et=N((a$,Ji)=>{var Dn=require("fs"),Un=require("path"),Ks=require("os"),{execFile:of}=require("child_process"),{promisify:rf}=require("util"),Js=rf(of),af=Un.join(".nex","servers.json"),Fn=Un.join(Ks.tmpdir(),"nex-ssh-sockets");function cf(){return Un.join(process.cwd(),af)}function Gi(){let t=cf();if(!Dn.existsSync(t))return{};try{return JSON.parse(Dn.readFileSync(t,"utf-8"))}catch{return{}}}function lf(t){let e=Gi();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,r]=t.includes("@")?t.split("@"):[void 0,t];return{host:r,user:o}}let 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 uf(){Dn.existsSync(Fn)||Dn.mkdirSync(Fn,{recursive:!0})}function zi(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Ks.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),uf();let s=t.user?`${t.user}@${t.host}`:t.host,n=Un.join(Fn,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function Ki(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,Ks.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function df(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=zi(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:a,stderr:c}=await Js("ssh",[...o,r],{timeout:s,maxBuffer:4194304});return{stdout:a||"",stderr:c||"",exitCode:0}}catch(a){let c=typeof a.code=="number"?a.code:1,l=(a.stderr||a.message||"").toString();return{stdout:(a.stdout||"").toString(),stderr:l,exitCode:c,error:Wn(l,t)}}}async function ff(t,e,s,{timeout:n=12e4}={}){let o=Ki(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:a,stderr:c}=await Js("scp",o,{timeout:n,maxBuffer:1048576});return a||c||`Uploaded ${e} \u2192 ${r}:${s}`}catch(a){let c=(a.stderr||a.message||"").toString();throw new Error(Wn(c,t)||c)}}async function mf(t,e,s,{timeout:n=12e4}={}){let o=Ki(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:a,stderr:c}=await Js("scp",o,{timeout:n,maxBuffer:1048576});return a||c||`Downloaded ${r}:${e} \u2192 ${s}`}catch(a){let c=(a.stderr||a.message||"").toString();throw new Error(Wn(c,t)||c)}}function Wn(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
|
|
121
121
|
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}
|
|
122
122
|
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}
|
|
123
123
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
124
124
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
125
125
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
126
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function
|
|
127
|
-
`,"utf-8")}
|
|
126
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function pf(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}]`:"",r=e.key?` key:${e.key}`:"",a=e.sudo?" sudo:yes":"";return`${t}: ${s}${n}${o}${r}${a}`}Ji.exports={loadServerProfiles:Gi,resolveProfile:lf,buildSSHArgs:zi,sshExec:df,scpUpload:ff,scpDownload:mf,enrichSSHError:Wn,formatProfile:pf,SSH_SOCKET_DIR:Fn}});var Vs=N((c$,Xi)=>{var Gt=require("fs"),Ys=require("path"),hf=Ys.join(".nex","deploy.json");function Xs(){return Ys.join(process.cwd(),hf)}function Yi(){let t=Xs();if(!Gt.existsSync(t))return{};try{return JSON.parse(Gt.readFileSync(t,"utf-8"))}catch{return{}}}function gf(t){let e=Yi();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 $f(t){let e=Ys.join(process.cwd(),".nex");Gt.existsSync(e)||Gt.mkdirSync(e,{recursive:!0}),Gt.writeFileSync(Xs(),JSON.stringify(t,null,2)+`
|
|
127
|
+
`,"utf-8")}Xi.exports={loadDeployConfigs:Yi,resolveDeployConfig:gf,saveDeployConfigs:$f,getDeployConfigPath:Xs}});var Kt=N((l$,Zi)=>{var Qs=null,Ue=null,zt=null,Vi=`Playwright is not installed. Install with:
|
|
128
128
|
npm install playwright && npx playwright install chromium
|
|
129
|
-
Then restart nex-code.`;function
|
|
130
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function
|
|
131
|
-
`)}function
|
|
129
|
+
Then restart nex-code.`;function Qi(){if(zt!==null)return zt;try{require("playwright"),zt=!0}catch{zt=!1}return zt}async function Bn(){if(!Qi())throw new Error(Vi);return Qs||(Qs=require("playwright")),(!Ue||!Ue.isConnected())&&(Ue=await Qs.chromium.launch({headless:!0})),Ue}async function yf(){if(Ue){try{await Ue.close()}catch{}Ue=null}}process.on("exit",()=>{if(Ue)try{Ue.close()}catch{}});async function wf(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await Bn()).newPage();try{await o.goto(t,{waitUntil:s,timeout:e});let r=await o.title(),a=await o.evaluate(()=>(document.querySelectorAll("script,style,nav,footer,header,aside,[role=navigation]").forEach(u=>u.remove()),document.body?.innerText||"")),c=await o.evaluate(()=>Array.from(document.querySelectorAll("a[href]")).slice(0,30).map(l=>({text:(l.innerText||l.textContent||"").trim().substring(0,80),href:l.href})).filter(l=>l.text&&l.href&&!l.href.startsWith("javascript:")));return{title:r,url:o.url(),text:a.substring(0,8e3)+(a.length>8e3?`
|
|
130
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function bf(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let a=await(await Bn()).newPage();try{await a.setViewportSize({width:e,height:s}),await a.goto(t,{waitUntil:"networkidle",timeout:o});let c=await a.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 a.title(),url:a.url()}}finally{await a.close()}}async function xf(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await Bn()).newPage();try{await r.goto(t,{waitUntil:"domcontentloaded",timeout:n}),s?await r.getByText(s,{exact:!1}).first().click({timeout:1e4}):await r.locator(e).first().click({timeout:1e4}),await r.waitForLoadState("domcontentloaded");let a=await r.title();return`Clicked \u2014 now at: ${r.url()} (${a})`}finally{await r.close()}}async function _f(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 a=await(await Bn()).newPage();try{return await a.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await a.fill(e,String(s)),n&&(await a.keyboard.press("Enter"),await a.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${a.url()}`:"Not submitted."}`}finally{await a.close()}}Zi.exports={isPlaywrightAvailable:Qi,browserNavigate:wf,browserScreenshot:bf,browserClick:xf,browserFill:_f,closeBrowser:yf,INSTALL_MSG:Vi}});var Hn=N((u$,ea)=>{var{C:K}=oe(),Yt="",pe=[],Jt=0,at=null;function kf(t){at=t}function vf(t,e){Yt=t,pe=[],Jt=0;for(let n of e){Jt++;let o=`t${Jt}`;pe.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${Jt}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=pe.map(n=>({...n}));return at&&at("create",{name:t,tasks:s}),s}function Sf(t,e,s){let n=pe.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),at&&at("update",{id:t,status:e,result:s}),{...n}):null}function Ef(){return{name:Yt,tasks:pe.map(t=>({...t}))}}function Cf(){Yt="",pe=[],Jt=0,at&&at("clear",{})}function Tf(){return pe.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=pe.find(n=>n.id===e);return s&&s.status==="done"}))}function Rf(){if(pe.length===0)return`${K.dim}No active tasks${K.reset}`;let t=[];Yt&&(t.push(` ${K.bold}${K.cyan}Tasks: ${Yt}${K.reset}`),t.push(` ${K.dim}${"\u2500".repeat(40)}${K.reset}`));for(let o of pe){let r,a;switch(o.status){case"done":r="\u2713",a=K.green;break;case"in_progress":r="\u2192",a=K.cyan;break;case"failed":r="\u2717",a=K.red;break;default:r="\xB7",a=K.dim}let c=o.dependsOn.length>0?` ${K.dim}(after: ${o.dependsOn.join(", ")})${K.reset}`:"",l=`[${o.status}]`,u=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${a}${r}${K.reset} ${K.bold}${o.id}${K.reset} ${u.padEnd(40)} ${a}${l}${K.reset}${c}`),o.result&&o.status==="done"){let d=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${K.dim}\u2192 ${d}${K.reset}`)}}let e=pe.filter(o=>o.status==="done").length,s=pe.filter(o=>o.status==="failed").length,n=pe.length;return t.push(` ${K.dim}${"\u2500".repeat(40)}${K.reset}`),t.push(` ${K.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${K.reset}`),t.join(`
|
|
131
|
+
`)}function Af(){return pe.length>0&&pe.some(t=>t.status==="pending"||t.status==="in_progress")}ea.exports={createTasks:vf,updateTask:Sf,getTaskList:Ef,clearTasks:Cf,getReadyTasks:Tf,renderTaskList:Rf,setOnChange:kf,hasActiveTasks:Af}});var eo=N((d$,na)=>{var{getActiveModel:Of,getActiveProviderName:Mf}=fe(),Xt={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},Vt={"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"},Qt={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Me={};function ta(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Me=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Me={}}}ta();function Zs(){let e=Of()?.id,s=Mf();return e&&Me[e]?Me[e]:s&&Me[`${s}:*`]?Me[`${s}:*`]:e&&Vt[e]?Vt[e]:s&&Qt[s]?Qt[s]:"full"}function Nf(t,e){return t&&Me[t]?Me[t]:e&&Me[`${e}:*`]?Me[`${e}:*`]:t&&Vt[t]?Vt[t]:e&&Qt[e]?Qt[e]:"full"}function Pf(t,e){let s=e||Zs();if(s==="full"||!Xt[s])return t;let n=new Set(Xt[s]);return t.filter(o=>n.has(o.function.name))}function Lf(){let t=Zs(),e=Xt[t]?Xt[t].length:"all";return{tier:t,toolCount:e}}na.exports={filterToolsForModel:Pf,getActiveTier:Zs,getModelTier:Nf,getTierInfo:Lf,TIERS:Xt,MODEL_TIERS:Vt,PROVIDER_DEFAULT_TIER:Qt,loadConfigOverrides:ta}});var pa=N((m$,ma)=>{var{callStream:If,getActiveProviderName:zn,getActiveModelId:qf,getConfiguredProviders:jf,getProvider:sa,getActiveProvider:oa,parseModelSpec:ra}=fe(),{parseToolArgs:Df}=Rn(),{filterToolsForModel:Ff,getModelTier:Gn}=eo(),{trackUsage:Uf}=xt(),{MultiProgress:Wf,C:f$}=oe(),Bf=15,ia=5,aa=3,Kn=new Map;function Hf(t,e){let s=Kn.get(t);return s&&s!==e?!1:(Kn.set(t,e),!0)}function to(t){Kn.delete(t)}function no(){Kn.clear()}function ca(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 la(t,e,s){let n;for(let o=0;o<=aa;o++)try{return await If(t,e,s)}catch(r){if(n=r,o<aa&&ca(r)){let c=(r.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 r}throw n}var Gf=new Set(["ask_user","task_list","spawn_agents"]),zf=new Set(["write_file","edit_file","patch_file"]),Kf=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Jf=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function ua(t){return Jf.test(t)?"full":Kf.test(t)?"essential":"standard"}function da(t){let e=jf(),s=zn(),n=[...e].sort((o,r)=>(o.name===s?-1:1)-(r.name===s?-1:1));for(let o of n)for(let r of o.models)if(Gn(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Yf={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function so(t){if(t.model){let{provider:o,model:r}=ra(t.model),a=o?sa(o):oa(),c=o||zn();if(a&&a.isConfigured()&&(a.getModel(r)||c==="local")){let l=Gn(r,c);return{provider:c,model:r,tier:l}}}let e=ua(t.task),s=Yf[e];if(s){let{provider:o,model:r}=ra(s),a=o?sa(o):oa(),c=o||zn();if(a&&a.isConfigured()&&(a.getModel(r)||c==="local")){let l=Gn(r,c);return{provider:c,model:r,tier:l}}}let n=da(e);if(n){let o=Gn(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function fa(t,e={}){let s=Math.min(t.max_iterations||10,Bf),n=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,o=[],r={input:0,output:0},a=new Set,l=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
|
|
132
132
|
|
|
133
133
|
TASK: ${t.task}
|
|
134
134
|
${t.context?`
|
|
@@ -150,49 +150,49 @@ TOOL STRATEGY:
|
|
|
150
150
|
ERROR RECOVERY:
|
|
151
151
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
152
152
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
153
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=
|
|
154
|
-
`)}let w={};d&&(w.provider=d),f&&(w.model=f);try{for(let $=0;$<s;$++){let x=await
|
|
155
|
-
...(truncated)`:
|
|
156
|
-
`)}catch(r){return o.stop(),
|
|
157
|
-
`);for(let r of o){let a=r.match(/^(\w+):\s*(.+)$/);if(!a)continue;let c=a[1].trim(),l=a[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
|
|
158
|
-
`);for(let a of r)if(a.startsWith("#")){let c=a.replace(/^#+\s*/,"");for(let l of
|
|
153
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=so(t),d=u.provider,f=u.model,m=u.tier,{TOOL_DEFINITIONS:h,executeTool:p}=Fe(),g=Ff(h.filter($=>!Gf.has($.function.name)),m);if(f&&!t._skipLog){let $=m?` (${m})`:"";process.stderr.write(` [sub-agent: ${d}:${f}${$}]
|
|
154
|
+
`)}let w={};d&&(w.provider=d),f&&(w.model=f);try{for(let $=0;$<s;$++){let x=await la(l,g,w);if(!x||typeof x!="object")throw new Error("Empty or invalid response from provider");if(x.usage){let T=x.usage.prompt_tokens||0,F=x.usage.completion_tokens||0;r.input+=T,r.output+=F;let q=d||zn(),Q=f||qf();Uf(q,Q,T,F)}let O=x.content||"",_=x.tool_calls,k={role:"assistant",content:O||""};if(_&&_.length>0&&(k.tool_calls=_),l.push(k),!_||_.length===0){for(let T of a)to(T);return{task:t.task,status:"done",result:O||"(no response)",toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}let C=_.map(T=>{let F=T.function.name,q=Df(T.function.arguments),Q=T.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!q)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${F}`,tool_call_id:Q});if(zf.has(F)&&q.path){let j=require("path"),Y=j.isAbsolute(q.path)?q.path:j.resolve(process.cwd(),q.path);if(!Hf(Y,n))return Promise.resolve({role:"tool",content:`ERROR: File '${q.path}' is locked by another sub-agent. Try a different approach or skip this file.`,tool_call_id:Q});a.add(Y)}return o.push(F),p(F,q,{autoConfirm:!0,silent:!0}).then(j=>{let Y=String(j??"");return{role:"tool",content:Y.length>2e4?Y.substring(0,2e4)+`
|
|
155
|
+
...(truncated)`:Y,tool_call_id:Q}}).catch(j=>({role:"tool",content:`ERROR: ${j.message}`,tool_call_id:Q}))}),v=await Promise.all(C);l.push(...v),e.onUpdate&&e.onUpdate(`step ${$+1}/${s}`)}for(let $ of a)to($);return{task:t.task,status:"truncated",abortReason:"iteration_limit",result:l[l.length-1]?.content||"(max iterations reached)",toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}catch($){for(let x of a)to(x);return{task:t.task,status:"failed",result:`Error: ${$.message}`,toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}}async function Xf(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>ia)return`ERROR: Max ${ia} parallel agents allowed, got ${e.length}`;let s=e.map(r=>so(r)),n=e.map((r,a)=>{let c=s[a],l=c.model?` [${c.model}]`:"",u=r.task.substring(0,44-l.length);return`Agent ${a+1}${l}: ${u}${r.task.length>u.length?"...":""}`}),o=new Wf(n);o.start();try{let r=e.map((d,f)=>{let m=s[f],h=m.model?{...d,model:`${m.provider}:${m.model}`,_skipLog:!0}:{...d,_skipLog:!0};return fa(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}}))}),a=await Promise.all(r);o.stop(),no();let c=["Sub-agent results:",""],l=0,u=0;for(let d=0;d<a.length;d++){let f=a[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(`
|
|
156
|
+
`)}catch(r){return o.stop(),no(),`ERROR: Sub-agent execution failed: ${r.message}`}}ma.exports={runSubAgent:fa,executeSpawnAgents:Xf,clearAllLocks:no,classifyTask:ua,pickModelForTier:da,resolveSubAgentModel:so,isRetryableError:ca,callWithRetry:la}});var tn=N((p$,Ca)=>{var X=require("fs"),We=require("path"),Vf=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 Ct(){let t=We.join(process.cwd(),".nex","brain");return X.existsSync(t)||X.mkdirSync(t,{recursive:!0}),t}function ha(){return We.join(Ct(),".brain-index.json")}function io(){return We.join(Ct(),".embeddings.json")}function Zt(){let t=We.join(process.cwd(),".nex","brain");if(!X.existsSync(t))return[];try{return X.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=We.join(t,e),n=X.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 en(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(`
|
|
157
|
+
`);for(let r of o){let a=r.match(/^(\w+):\s*(.+)$/);if(!a)continue;let c=a[1].trim(),l=a[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 ga(t){let e=We.join(Ct(),`${t}.md`);if(!X.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=X.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=en(s);return{name:t,content:s,body:o,frontmatter:n}}function Qf(t,e){let s=We.join(Ct(),`${t}.md`);X.writeFileSync(s,e,"utf-8"),tm(t,e),Zf()}function Zf(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=io();X.existsSync(t)&&setImmediate(async()=>{try{await ka()}catch{}})}function em(t){let e=We.join(Ct(),`${t}.md`);return X.existsSync(e)?(X.unlinkSync(e),nm(t),!0):!1}function Jn(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Vf.has(e))}function ao(t){let e={},{frontmatter:s,body:n}=en(t),o=Array.isArray(s.tags)?s.tags:[];for(let a of o){let c=a.toLowerCase().replace(/[^a-z0-9-]/g,"");c.length>1&&(e[c]=(e[c]||0)+5)}let r=(n||t).split(`
|
|
158
|
+
`);for(let a of r)if(a.startsWith("#")){let c=a.replace(/^#+\s*/,"");for(let l of Jn(c))e[l]=(e[l]||0)+3}for(let a of Jn(n||t))e[a]=(e[a]||0)+1;return e}function co(){let t=ha();if(!X.existsSync(t))return{documents:{}};try{return JSON.parse(X.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function lo(t){X.writeFileSync(ha(),JSON.stringify(t,null,2),"utf-8")}function tm(t,e){let s=co(),{frontmatter:n}=en(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:ao(e),tags:o,modified:new Date().toISOString()},lo(s)}function nm(t){let e=co();delete e.documents[t],lo(e)}function ro(){let t=Zt(),e={documents:{}};for(let s of t){let n=X.readFileSync(s.path,"utf-8"),{frontmatter:o}=en(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:ao(n),tags:r,modified:s.modified.toISOString()}}return lo(e),e}function $a(){let t=co(),e=Zt();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return ro()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return ro();return t}function ya(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=Jn(t);if(o.length===0)return[];let r=$a(),a=[];for(let[c,l]of Object.entries(r.documents)){let u=0;for(let d of o){l.keywords[d]&&(u+=l.keywords[d]);for(let[f,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&&a.push({name:c,score:u})}return a.sort((c,l)=>l.score-c.score),a.slice(0,s)}var wa=process.env.NEX_EMBED_MODEL||"nomic-embed-text",oo=400,sm=50;async function ba(){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(wa.split(":")[0]))}catch{return!1}}async function uo(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),n=require("https"),o=new URL(`${e}/api/embeddings`),r=o.protocol==="https:"?n:s,a=JSON.stringify({model:wa,prompt:t});return new Promise((c,l)=>{let u=r.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(a)},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(a),u.end()})}function xa(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,n=0,o=0;for(let a=0;a<t.length;a++)s+=t[a]*e[a],n+=t[a]*t[a],o+=e[a]*e[a];let r=Math.sqrt(n)*Math.sqrt(o);return r===0?0:s/r}function _a(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+oo).join(" ");if(s.push({text:o,offset:n}),n+oo>=e.length)break;n+=oo-sm}return s}async function ka(){let t=Zt(),e={documents:{}},s=io();if(X.existsSync(s))try{e=JSON.parse(X.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 r=X.readFileSync(n.path,"utf-8"),a=_a(r),c=[];for(let l of a){let u=await uo(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 X.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function va(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=io();if(!X.existsSync(o))return[];let r;try{r=JSON.parse(X.readFileSync(o,"utf-8"))}catch{return[]}let a=await uo(t),c=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,f="";for(let m of u.chunks||[]){let h=xa(a,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 Sa(t,e,s={}){let{k:n=60,topK:o=3}=s,r={};return t.forEach((a,c)=>{r[a.name]=(r[a.name]||0)+1/(n+c+1)}),e.forEach((a,c)=>{r[a.name]=(r[a.name]||0)+1/(n+c+1)}),Object.entries(r).map(([a,c])=>({name:a,score:c})).sort((a,c)=>c.score-a.score).slice(0,o)}async function Ea(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=ya(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await ba()){let c=await va(t,{topK:s});r=Sa(o,c,{topK:s})}}catch{}return r.map(a=>{let c=ga(a.name),l=(c.body||c.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:a.name,score:a.score,content:c.content,excerpt:l}})}async function om(t){if(!t||!t.trim())return"";let e=We.join(process.cwd(),".nex","brain");if(!X.existsSync(e)||Zt().length===0)return"";let n;try{n=await Ea(t,{topK:3})}catch{return""}if(!n||n.length===0)return"";let o;try{o=Te().estimateTokens}catch{o=l=>Math.ceil(l.length/4)}let r=25e3,a=[],c=0;for(let l of n){let u=l.content||"",d=o(u);if(c+d>r){let m=r-c;if(m<100)break;let h=m/d;u=u.slice(0,Math.floor(u.length*h))+`
|
|
159
159
|
...(truncated)`}let f=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(a.push(`--- ${l.name} (relevance: ${f}) ---
|
|
160
160
|
${u}`),c+=o(u),c>=r)break}return a.length===0?"":`KNOWLEDGE BASE (auto-selected):
|
|
161
161
|
|
|
162
162
|
${a.join(`
|
|
163
163
|
|
|
164
|
-
`)}`}
|
|
165
|
-
${a.map(l=>
|
|
166
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
164
|
+
`)}`}Ca.exports={getBrainDir:Ct,listDocuments:Zt,readDocument:ga,writeDocument:Qf,removeDocument:em,buildIndex:ro,getIndex:$a,query:Ea,getBrainContext:om,isEmbeddingAvailable:ba,generateEmbedding:uo,buildEmbeddingIndex:ka,semanticQuery:va,cosineSimilarity:xa,_keywordQuery:ya,_extractKeywords:ao,_chunkText:_a,parseFrontmatter:en,tokenize:Jn,_fuseResults:Sa}});var Fe=N((y$,ja)=>{var V=require("fs").promises,Ta=require("fs"),we=require("path"),ee=require("util").promisify(require("child_process").exec),Ra=require("util").promisify(require("child_process").execFile),{spawnSync:rm}=require("child_process"),fo=require("axios"),{isForbidden:im,isDangerous:am,isCritical:Aa,confirm:Ne}=Oe(),{showClaudeDiff:Yn,showClaudeNewFile:cm,showEditDiff:h$,confirmFileChange:nn}=hi(),{C:P,Spinner:La,getToolSpinnerText:lm}=oe(),{isGitRepo:mo,getCurrentBranch:Oa,getStatus:um,getDiff:dm}=it(),{recordChange:Xn}=kt(),{fuzzyFindText:Ma,findMostSimilar:ho}=Di(),{runDiagnostics:sn}=Ui(),{findFileInIndex:fm,getFileIndex:g$}=zs(),{resolveProfile:Pe,sshExec:Ye,scpUpload:mm,scpDownload:pm}=Et(),{resolveDeployConfig:hm,loadDeployConfigs:$$}=Vs(),gm=/^(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/,$m=/^ssh\s/,ym=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function Vn(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=ye(e);if(s&&await V.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=we.extname(t);if(!o)for(let a of n){let c=ye(t+a);if(c&&await V.access(c).then(()=>!0).catch(()=>!1))return{fixedPath:c,message:`(auto-fixed: added ${a} extension)`}}if(o){let a=t.replace(/\.[^.]+$/,"");for(let c of n){if(c===o)continue;let l=ye(a+c);if(l&&await V.access(l).then(()=>!0).catch(()=>!1))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${c})`}}}let r=we.basename(t);if(r&&r.length>2)try{let a=fm(r).map(c=>ye(c));if(a.length===1)return{fixedPath:a[0],message:`(auto-fixed: found ${r} at ${we.relative(process.cwd(),a[0])})`};if(a.length>1&&a.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
165
|
+
${a.map(l=>we.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
166
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function wm(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 Ia(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+`
|
|
167
167
|
|
|
168
168
|
`+s.join(`
|
|
169
|
-
`)}function Na(t,e,s){let n=fo(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 Ra=!1,rn=null;function gm(){rn&&(rn(),rn=null)}async function uo(){if(!Ra){Ra=!0;try{let{stdout:t}=await se("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await se('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await se("git stash pop",{cwd:process.cwd(),timeout:1e4}),await se("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var $m=[/\.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 $e(t){let e=ye.isAbsolute(t)?ye.resolve(t):ye.resolve(process.cwd(),t);for(let s of $m)if(s.test(e))return null;return e}var ym=[{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 on(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 a=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${a}"`}return r}async function Aa(t,e,s={}){switch(t){case"bash":{let n=e.command,o=nm(n);if(o){let u=hm(n);return`BLOCKED: Command matches forbidden pattern: ${o}${u?`
|
|
170
|
-
HINT: ${u}`:""}`}if(s.autoConfirm?
|
|
171
|
-
${P.yellow}${u}: ${n}${P.reset}`),!await
|
|
172
|
-
${f}`}}case"read_file":{let n
|
|
173
|
-
`+m.message:""}`}let r=Buffer.alloc(8192),a=await
|
|
169
|
+
`)}function qa(t,e,s){let n=ho(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 Na=!1,rn=null;function bm(){rn&&(rn(),rn=null)}async function po(){if(!Na){Na=!0;try{let{stdout:t}=await ee("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await ee('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await ee("git stash pop",{cwd:process.cwd(),timeout:1e4}),await ee("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var xm=[/\.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 ye(t){let e=we.isAbsolute(t)?we.resolve(t):we.resolve(process.cwd(),t);for(let s of xm)if(s.test(e))return null;return e}var _m=[{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 on(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 a=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${a}"`}return r}async function Pa(t,e,s={}){switch(t){case"bash":{let n=e.command,o=im(n);if(o){let u=wm(n);return`BLOCKED: Command matches forbidden pattern: ${o}${u?`
|
|
170
|
+
HINT: ${u}`:""}`}if(s.autoConfirm?Aa(n):am(n)){let u=Aa(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
|
|
171
|
+
${P.yellow}${u}: ${n}${P.reset}`),!await Ne(" Execute?"))return"CANCELLED: User declined to execute this command."}let a=process.cwd();try{Ta.accessSync(a)}catch{a=require("os").homedir(),s.silent||console.log(`${P.yellow} \u26A0 Working directory no longer exists \u2014 running in ${a}${P.reset}`)}let c=$m.test(n.trim())&&!ym.test(n.trim());if(gm.test(n.trim())||c){s.silent||console.log(`${P.dim} \u25B6 interactive: ${n}${P.reset}`);let u=rm("sh",["-c",n],{stdio:"inherit",cwd:a});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 La(`Running: ${n.substring(0,60)}${n.length>60?"...":""}`);l&&l.start();try{let{stdout:u,stderr:d}=await ee(n,{cwd:a,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=Ia(d,n);return`EXIT ${u.code||1}
|
|
172
|
+
${f}`}}case"read_file":{let n=ye(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await V.access(n).then(()=>!0).catch(()=>!1)){let m=await Vn(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${P.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${we.relative(process.cwd(),n)}${P.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
173
|
+
`+m.message:""}`}let r=Buffer.alloc(8192),a=await Ta.promises.open(n,"r"),{bytesRead:c}=await a.read(r,0,8192,0);await a.close();for(let m=0;m<c;m++)if(r[m]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let l=await V.readFile(n,"utf-8");if(!l&&(await V.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let u=l.split(`
|
|
174
174
|
`),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(`
|
|
175
|
-
`)}case"write_file":{await
|
|
176
|
-
`+d.message:""}`}let r=await
|
|
175
|
+
`)}case"write_file":{await po();let n=ye(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await V.access(n).then(()=>!0).catch(()=>!1),r=null;if(s.autoConfirm)o&&(r=await V.readFile(n,"utf-8"));else if(o){r=await V.readFile(n,"utf-8");let l=await sn(n,e.content);if(Yn(n,r,e.content,{annotations:l}),!await nn("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let l=await sn(n,e.content);if(cm(n,e.content,{annotations:l}),!await nn("Create"))return"CANCELLED: User declined to create file."}let a=we.dirname(n);return await V.access(a).then(()=>!0).catch(()=>!1)||await V.mkdir(a,{recursive:!0}),await V.writeFile(n,e.content,"utf-8"),Xn("write_file",n,r,e.content),`Written: ${n} (${e.content.length} chars)`}case"edit_file":{await po();let n=ye(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await V.access(n).then(()=>!0).catch(()=>!1)){let d=await Vn(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${P.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${we.relative(process.cwd(),n)}${P.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
176
|
+
`+d.message:""}`}let r=await V.readFile(n,"utf-8"),a=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let d=Ma(r,e.old_text);if(d)a=d,c=!0,console.log(`${P.dim} \u2713 fuzzy whitespace match applied${P.reset}`);else{let f=qa(r,e.old_text,e.new_text);if(f){if(!s.autoConfirm){let p=await sn(n,f.content);if(Yn(n,r,f.content,{annotations:p}),!await nn(`Apply (auto-fix, line ${f.line}, distance ${f.distance})`))return"CANCELLED: User declined to apply edit."}await V.writeFile(n,f.content,"utf-8"),Xn("edit_file",n,r,f.content);let h=f.matchText.length>80?f.matchText.substring(0,77)+"...":f.matchText;return console.log(`${P.dim} \u2713 auto-fixed edit: line ${f.line}, distance ${f.distance}${P.reset}`),`Edited: ${n} (auto-fixed, line ${f.line}, distance ${f.distance}, matched: "${h}")`}let m=ho(r,e.old_text);return m?`ERROR: old_text not found in ${n}
|
|
177
177
|
Most similar text (line ${m.line}, distance ${m.distance}):
|
|
178
|
-
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=r.split(a).join(e.new_text),f=await sn(n,d);if(
|
|
179
|
-
`)||"(empty)"}case"search_files":{let n
|
|
178
|
+
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=r.split(a).join(e.new_text),f=await sn(n,d);if(Yn(n,r,d,{annotations:f}),!await nn(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(a).join(e.new_text);return await V.writeFile(n,u,"utf-8"),Xn("edit_file",n,r,u),c?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=ye(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await V.access(n).then(()=>!0).catch(()=>!1)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=ye(u),f=await V.access(d).then(()=>!0).catch(()=>!1);if(d&&f)n=d;else return`ERROR: Directory not found: ${e.path}`}let r=e.max_depth||2,a=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");a=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let c=[],l=async(u,d,f)=>{if(d>r)return;let m;try{m=await V.readdir(u,{withFileTypes:!0})}catch{return}m=m.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of m){if(a&&!h.isDirectory()&&!a.test(h.name))continue;let p=h.isDirectory()?"/":"";c.push(`${f}${h.name}${p}`),h.isDirectory()&&await l(we.join(u,h.name),d+1,f+" ")}};return await l(n,1,""),c.join(`
|
|
179
|
+
`)||"(empty)"}case"search_files":{let n=ye(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:r}=await Ra("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
180
180
|
`).slice(0,50).join(`
|
|
181
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path
|
|
182
|
-
`);return x?`${
|
|
181
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?ye(e.path):o,a=e.pattern,c=_=>{let k=_.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${k}$`)},l=c(a),u=a.split("/").pop(),d=c(u),{getFileIndex:f,getIndexedCwd:m,refreshIndex:h,isIndexValid:p}=zs(),g=f(),w=m();p(r)||(await h(r),g=f());let $=g.filter(_=>l.test(_)||d.test(we.basename(_))).map(_=>we.join(r,_));if($.length===0)return"(no matches)";let x=$.length>200,O=$.slice(0,200).join(`
|
|
182
|
+
`);return x?`${O}
|
|
183
183
|
|
|
184
|
-
\u26A0 Results truncated at 200. Use a more specific pattern.`:
|
|
184
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:O}case"grep":{let n=e.path?ye(e.path):process.cwd(),o=["-rn","-E"];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:r}=await Ra("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
185
185
|
`).slice(0,100).join(`
|
|
186
|
-
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await
|
|
187
|
-
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let a=await
|
|
186
|
+
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await po();let n=ye(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await V.access(n).then(()=>!0).catch(()=>!1)){let m=await Vn(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${P.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${we.relative(process.cwd(),n)}${P.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
187
|
+
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let a=await V.readFile(n,"utf-8"),c=[],l=!1,u=!1;for(let m=0;m<r.length;m++){let{old_text:h,new_text:p}=r[m];if(a.includes(h))c.push({old_text:h,new_text:p});else{let g=Ma(a,h);if(g)c.push({old_text:g,new_text:p}),l=!0;else{let w=ho(a,h);if(w){let $=Math.max(3,Math.ceil(h.length*.05));if(w.distance<=$)c.push({old_text:w.text,new_text:p}),u=!0;else return`ERROR: Patch ${m+1} old_text not found in ${n}
|
|
188
188
|
Most similar text (line ${w.line}, distance ${w.distance}):
|
|
189
|
-
${w.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${n}`}}}let d=a;for(let{old_text:m,new_text:h}of c)d=d.split(m).join(h);if(!s.autoConfirm){let m=await sn(n,d);if(
|
|
189
|
+
${w.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${n}`}}}let d=a;for(let{old_text:m,new_text:h}of c)d=d.split(m).join(h);if(!s.autoConfirm){let m=await sn(n,d);if(Yn(n,a,d,{annotations:m}),!await nn(l?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await V.writeFile(n,d,"utf-8"),Xn("patch_file",n,a,d);let f=u?" (auto-fixed)":l?" (fuzzy match)":"";return`Patched: ${n} (${r.length} replacements)${f}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let r=await fo.get(n,{timeout:15e3,maxContentLength:1048576,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}});return(typeof r.data=="string"?r.data:JSON.stringify(r.data)).replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().substring(0,o)||"(empty response)"}catch(r){return`ERROR: Failed to fetch ${n}: ${r.message}`}}case"web_search":{let n=e.max_results||5;if(process.env.PERPLEXITY_API_KEY)try{let o=await fo.post("https://api.perplexity.ai/chat/completions",{model:"sonar",messages:[{role:"user",content:e.query}],max_tokens:1024,search_recency_filter:"month",return_citations:!0},{timeout:2e4,headers:{Authorization:`Bearer ${process.env.PERPLEXITY_API_KEY}`,"Content-Type":"application/json"}}),r=o.data?.choices?.[0]?.message?.content||"",a=o.data?.citations||[],c=`[Perplexity grounded search]
|
|
190
190
|
|
|
191
191
|
${r}`;return a.length>0&&(c+=`
|
|
192
192
|
|
|
193
193
|
Sources:
|
|
194
194
|
`+a.slice(0,n).map((l,u)=>`${u+1}. ${l}`).join(`
|
|
195
|
-
`)),c}catch(o){console.error(`${P.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${P.reset}`)}try{let r=(await
|
|
195
|
+
`)),c}catch(o){console.error(`${P.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${P.reset}`)}try{let r=(await fo.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,a=[],c=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=c.exec(r))!==null&&a.length<n;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],d=l[2].replace(/<[^>]+>/g,"").trim();try{a.push({title:d,url:decodeURIComponent(u)})}catch{a.push({title:d,url:u})}}return a.length===0?"(no results)":a.map((u,d)=>`${d+1}. ${u.title}
|
|
196
196
|
${u.url}`).join(`
|
|
197
197
|
|
|
198
198
|
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=Kt();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
|
|
@@ -207,58 +207,58 @@ Title: ${o.title}
|
|
|
207
207
|
URL: ${o.url}
|
|
208
208
|
|
|
209
209
|
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=Kt();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=Kt();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 n=e.question;return new Promise(o=>{let r=require("readline").createInterface({input:process.stdin,output:process.stdout});rn=()=>{r.close(),o("CANCELLED")},console.log(`
|
|
210
|
-
${P.cyan}${P.bold} ? ${n}${P.reset}`),r.question(`${P.cyan} > ${P.reset}`,a=>{rn=null,r.close(),o(a.trim()||"(no response)")})})}case"git_status":{if(!await
|
|
210
|
+
${P.cyan}${P.bold} ? ${n}${P.reset}`),r.question(`${P.cyan} > ${P.reset}`,a=>{rn=null,r.close(),o(a.trim()||"(no response)")})})}case"git_status":{if(!await mo())return"ERROR: Not a git repository";let n=await Oa()||"(detached)",o=await um();if(o.length===0)return`Branch: ${n}
|
|
211
211
|
Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let a of o){let c=a.status==="M"?"modified":a.status==="A"?"added":a.status==="D"?"deleted":a.status==="??"?"untracked":a.status;r.push(` ${c}: ${a.file}`)}return r.join(`
|
|
212
|
-
`)}case"git_diff":{if(!await
|
|
212
|
+
`)}case"git_diff":{if(!await mo())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 dm(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await mo())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:r,renderTaskList:a,hasActiveTasks:c}=Hn(),{getActiveTaskProgress:l}=oe(),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(`
|
|
213
213
|
`+a()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
214
214
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
215
215
|
`)}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(`
|
|
216
216
|
`+a()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let d=r();return d.tasks.length===0?"No active tasks":(u||console.log(`
|
|
217
|
-
`+a()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=
|
|
217
|
+
`+a()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=pa();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=fe();return n(e.model)?`Switched to ${o()}:${r()}`:`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:r}=await ee(`gh ${o.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),a=JSON.parse(r||"[]");return a.length===0?"No workflow runs found.":a.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(`
|
|
218
218
|
`)}catch(r){let a=(r.stderr||r.message||"").toString();return a.includes("not found")||a.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${a.split(`
|
|
219
|
-
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:a}=await
|
|
220
|
-
...(truncated)`:"")}let{stdout:n}=await
|
|
219
|
+
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:a}=await ee(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return a.substring(0,8e3)+(a.length>8e3?`
|
|
220
|
+
...(truncated)`:"")}let{stdout:n}=await ee(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),r=[`Run: ${o.name} [${e.run_id}]`,`Branch: ${o.headBranch} Status: ${o.conclusion||o.status}`,`Started: ${o.createdAt} Finished: ${o.updatedAt||"\u2014"}`,"","Jobs:"];for(let a of o.jobs||[]){let c=a.conclusion==="success"?"\u2713":a.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${c} ${a.name} (${a.conclusion||a.status})`);for(let l of a.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${l.name}`)}}return r.join(`
|
|
221
221
|
`)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
|
|
222
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=
|
|
223
|
-
${P.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${P.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await
|
|
224
|
-
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=on(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:a,stderr:c}=await
|
|
225
|
-
`)[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,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let a=on(r,e);try{let{stdout:c,stderr:l}=await
|
|
222
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Oe(),o=e.branch||await Oa()||"main",r=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",a=`gh workflow run ${e.workflow} --ref ${o} ${r}`.trim();if(console.log(`
|
|
223
|
+
${P.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${P.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await ee(a,{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(`
|
|
224
|
+
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=on(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:a,stderr:c}=await ee(r,{timeout:3e4,maxBuffer:2097152});return(a||c||"(no pods)").trim()}catch(a){let c=(a.stderr||a.message||"").toString().split(`
|
|
225
|
+
`)[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,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let a=on(r,e);try{let{stdout:c,stderr:l}=await ee(a,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
|
|
226
226
|
...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
227
227
|
`)[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(`
|
|
228
|
-
${P.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${P.reset}`),console.log(`${P.dim} Command: ${e.command}${P.reset}`),!await
|
|
228
|
+
${P.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${P.reset}`),console.log(`${P.dim} Command: ${e.command}${P.reset}`),!await Ne(" Execute in pod?"))return"CANCELLED: User declined.";let r=`exec ${e.pod} -n ${n}`;e.container&&(r+=` -c ${e.container}`),r+=` -- sh -c ${JSON.stringify(e.command)}`;let a=on(r,e);try{let{stdout:c,stderr:l}=await ee(a,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
229
229
|
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let n=!!e.dry_run;if(!n){let a=e.file;if(console.log(`
|
|
230
|
-
${P.yellow} \u26A0 kubectl apply: ${a}${e.namespace?` (ns: ${e.namespace})`:""}${P.reset}`),!await
|
|
230
|
+
${P.yellow} \u26A0 kubectl apply: ${a}${e.namespace?` (ns: ${e.namespace})`:""}${P.reset}`),!await Ne(" 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 r=on(o,e);try{let{stdout:a,stderr:c}=await ee(r,{timeout:12e4,maxBuffer:2097152});return(a||c||"(no output)").trim()}catch(a){return`ERROR: ${(a.stderr||a.message||"").toString().split(`
|
|
231
231
|
`)[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(`
|
|
232
|
-
${P.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${n})${P.reset}`),!await
|
|
232
|
+
${P.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${n})${P.reset}`),!await Ne(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,a=on(r,e);try{let{stdout:c,stderr:l}=await ee(a,{timeout:12e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
233
233
|
`)[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}=tn(),{name:r,content:a,mode:c}=e;if(c==="create"&&o(r).content)return`ERROR: Document "${r}" already exists. Use mode "update" to overwrite.`;if(c==="append"){let l=o(r),u=l.content?l.content+`
|
|
234
234
|
|
|
235
|
-
`+a:a;return n(r,u),`Appended to brain document: ${r}.md`}return n(r,a),`${c==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=
|
|
236
|
-
${P.yellow} \u26A0 Remote command on ${h}: ${o}${P.reset}`),!await
|
|
235
|
+
`+a:a;return n(r,u),`Appended to brain document: ${r}.md`}return n(r,a),`${c==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=Pe(e.server)}catch(h){return`ERROR: ${h.message}`}let o=e.command,r=!!e.sudo,a=(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(`
|
|
236
|
+
${P.yellow} \u26A0 Remote command on ${h}: ${o}${P.reset}`),!await Ne(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await Ye(n,o,{timeout:a,sudo:r}),m=[l,u].filter(Boolean).join(`
|
|
237
237
|
`).trim();return d!==0?`EXIT ${d}
|
|
238
|
-
${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=
|
|
239
|
-
${P.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${P.reset}`),!await
|
|
240
|
-
${P.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${P.reset}`),!await
|
|
238
|
+
${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=Pe(e.server)}catch(a){return`ERROR: ${a.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
239
|
+
${P.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${P.reset}`),!await Ne(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await mm(n,e.local_path,e.remote_path)}catch(a){return`ERROR: ${a.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=Pe(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await pm(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",r=e.action==="status",a=null;if(!o)try{a=Pe(e.server)}catch(l){return`ERROR: ${l.message}`}if(!r){let l=o?"local machine":a.user?`${a.user}@${a.host}`:a.host;if(console.log(`
|
|
240
|
+
${P.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${P.reset}`),!await Ne(" 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 ee(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}
|
|
241
241
|
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await Ye(a,c,{timeout:15e3,sudo:!0}),m=[l,u].filter(Boolean).join(`
|
|
242
242
|
`).trim();return d!==0?/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${e.service}" not found on ${a.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${d}
|
|
243
|
-
${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,r=e.since?`--since "${e.since}"`:"",a=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${o} ${r} ${a} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:p,stderr:g}=await
|
|
244
|
-
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=
|
|
243
|
+
${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,r=e.since?`--since "${e.since}"`:"",a=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${o} ${r} ${a} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:p,stderr:g}=await ee(c,{timeout:15e3});return(p||g||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
|
|
244
|
+
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=Pe(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await Ye(l,c,{timeout:2e4}),h=[u,d].filter(Boolean).join(`
|
|
245
245
|
`).trim();return f!==0?`EXIT ${f}
|
|
246
|
-
${m||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:m,stderr:h}=await
|
|
247
|
-
${(m.stderr||m.message||"").toString().trim()}`}let a;try{a=
|
|
246
|
+
${m||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:m,stderr:h}=await ee(r,{timeout:1e4});return(m||h||"(no containers)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
247
|
+
${(m.stderr||m.message||"").toString().trim()}`}let a;try{a=Pe(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await Ye(a,r,{timeout:15e3}),f=[c,l].filter(Boolean).join(`
|
|
248
248
|
`).trim();return u!==0?`EXIT ${u}
|
|
249
|
-
${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,r=e.since?`--since "${e.since}"`:"",a=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:h,stderr:p}=await
|
|
250
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=
|
|
249
|
+
${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,r=e.since?`--since "${e.since}"`:"",a=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:h,stderr:p}=await ee(a,{timeout:15e3});return(h||p||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
250
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Pe(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Ye(c,a,{timeout:2e4}),m=[l,u].filter(Boolean).join(`
|
|
251
251
|
`).trim();return d!==0?`EXIT ${d}
|
|
252
252
|
${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(`
|
|
253
|
-
${P.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${P.reset}`),!await
|
|
254
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=
|
|
253
|
+
${P.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${P.reset}`),!await Ne(" Execute?"))return"CANCELLED: User declined."}let a=`docker exec ${e.container} sh -c ${JSON.stringify(e.command)}`;if(n)try{let{stdout:h,stderr:p}=await ee(a,{timeout:3e4});return(h||p||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
254
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Pe(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Ye(c,a,{timeout:35e3}),m=[l,u].filter(Boolean).join(`
|
|
255
255
|
`).trim();return d!==0?`EXIT ${d}
|
|
256
256
|
${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(`
|
|
257
|
-
${P.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${P.reset}`),!await
|
|
258
|
-
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=
|
|
257
|
+
${P.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${P.reset}`),!await Ne(" Execute?"))return"CANCELLED: User declined."}let a=e.action==="remove"?"rm":e.action,c=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${a} ${e.container}`;if(o)try{let{stdout:p,stderr:g}=await ee(c,{timeout:3e4});return(p||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(p){return`EXIT ${p.code||1}
|
|
258
|
+
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=Pe(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await Ye(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
|
|
259
259
|
`).trim();return f!==0?`EXIT ${f}
|
|
260
|
-
${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...
|
|
261
|
-
${P.yellow} \u26A0 Deploy: ${d} \u2192 ${o}:${e.remote_path}${P.reset}`),e.deploy_script&&console.log(`${P.yellow} Then run: ${e.deploy_script}${P.reset}`),!await
|
|
260
|
+
${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...hm(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=Pe(e.server)}catch(p){return`ERROR: ${p.message}`}let o=n.user?`${n.user}@${n.host}`:n.host,r=n.port&&Number(n.port)!==22?`-e "ssh -p ${n.port}"`:"",a=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}`:""}"`:r,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(`
|
|
261
|
+
${P.yellow} \u26A0 Deploy: ${d} \u2192 ${o}:${e.remote_path}${P.reset}`),e.deploy_script&&console.log(`${P.yellow} Then run: ${e.deploy_script}${P.reset}`),!await Ne(" Proceed with deployment?")))return"CANCELLED: User declined.";let m="";try{let{stdout:p,stderr:g}=await ee(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:
|
|
262
262
|
${m||"(nothing to sync)"}`;let h="";if(e.deploy_script){let{stdout:p,stderr:g,exitCode:w,error:$}=await Ye(n,e.deploy_script,{timeout:6e4}),x=[p,g].filter(Boolean).join(`
|
|
263
263
|
`).trim();if(w!==0)return`rsync OK
|
|
264
264
|
|
|
@@ -267,33 +267,33 @@ ${$||x}`;h=`
|
|
|
267
267
|
|
|
268
268
|
Remote script output:
|
|
269
269
|
${x||"(no output)"}`}return`Deployed ${d} \u2192 ${o}:${e.remote_path}
|
|
270
|
-
${m}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function
|
|
271
|
-
`)}function
|
|
270
|
+
${m}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function km(t,e,s={}){let n=s.silent?null:lm(t,e);if(!n)return Pa(t,e,s);let o=new La(n);o.start();try{let r=await Pa(t,e,s);return o.stop(),r}catch(r){throw o.stop(),r}}ja.exports={TOOL_DEFINITIONS:_m,executeTool:km,resolvePath:ye,autoFixPath:Vn,autoFixEdit:qa,enrichBashError:Ia,cancelPendingAskUser:bm}});var Fa=N((w$,Da)=>{var{loadServerProfiles:$o}=Et(),go={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 vm(){let t=$o();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,r]of Object.entries(t)){let a=r.user?`${r.user}@${r.host}`:r.host,c=r.port&&Number(r.port)!==22?`:${r.port}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",u=r.sudo?", sudo available":"";s.push(`- **${o}**: ${a}${c}${l}${u}`)}let n=new Set;for(let o of Object.values(t))o.os&&go[o.os]&&n.add(o.os);if(n.size>0){s.push("");for(let o of n){let r={almalinux9:"AlmaLinux 9",almalinux8:"AlmaLinux 8",ubuntu:"Ubuntu",debian:"Debian",macos:"macOS"}[o]||o;s.push(`### ${r} Notes`);for(let a of go[o])s.push(`- ${a}`)}}return s.join(`
|
|
271
|
+
`)}function Sm(t){let e=$o();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function Em(){return Object.keys($o())}Da.exports={getServerContext:vm,hasServerOS:Sm,getProfileNames:Em,OS_HINTS:go}});var wo=N((b$,Wa)=>{var Ae=require("fs").promises,ve=require("path"),Qn=require("util").promisify(require("child_process").exec),{C:Le}=oe(),{getMergeConflicts:Ua}=it(),{getServerContext:Cm}=Fa(),yo=new Map,Tt=new Map,Zn=null,Tm=3e4;async function Xe(t){try{return await t()}catch{return null}}async function Rm(){if(!Zn||Date.now()>Zn)return!1;let t=[ve.join(process.cwd(),"package.json"),ve.join(process.cwd(),"README.md"),ve.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await Ae.stat(e),n=Tt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(Tt.has(e))return!1}try{let e=ve.join(process.cwd(),".git","HEAD"),s=await Ae.stat(e),n=Tt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function Am(){let t=[ve.join(process.cwd(),"package.json"),ve.join(process.cwd(),"README.md"),ve.join(process.cwd(),".gitignore"),ve.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await Ae.stat(e);Tt.set(e,s.mtimeMs)}catch{Tt.delete(e)}}async function Om(t){let e="fileContext",s=yo.get(e),n=!1;if(s&&await Rm()&&(n=!0),!n){let u=[],d=ve.join(t,"package.json");if(await Xe(()=>Ae.access(d).then(()=>!0).catch(()=>!1)))try{let w=await Ae.readFile(d,"utf-8"),$=JSON.parse(w),x={name:$.name,version:$.version};$.scripts&&(x.scripts=Object.keys($.scripts).slice(0,15)),$.dependencies&&(x.deps=Object.keys($.dependencies).length),$.devDependencies&&(x.devDeps=Object.keys($.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(x)}`)}catch{}let m=ve.join(t,"README.md");if(await Xe(()=>Ae.access(m).then(()=>!0).catch(()=>!1))){let $=(await Ae.readFile(m,"utf-8")).split(`
|
|
272
272
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
273
273
|
${$.join(`
|
|
274
|
-
`)}`)}let p=ve.join(t,".gitignore");if(await Xe(()=>
|
|
274
|
+
`)}`)}let p=ve.join(t,".gitignore");if(await Xe(()=>Ae.access(p).then(()=>!0).catch(()=>!1))){let w=await Ae.readFile(p,"utf-8");u.push(`GITIGNORE:
|
|
275
275
|
${w.trim()}`)}s=u.join(`
|
|
276
276
|
|
|
277
|
-
`),
|
|
277
|
+
`),yo.set(e,s),Zn=Date.now()+Tm,await Am()}let o=[s],[r,a,c,l]=await Promise.all([Xe(async()=>{let{stdout:u}=await Qn("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Xe(async()=>{let{stdout:u}=await Qn("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Xe(async()=>{let{stdout:u}=await Qn("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),Ua()]);if(r&&o.push(`GIT BRANCH: ${r}`),a&&o.push(`GIT STATUS:
|
|
278
278
|
${a}`),c&&o.push(`RECENT COMMITS:
|
|
279
279
|
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
280
280
|
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
281
|
-
${u}`)}try{let u=
|
|
281
|
+
${u}`)}try{let u=Cm();u&&o.push(u)}catch{}return o.join(`
|
|
282
282
|
|
|
283
|
-
`)}async function
|
|
284
|
-
${e}`);let s=
|
|
285
|
-
${s}`);let n=
|
|
283
|
+
`)}async function Mm(t){let e=ve.join(t,"package.json"),s="";if(await Xe(()=>Ae.access(e).then(()=>!0).catch(()=>!1)))try{let a=await Ae.readFile(e,"utf-8"),c=JSON.parse(a);s=`${c.name||"?"} v${c.version||"?"}`}catch{}let[o,r]=await Promise.all([Xe(async()=>{let{stdout:a}=await Qn("git branch --show-current",{cwd:t,timeout:5e3});return a.trim()}),Ua()]);if(s&&console.log(`${Le.dim} project: ${s}${Le.reset}`),o&&console.log(`${Le.dim} branch: ${o}${Le.reset}`),r&&r.length>0){console.log(`${Le.red} \u26A0 ${r.length} unresolved merge conflict(s):${Le.reset}`);for(let a of r)console.log(`${Le.red} ${a.file}${Le.reset}`);console.log(`${Le.yellow} \u2192 Resolve conflicts before starting tasks${Le.reset}`)}console.log()}Wa.exports={gatherProjectContext:Om,printContext:Mm,_clearContextCache:()=>{yo.clear(),Tt.clear(),Zn=null}}});var lt=N((x$,za)=>{var He=require("fs"),bo=require("path");function es(){return bo.join(process.cwd(),".nex","sessions")}function Ba(){let t=es();He.existsSync(t)||He.mkdirSync(t,{recursive:!0})}function xo(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return bo.join(es(),`${e}.json`)}function _o(t,e,s={}){Ba();let n=xo(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 He.writeFileSync(n,JSON.stringify(o,null,2),"utf-8"),{path:n,name:t}}function Ha(t){let e=xo(t);if(!He.existsSync(e))return null;try{return JSON.parse(He.readFileSync(e,"utf-8"))}catch{return null}}function Ga(){Ba();let t=es(),e=He.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(He.readFileSync(bo.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 Nm(t){let e=xo(t);return He.existsSync(e)?(He.unlinkSync(e),!0):!1}function Pm(){let t=Ga();return t.length===0?null:Ha(t[0].name)}var ct=null,Be=null,an=null;function Lm(t,e={}){t.length!==0&&(ct&&clearTimeout(ct),Be=t,an=e||{},ct=setTimeout(()=>{Be&&Be.length>0&&_o("_autosave",Be,an),ct=null,Be=null,an=null},5e3))}function Im(){ct&&(clearTimeout(ct),ct=null),Be&&Be.length>0&&(_o("_autosave",Be,an),Be=null,an=null)}za.exports={saveSession:_o,loadSession:Ha,listSessions:Ga,deleteSession:Nm,getLastSession:Pm,autoSave:Lm,flushAutoSave:Im,_getSessionsDir:es}});var Ve=N((_$,Qa)=>{var Ge=require("fs"),ts=require("path"),qm=require("os");function ko(){return ts.join(process.cwd(),".nex","memory")}function vo(){return ts.join(ko(),"memory.json")}function jm(){return ts.join(process.cwd(),"NEX.md")}function Ka(){return ts.join(qm.homedir(),".nex","NEX.md")}function Dm(){let t=ko();Ge.existsSync(t)||Ge.mkdirSync(t,{recursive:!0})}function ns(){let t=vo();if(!Ge.existsSync(t))return{};try{return JSON.parse(Ge.readFileSync(t,"utf-8"))}catch{return{}}}function Ja(t){Dm(),Ge.writeFileSync(vo(),JSON.stringify(t,null,2),"utf-8")}function Fm(t,e){let s=ns();s[t]={value:e,updatedAt:new Date().toISOString()},Ja(s)}function Um(t){let e=ns();return e[t]?e[t].value:null}function Wm(t){let e=ns();return t in e?(delete e[t],Ja(e),!0):!1}function Ya(){let t=ns();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Xa(){let t=Ka();if(!Ge.existsSync(t))return"";try{return Ge.readFileSync(t,"utf-8").trim()}catch{return""}}function Va(){let t=jm();if(!Ge.existsSync(t))return"";try{return Ge.readFileSync(t,"utf-8").trim()}catch{return""}}function Bm(){let t=[],e=Xa();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
284
|
+
${e}`);let s=Va();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
285
|
+
${s}`);let n=Ya();if(n.length>0){let o=n.map(r=>` ${r.key}: ${r.value}`).join(`
|
|
286
286
|
`);t.push(`PROJECT MEMORY:
|
|
287
287
|
${o}`)}return t.join(`
|
|
288
288
|
|
|
289
|
-
`)}
|
|
290
|
-
${
|
|
291
|
-
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${
|
|
292
|
-
`)}function
|
|
289
|
+
`)}Qa.exports={remember:Fm,recall:Um,forget:Wm,listMemories:Ya,loadGlobalInstructions:Xa,loadProjectInstructions:Va,getMemoryContext:Bm,_getMemoryDir:ko,_getMemoryFile:vo,_getGlobalNexMdPath:Ka}});var cn=N((v$,tc)=>{var ut=require("fs"),So=require("path"),{C:k$}=oe(),ss={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"},Rt={...ss};function Za(){let t=So.join(process.cwd(),".nex","config.json");if(ut.existsSync(t))try{let e=JSON.parse(ut.readFileSync(t,"utf-8"));e.permissions&&(Rt={...ss,...e.permissions})}catch{}}function Hm(){let t=So.join(process.cwd(),".nex"),e=So.join(t,"config.json"),s={};if(ut.existsSync(e))try{s=JSON.parse(ut.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Rt,ut.existsSync(t)||ut.mkdirSync(t,{recursive:!0}),ut.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function ec(t){return Rt[t]||"ask"}function Gm(t,e){return["allow","ask","deny"].includes(e)?(Rt[t]=e,!0):!1}function zm(t){return ec(t)}function Km(){return Object.entries(Rt).map(([t,e])=>({tool:t,mode:e}))}function Jm(){Rt={...ss}}Za();tc.exports={getPermission:ec,setPermission:Gm,checkPermission:zm,listPermissions:Km,loadPermissions:Za,savePermissions:Hm,resetPermissions:Jm,DEFAULT_PERMISSIONS:ss}});var At=N((E$,ic)=>{var dt=require("fs"),os=require("path"),S$=require("readline"),{C:B}=oe(),re=null,Eo=!1,Co=null,nc=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 rs(){return os.join(process.cwd(),".nex","plans")}function sc(){let t=rs();dt.existsSync(t)||dt.mkdirSync(t,{recursive:!0})}function Ym(t,e=[]){return re={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()},re}function Xm(){return re}function Vm(t){Eo=t}function Qm(){return Eo}function Zm(){return!re||re.status!=="draft"?!1:(re.status="approved",re.updatedAt=new Date().toISOString(),!0)}function ep(){return!re||re.status!=="approved"?!1:(re.status="executing",!0)}function tp(t,e){return!re||t<0||t>=re.steps.length?!1:(re.steps[t].status=e,re.updatedAt=new Date().toISOString(),re.steps.every(s=>s.status==="done"||s.status==="skipped")&&(re.status="completed"),!0)}function np(t){if(!t)return`${B.dim}No active plan${B.reset}`;let e={draft:`${B.yellow}DRAFT${B.reset}`,approved:`${B.green}APPROVED${B.reset}`,executing:`${B.blue}EXECUTING${B.reset}`,completed:`${B.green}COMPLETED${B.reset}`},s=[];s.push(`
|
|
290
|
+
${B.bold}${B.cyan}Plan: ${t.task}${B.reset}`),s.push(`${B.dim}Status: ${e[t.status]||t.status}${B.reset}
|
|
291
|
+
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${B.green}\u2713${B.reset}`;break;case"in_progress":r=`${B.blue}\u2192${B.reset}`;break;case"skipped":r=`${B.dim}\u25CB${B.reset}`;break;default:r=`${B.dim} ${B.reset}`}s.push(` ${r} ${B.bold}Step ${n+1}:${B.reset} ${o.description}`),o.files.length>0&&s.push(` ${B.dim}Files: ${o.files.join(", ")}${B.reset}`)}return s.push(""),s.join(`
|
|
292
|
+
`)}function sp(t){if(t||(t=re),!t)return null;sc();let e=os.join(rs(),`${t.name}.json`);return dt.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function op(t){let e=os.join(rs(),`${t}.json`);if(!dt.existsSync(e))return null;try{let s=JSON.parse(dt.readFileSync(e,"utf-8"));return re=s,s}catch{return null}}function rp(){sc();let t=rs(),e=dt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(dt.readFileSync(os.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 ip(t){Co=t}function ap(){return Co}function cp(){re=null,Eo=!1,Co=null}function lp(){return`
|
|
293
293
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
294
294
|
|
|
295
295
|
# Allowed Tools (read-only)
|
|
296
|
-
You may ONLY use these tools: ${[...
|
|
296
|
+
You may ONLY use these tools: ${[...nc].join(", ")}
|
|
297
297
|
Any other tool call will be blocked and returned with an error.
|
|
298
298
|
|
|
299
299
|
# Analysis Phase
|
|
@@ -324,42 +324,42 @@ Bullet list of potential issues and mitigations.
|
|
|
324
324
|
# Important
|
|
325
325
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
326
326
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
327
|
-
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var
|
|
328
|
-
`),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${y.dim}${"\u2500".repeat(40)}${y.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";s.push(`${y.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${y.reset}`)}continue}if(n){s.push(` ${
|
|
329
|
-
`)}function
|
|
330
|
-
`)}function
|
|
327
|
+
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var oc=["interactive","semi-auto","autonomous"],rc="interactive";function up(t){return oc.includes(t)?(rc=t,!0):!1}function dp(){return rc}ic.exports={createPlan:Ym,getActivePlan:Xm,setPlanMode:Vm,isPlanMode:Qm,approvePlan:Zm,startExecution:ep,updateStep:tp,formatPlan:np,savePlan:sp,loadPlan:op,listPlans:rp,clearPlan:cp,getPlanModePrompt:lp,setPlanContent:ip,getPlanContent:ap,PLAN_MODE_ALLOWED_TOOLS:nc,setAutonomyLevel:up,getAutonomyLevel:dp,AUTONOMY_LEVELS:oc}});var gc=N((C$,hc)=>{var{C:y}=oe();function fp(t){if(!t)return"";let e=t.split(`
|
|
328
|
+
`),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${y.dim}${"\u2500".repeat(40)}${y.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let a=o?` ${o} `:"";s.push(`${y.dim}${"\u2500".repeat(3)}${a}${"\u2500".repeat(Math.max(0,37-a.length))}${y.reset}`)}continue}if(n){s.push(` ${Ro(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${y.bold}${y.cyan} ${ft(r.substring(4))}${y.reset}`);continue}if(r.startsWith("## ")){s.push(`${y.bold}${y.cyan} ${ft(r.substring(3))}${y.reset}`);continue}if(r.startsWith("# ")){s.push(`${y.bold}${y.cyan}${ft(r.substring(2))}${y.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let a=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,"");s.push(`${a}${y.cyan}\u2022${y.reset} ${mt(c)}`);continue}if(/^\s*\d+\.\s/.test(r)){let a=r.match(/^(\s*)(\d+)\.\s(.*)/);if(a){s.push(`${a[1]}${y.cyan}${a[2]}.${y.reset} ${mt(a[3])}`);continue}}s.push(mt(r))}return s.join(`
|
|
329
|
+
`)}function ft(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function mt(t){return t?t.replace(/`([^`]+)`/g,`${y.cyan}$1${y.reset}`).replace(/\*\*([^*]+)\*\*/g,`${y.bold}$1${y.reset}`).replace(/\*([^*]+)\*/g,`${y.dim}$1${y.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${y.cyan}$1${y.reset} ${y.dim}($2)${y.reset}`):""}function Ro(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?ac(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?cc(t):e==="json"||e==="jsonc"?lc(t):e==="python"||e==="py"?uc(t):e==="go"||e==="golang"?dc(t):e==="rust"||e==="rs"?fc(t):e==="css"||e==="scss"||e==="less"?mc(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?pc(t):t:""}function ac(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,r=t;return r=r.replace(o,`${y.yellow}$1${y.reset}`),r=r.replace(e,`${y.magenta}$1${y.reset}`),r=r.replace(s,`${y.green}$&${y.reset}`),r=r.replace(n,`${y.dim}$1${y.reset}`),r}function cc(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${y.cyan}$1${y.reset}`),r=r.replace(e,`$1${y.green}$2${y.reset}`),r=r.replace(n,`${y.yellow}$&${y.reset}`),r=r.replace(o,`${y.dim}$1${y.reset}`),r}function lc(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${y.cyan}$1${y.reset}:`),r=r.replace(s,`: ${y.green}$1${y.reset}`),r=r.replace(n,`: ${y.yellow}$1${y.reset}`),r=r.replace(o,`: ${y.magenta}$1${y.reset}`),r}function uc(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,r=/^(\s*@\w+)/,a=t;return a=a.replace(o,`${y.yellow}$1${y.reset}`),a=a.replace(e,`${y.magenta}$1${y.reset}`),a=a.replace(r,`${y.cyan}$1${y.reset}`),a=a.replace(s,`${y.green}$&${y.reset}`),a=a.replace(n,`${y.dim}$1${y.reset}`),a}function dc(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=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,a=t;return a=a.replace(r,`${y.yellow}$1${y.reset}`),a=a.replace(s,`${y.cyan}$1${y.reset}`),a=a.replace(e,`${y.magenta}$1${y.reset}`),a=a.replace(n,`${y.green}$&${y.reset}`),a=a.replace(o,`${y.dim}$1${y.reset}`),a}function fc(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=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,a=/\b(\w+!)/g,c=t;return c=c.replace(r,`${y.yellow}$1${y.reset}`),c=c.replace(s,`${y.cyan}$1${y.reset}`),c=c.replace(e,`${y.magenta}$1${y.reset}`),c=c.replace(a,`${y.yellow}$1${y.reset}`),c=c.replace(n,`${y.green}$&${y.reset}`),c=c.replace(o,`${y.dim}$1${y.reset}`),c}function mc(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,r=/(\/\*.*?\*\/|\/\/.*$)/,a=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(a,`${y.yellow}$1${y.reset}`),c=c.replace(o,`${y.yellow}$1${y.reset}`),c=c.replace(e,`$1${y.cyan}$2${y.reset}:`),c=c.replace(n,`$1${y.magenta}$&${y.reset}`),c=c.replace(r,`${y.dim}$1${y.reset}`),c}function pc(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,a=t;return a=a.replace(o,`${y.dim}$1${y.reset}`),a=a.replace(n,`${y.green}$&${y.reset}`),a=a.replace(e,`<${y.magenta}$1${y.reset}`),a=a.replace(s,` ${y.cyan}$1${y.reset}=`),a=a.replace(r,`${y.yellow}$1${y.reset}`),a}function mp(t,e){if(!t||t.length===0)return"";let s=t.map((a,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(a.length,l)}),n=s.map(a=>"\u2500".repeat(a+2)).join("\u253C"),o=t.map((a,c)=>` ${y.bold}${a.padEnd(s[c])}${y.reset} `).join("\u2502"),r=[];r.push(`${y.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${y.reset}`),r.push(`${y.dim}\u2502${y.reset}${o}${y.dim}\u2502${y.reset}`),r.push(`${y.dim}\u251C${n}\u2524${y.reset}`);for(let a of e){let c=t.map((l,u)=>` ${(a[u]||"").padEnd(s[u])} `).join(`${y.dim}\u2502${y.reset}`);r.push(`${y.dim}\u2502${y.reset}${c}${y.dim}\u2502${y.reset}`)}return r.push(`${y.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${y.reset}`),r.join(`
|
|
330
|
+
`)}function pp(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),a=n-r,c=o>=100?y.green:o>50?y.yellow:y.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${y.dim}${"\u2591".repeat(a)}${y.reset} ${o}% (${e}/${s})`}var To=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(`
|
|
331
331
|
`))!==-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(`${y.dim}${"\u2500".repeat(40)}${y.reset}
|
|
332
332
|
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${y.dim}${"\u2500".repeat(40)}${y.reset}
|
|
333
333
|
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${y.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${y.reset}
|
|
334
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
335
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${y.bold}${y.cyan} ${
|
|
336
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${y.bold}${y.cyan} ${
|
|
337
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${y.bold}${y.cyan}${
|
|
338
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${y.cyan}\u2022${y.reset} ${
|
|
339
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${y.cyan}${s[2]}.${y.reset} ${
|
|
340
|
-
`);return}}this._safeWrite(`${
|
|
341
|
-
`)}};
|
|
334
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${Ro(e,this.codeBlockLang)}
|
|
335
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${y.bold}${y.cyan} ${ft(e.substring(4))}${y.reset}
|
|
336
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${y.bold}${y.cyan} ${ft(e.substring(3))}${y.reset}
|
|
337
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${y.bold}${y.cyan}${ft(e.substring(2))}${y.reset}
|
|
338
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${y.cyan}\u2022${y.reset} ${mt(n)}
|
|
339
|
+
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${y.cyan}${s[2]}.${y.reset} ${mt(s[3])}
|
|
340
|
+
`);return}}this._safeWrite(`${mt(e)}
|
|
341
|
+
`)}};hc.exports={renderMarkdown:fp,renderInline:mt,stripHeadingMarkers:ft,highlightCode:Ro,highlightJS:ac,highlightBash:cc,highlightJSON:lc,highlightPython:uc,highlightGo:dc,highlightRust:fc,highlightCSS:mc,highlightHTML:pc,renderTable:mp,renderProgress:pp,StreamRenderer:To}});var Mo=N((T$,bc)=>{var{execSync:hp}=require("child_process"),Ao=require("path"),ln=require("fs"),Oo=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function $c(){return Ao.join(process.cwd(),".nex","hooks")}function gp(){return Ao.join(process.cwd(),".nex","config.json")}function yc(){let t=gp();if(!ln.existsSync(t))return{};try{return JSON.parse(ln.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function is(t){if(!Oo.includes(t))return[];let e=[],s=$c(),n=Ao.join(s,t);ln.existsSync(n)&&e.push(n);let o=yc();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function wc(t,e={},s=3e4){try{return{success:!0,output:hp(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 $p(t,e={}){let s=is(t);if(s.length===0)return[];let n={};for(let[r,a]of Object.entries(e))n[`NEX_${r.toUpperCase()}`]=String(a);let o=[];for(let r of s){let a=wc(r,n);if(o.push({command:r,...a}),!a.success&&t.startsWith("pre-"))break}return o}function yp(t){return is(t).length>0}function wp(){let t=[];for(let e of Oo){let s=is(e);s.length>0&&t.push({event:e,commands:s})}return t}function bp(){let t=$c();return ln.existsSync(t)||ln.mkdirSync(t,{recursive:!0}),t}bc.exports={HOOK_EVENTS:Oo,loadHookConfig:yc,getHooksForEvent:is,executeHook:wc,runHooks:$p,hasHooks:yp,listHooks:wp,initHooksDir:bp}});var ie=N((O$,Mc)=>{var{C:S,Spinner:Ot,TaskProgress:xp,formatToolCall:_p,formatResult:kp,formatToolSummary:Sc,formatSectionHeader:vp,setActiveTaskProgress:R$}=oe(),{callStream:Sp}=fe(),{parseToolArgs:Ep}=Rn(),{executeTool:Cp}=Fe(),{gatherProjectContext:Tp}=wo(),{fitToContext:Rp,forceCompress:No,getUsage:Ap,estimateTokens:Op}=Te(),{autoSave:pt}=lt(),{getMemoryContext:Mp}=Ve(),{checkPermission:Np,setPermission:Pp,savePermissions:Lp}=cn(),{confirm:Ec,setAllowAlwaysHandler:Ip}=Oe(),{isPlanMode:ds,getPlanModePrompt:qp,PLAN_MODE_ALLOWED_TOOLS:Cc,setPlanContent:jp}=At(),{StreamRenderer:Dp}=gc(),{runHooks:xc}=Mo(),{routeMCPCall:Fp,getMCPToolDefinitions:Up}=Pn(),{getSkillInstructions:Wp,getSkillToolDefinitions:Bp,routeSkillCall:Hp}=Ht(),{trackUsage:Gp}=xt(),{validateToolArgs:zp}=Ws(),{filterToolsForModel:_c,getModelTier:Kp,PROVIDER_DEFAULT_TIER:A$}=eo(),{getConfiguredProviders:Jp,getActiveProviderName:Yp,getActiveModelId:Xp}=fe(),Wo=require("fs"),Bo=require("path"),kc=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function Vp(t){let e=[],s;for(kc.lastIndex=0;(s=kc.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):Bo.resolve(n);Wo.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Qp(t){let e=Wo.readFileSync(t),s=Bo.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 Tc(t){let e=Vp(t);if(e.length===0)return t;let s=[{type:"text",text:t}];for(let n of e)try{let{data:o,media_type:r}=Qp(n.abs);s.push({type:"image",media_type:r,data:o})}catch{}return s.length>1?s:t}var Po=null,Lo=null,Io=null;function Mt(){if(Po===null){let{TOOL_DEFINITIONS:t}=Fe();Po=t}return Lo===null&&(Lo=Bp()),Io===null&&(Io=Up()),[...Po,...Lo,...Io]}var Fo=50;function Zp(t){Number.isFinite(t)&&t>0&&(Fo=t)}var cs=()=>null;function eh(t){cs=t}var un=null,Uo=null,Nt=null,ls=new Map,th=1e4,nh=6e3,sh=/\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 oh(t){return!t||typeof t!="string"?t:t.replace(sh,(e,s)=>`${s}=***REDACTED***`)}function rh(t){let e=oh(t);if(Op(e)>th)try{let{compressToolResult:n}=Te();return n(e,nh)}catch{return e}return e}function Rc(t){try{let{getActiveModel:e}=fe(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(ls.has(n))return ls.get(n);let o=_c(t);return ls.set(n,o),o}catch{return _c(t)}}function ih(){ls.clear()}async function Ac(){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(r=>t.stat(r).then(a=>`${r}:${a.mtimeMs}`)))).filter(r=>r.status==="fulfilled").map(r=>r.value);try{let{getMemoryContextHash:r}=Ve(),a=r();a&&o.push(`memory:${a}`)}catch{}try{let r=e.join(process.cwd(),".nex","brain");if(Wo.existsSync(r)){let a=await t.stat(r);o.push(`brain:${a.mtimeMs}`)}}catch{}return o.join("|")}catch{return`fallback:${Date.now()}`}}function ah(){un=null,Uo=null,Nt=null}var ch=new Set(["spawn_agents"]),qo=5,jo=3,as=2,lh=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),uh=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10);function dh(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{}}Ip(t=>{Pp(t,"allow"),Lp(),console.log(`${S.green} \u2713 ${t}: always allow${S.reset}`)});async function fh(t){let e=t.function.name,s=Ep(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let l=Mt().find(d=>d.function.name===e),u=l?JSON.stringify(l.function.parameters,null,2):"unknown";return console.log(`${S.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${S.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
342
342
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
343
343
|
|
|
344
344
|
Expected JSON schema for "${e}":
|
|
345
345
|
${u}
|
|
346
346
|
|
|
347
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=
|
|
348
|
-
`)[0]}${
|
|
347
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=zp(e,s);if(!o.valid)return console.log(`${S.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
348
|
+
`)[0]}${S.reset}`),{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:o.error,tool_call_id:n}};let r=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(`${S.dim} \u2713 ${e}: corrected args (${u.join(", ")})${S.reset}`)}if(ds()&&!Cc.has(e))return console.log(`${S.yellow} \u2717 ${e}: blocked in plan mode${S.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`PLAN MODE: '${e}' is blocked. Only read-only tools are allowed. Present your plan as text output instead of making changes.`,tool_call_id:n}};let a=Np(e);if(a==="deny")return console.log(`${S.red} \u2717 ${e}: denied by permissions${S.reset}`),{callId:n,fnName:e,args:r,canExecute:!1,errorResult:{role:"tool",content:`DENIED: Tool '${e}' is blocked by permissions`,tool_call_id:n}};if(a==="ask"){let c=` Allow ${e}?`;return e==="bash"&&r.command&&(c=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await Ec(c,{toolName:e})?{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}:{callId:n,fnName:e,args:r,canExecute:!1,confirmedByUser:!1,errorResult:{role:"tool",content:`CANCELLED: User declined ${e}`,tool_call_id:n}}}return{callId:n,fnName:e,args:r,canExecute:!0,confirmedByUser:!0,errorResult:null}}async function mh(t,e,s={}){let n=await Hp(t,e);if(n!==null)return n;let o=await Fp(t,e);return o!==null?o:Cp(t,e,s)}function ph(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 Do(t,e=!1){e||console.log(_p(t.fnName,t.args)),xc("pre-tool",{tool_name:t.fnName});let s=await mh(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(s??""),o=n.length>5e4?n.substring(0,5e4)+`
|
|
349
349
|
...(truncated ${n.length-5e4} chars)`:n,r=o.split(`
|
|
350
|
-
`)[0],a=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),c=
|
|
351
|
-
`)}function
|
|
350
|
+
`)[0],a=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),c=Sc(t.fnName,t.args,o,a);return e||(console.log(kp(o)),console.log(c)),xc("post-tool",{tool_name:t.fnName}),{msg:{role:"tool",content:rh(o),tool_call_id:t.callId},summary:c}}async function hh(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],a=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=ph(d.fnName,d.args);u=`\u23FA ${d.fnName}${f?`(${f})`:""}`}else{let d=l.map(f=>f.fnName).join(", ");u=`\u23FA ${l.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}a=new Ot(u),a.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await Do(t[l],e);n[l]=u,o.push(d)}else{let l=r.map(d=>Do(t[d],e)),u=await Promise.all(l);for(let d=0;d<r.length;d++)n[r[d]]=u[d].msg,o.push(u[d].summary)}r=[]}}for(let l=0;l<t.length;l++){let u=t[l];if(!u.canExecute){await c(),n[l]=u.errorResult,o.push(Sc(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(ch.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&a&&(a.stop(),a=null);let{msg:d,summary:f}=await Do(u,e);n[l]=d,o.push(f)}else r.push(l)}if(await c(),a&&a.stop(),e&&o.length>0&&!s.skipSummaries)for(let l of o)console.log(l);return{results:n,summaries:o}}var se=[],vc=300,us=[];function gh(t){us.push(t.trim())}function $h(){return us.length===0?null:us.splice(0,us.length).join(`
|
|
351
|
+
`)}function yh(){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)
|
|
352
352
|
`];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 r=e||(n?"English":null);r&&o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let a=s||(n?"English":null);return a&&o.push(`COMMIT MESSAGES: Write all git commit messages in ${a}.`),n&&o.push(`
|
|
353
353
|
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(`
|
|
354
354
|
`)+`
|
|
355
355
|
|
|
356
|
-
`}function
|
|
356
|
+
`}function wh(){if(Nt!==null)return Nt;try{let e=Jp().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:Kp(r.id,o.name),name:r.name})));if(e.length<2)return Nt="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
|
|
357
357
|
# Sub-Agent Model Routing
|
|
358
358
|
|
|
359
359
|
`;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 |
|
|
360
360
|
|---|---|---|
|
|
361
361
|
`;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
|
|
362
|
-
`;return
|
|
362
|
+
`;return Nt=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Nt="",""}}async function Oc(){let t=await Ac();if(un!==null&&t===Uo)return un;let e=await Tp(process.cwd()),s=Mp(),n=Wp(),o=ds()?qp():"",r=yh();return un=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
|
|
363
363
|
|
|
364
364
|
WORKING DIRECTORY: ${process.cwd()}
|
|
365
365
|
All relative paths resolve from this directory.
|
|
@@ -455,7 +455,7 @@ After completing multi-step tasks, suggest logical next steps (e.g. "You can run
|
|
|
455
455
|
- Good for: reading multiple files, analyzing separate modules.
|
|
456
456
|
- Bad for: tasks that depend on each other or modify the same file.
|
|
457
457
|
- Max 5 parallel agents.
|
|
458
|
-
${
|
|
458
|
+
${wh()}
|
|
459
459
|
|
|
460
460
|
# Edit Reliability (Critical)
|
|
461
461
|
|
|
@@ -506,17 +506,19 @@ You have access to a persistent knowledge base in .nex/brain/.
|
|
|
506
506
|
- Include tags in frontmatter for better retrieval
|
|
507
507
|
- The user reviews all brain writes via /brain review or git diff
|
|
508
508
|
|
|
509
|
-
`,
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
`),
|
|
517
|
-
`);
|
|
509
|
+
`,Uo=t,un}function bh(){se=[]}function xh(){se.length>vc&&se.splice(0,se.length-vc)}function _h(){return se.length}function kh(){return se}function vh(t){se=t}async function Sh(){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/*"])]),r=new Set(["js","ts","jsx","tsx","py","go","rs","rb","java","cpp","c","cs"]),a=(o?o.split(`
|
|
510
|
+
`):[]).filter(f=>{let m=f.split(".").pop();return r.has(m)});if(a.length<3)return null;let c={};for(let f of a){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=Bo.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+=`
|
|
511
|
+
\u{1F4E6} ${h}${p}`}}catch{}return u}function ht(t,e,s,n,o){if(t<1)return;let r=[...e.values()].reduce((c,l)=>c+l,0),a=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${r} ${r===1?"tool":"tools"}`;if(s.size>0&&(a+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),o){let c=Date.now()-o,l=Math.round(c/1e3);a+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}a+=" \u2500\u2500",console.log(`
|
|
512
|
+
${S.dim} ${a}${S.reset}`),s.size>0?console.log(`${S.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${S.reset}`):n.size>0&&t>=2&&console.log(`${S.dim} \u{1F4A1} /save \xB7 /clear${S.reset}`)}async function Eh(t){let e=Tc(t);se.push({role:"user",content:e}),xh();let{setOnChange:s}=Hn(),n=null,o=0;s((ce,A)=>{ce==="create"?(n&&n.stop(),n=new xp(A.name,A.tasks),n.setStats({tokens:o}),n.start()):ce==="update"&&n?n.updateTask(A.id,A.status):ce==="clear"&&n&&(n.stop(),n=null)});let r=await Oc(),a=r;try{let{getBrainContext:ce}=tn(),A=await ce(t);A&&(a=r+`
|
|
513
|
+
`+A+`
|
|
514
|
+
`)}catch(ce){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",ce.message)}let c=[{role:"system",content:a},...se],l=new Ot("Thinking...");l.start();let d=se.length===1?Sh().catch(()=>null):Promise.resolve(null),f=Mt(),[{messages:m,compressed:h,compacted:p,tokensRemoved:g},w]=await Promise.all([Rp(c,f),d]),$=Ap(c,f);if(l.stop(),w&&console.log(`${S.dim}${w}${S.reset}`),p)console.log(`${S.dim} [context compacted \u2014 summary (~${g} tokens freed)]${S.reset}`);else if(h){let ce=$.limit>0?Math.round(g/$.limit*100):0;console.log(`${S.dim} [context compressed \u2014 ~${g} tokens freed (${ce}%)]${S.reset}`)}$.percentage>85&&console.log(`${S.yellow} \u26A0 Context ${Math.round($.percentage)}% full \u2014 consider /clear or /save + start fresh${S.reset}`);let x=m,O=0,_=0,k=0,C=0,v=0,T=new Map,F=new Set,q=new Set,Q=Date.now(),j,Y=Fo,qe=0,me=10;e:for(;;){for(j=0;j<Y&&!cs()?.aborted;j++){let A=!0,L=null;if(n&&n.isActive())n._paused&&n.resume();else if(!n){let E=v>0?`Thinking... (step ${v+1})`:"Thinking...";L=new Ot(E),L.start()}let ne=!0,z="",I=new Dp,U,H=Date.now(),le=!1,tt=new AbortController,pn=setInterval(()=>{let E=Date.now()-H;E>=uh?(I._clearCursorLine(),console.log(`${S.yellow} \u26A0 Stream stale for ${Math.round(E/1e3)}s \u2014 aborting and retrying${S.reset}`),tt.abort()):E>=lh&&!le&&(le=!0,I._clearCursorLine(),console.log(`${S.yellow} \u26A0 No tokens received for ${Math.round(E/1e3)}s \u2014 waiting...${S.reset}`))},5e3),ge="",Ee=null;try{let E=Rc(Mt()),D=ds()?E.filter(de=>Cc.has(de.function.name)):E,gt=cs(),W=new AbortController;gt&>.addEventListener("abort",()=>W.abort(),{once:!0}),tt.signal.addEventListener("abort",()=>W.abort(),{once:!0}),U=await Sp(x,D,{signal:W.signal,onToken:de=>{H=Date.now(),le=!1,ge+=de,process.stdout.isTTY?Ee||(Ee=setTimeout(()=>{ge&&I&&I.push(ge),ge="",Ee=null},50)):(I.push(ge),ge=""),ne&&(n&&!n._paused?n.pause():L&&L.stop(),A||(A=!0),I.startCursor(),ne=!1),z+=de}})}catch(E){if(clearInterval(pn),Ee&&(clearTimeout(Ee),Ee=null),ge&&I&&(I.push(ge),ge=""),n&&!n._paused&&n.pause(),L&&L.stop(),I.stopCursor(),tt.signal.aborted&&!cs()?.aborted){if(k++,k>as){if(C<1){C++,console.log(`${S.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${S.reset}`);let Ce=Mt(),{messages:qt,tokensRemoved:jt}=No(x,Ce);x=qt,console.log(`${S.dim} [force-compressed \u2014 ~${jt} tokens freed]${S.reset}`),k=0,j--;continue}console.log(`${S.red} \u2717 Stream stale: max retries (${as}) exceeded. The model may be overloaded \u2014 try again or switch models.${S.reset}`),n&&(n.stop(),n=null),s(null),ht(v,T,F,q,Q),pt(se);break}let W=k===1?3e3:5e3;if(k>=2&&C<1){C++,console.log(`${S.yellow} \u26A0 Stale retry ${k}/${as} \u2014 force-compressing before retry...${S.reset}`);let Ce=Mt(),{messages:qt,tokensRemoved:jt}=No(x,Ce);x=qt,console.log(`${S.dim} [force-compressed \u2014 ~${jt} tokens freed]${S.reset}`)}else console.log(`${S.yellow} \u26A0 Stale retry ${k}/${as} \u2014 retrying in ${W/1e3}s...${S.reset}`);let de=new Ot(`Waiting ${W/1e3}s before retry...`);de.start(),await new Promise(Ce=>setTimeout(Ce,W)),de.stop(),j--;continue}if(E.name==="AbortError"||E.name==="CanceledError"||E.message?.includes("canceled")||E.message?.includes("aborted")){n&&(n.stop(),n=null),s(null),ht(v,T,F,q,Q),pt(se);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 W=(E.message||"").toLowerCase(),de=W.includes("context")||W.includes("token")||W.includes("length")||W.includes("too long")||W.includes("too many")||W.includes("prompt")||W.includes("size")||W.includes("exceeds")||W.includes("num_ctx")||W.includes("input");if(de&&C<1){C++,console.log(`${S.yellow} \u26A0 Context too long \u2014 force-compressing and retrying...${S.reset}`);let Ce=Mt(),{messages:qt,tokensRemoved:jt}=No(x,Ce);x=qt,console.log(`${S.dim} [force-compressed \u2014 ~${jt} tokens freed]${S.reset}`),j--;continue}de?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(`${S.red} \u2717 ${D}${S.reset}`),E.message.includes("429")){if(O++,O>qo){console.log(`${S.red} Rate limit: max retries (${qo}) exceeded. Try again later or use /budget to check your limits.${S.reset}`),n&&(n.stop(),n=null),s(null),ht(v,T,F,q,Q),pt(se);break}let W=Math.min(1e4*Math.pow(2,O-1),12e4),de=new Ot(`Rate limit \u2014 waiting ${Math.round(W/1e3)}s (retry ${O}/${qo})`);de.start(),await new Promise(Ce=>setTimeout(Ce,W)),de.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(_++,_>jo){console.log(`${S.red} Network error: max retries (${jo}) exceeded. Check your connection and try again.${S.reset}`),n&&(n.stop(),n=null),s(null),ht(v,T,F,q,Q),pt(se);break}let W=Math.min(2e3*Math.pow(2,_-1),3e4),de=new Ot(`Network error \u2014 retrying in ${Math.round(W/1e3)}s (${_}/${jo})`);de.start(),await new Promise(Ce=>setTimeout(Ce,W)),de.stop(),j--;continue}n&&(n.stop(),n=null),s(null),ht(v,T,F,q,Q),pt(se);break}clearInterval(pn),ne&&(n&&!n._paused&&n.pause(),L&&L.stop()),Ee&&(clearTimeout(Ee),Ee=null),ge&&I&&(I.push(ge),ge=""),z&&I.flush(),_=0,k=0,U&&U.usage&&(Gp(Yp(),Xp(),U.usage.prompt_tokens||0,U.usage.completion_tokens||0),o+=(U.usage.prompt_tokens||0)+(U.usage.completion_tokens||0),n&&n.setStats({tokens:o}));let{content:gs,tool_calls:nt}=U,$s={role:"assistant",content:gs||""};if(nt&&nt.length>0&&($s.tool_calls=nt),se.push($s),x.push($s),!nt||nt.length===0){let E=(gs||"").trim().length>0||z.trim().length>0;if(!E&&v>0&&j<Fo-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."};x.push(D);continue}if(ds()&&E){let D=(gs||z||"").trim();jp(D),dh(D),console.log(`
|
|
515
|
+
${S.cyan}${S.bold}Plan ready.${S.reset} ${S.dim}Type ${S.reset}${S.cyan}/plan approve${S.reset}${S.dim} to execute, or ask follow-up questions to refine.${S.reset}`)}n&&(n.stop(),n=null),s(null),ht(v,T,F,q,Q),pt(se);return}v++,v>1&&(A=!1);for(let E of nt){let D=E.function.name;T.set(D,(T.get(D)||0)+1)}let hn=await Promise.all(nt.map(E=>fh(E))),ys=n?{skipSpinner:!0,skipSummaries:!0}:{},cr=!ys.skipSummaries&&!A;cr&&(A=!0),n&&n._paused&&n.resume();let{results:lr,summaries:gn}=await hh(hn,!0,{...ys,skipSummaries:!0});if(!ys.skipSummaries)if(cr){let E=vp(hn,v);if(gn.length===1)console.log(E+gn[0]);else{console.log(E);for(let D of gn)console.log(D)}}else for(let E of gn)console.log(E);for(let E=0;E<hn.length;E++){let D=hn[E];if(!D.canExecute)continue;let gt=lr[E].content,W=!gt.startsWith("ERROR")&&!gt.includes("CANCELLED");W&&["write_file","edit_file","patch_file"].includes(D.fnName)&&D.args&&D.args.path&&F.add(D.args.path),W&&D.fnName==="read_file"&&D.args&&D.args.path&&q.add(D.args.path)}for(let E of lr)se.push(E),x.push(E);let ur=$h();if(ur){let E={role:"user",content:`[User note mid-run]: ${ur}`};se.push(E),x.push(E),console.log(`${S.cyan} \u270E Kontext hinzugef\xFCgt${S.reset}`)}}if(j>=Y){n&&(n.stop(),n=null),s(null),ht(v,T,F,q,Q),pt(se);let{getActiveProviderName:ce}=fe();if(ce()==="ollama"&&qe<me){qe++,Y+=20,console.log(`${S.dim} \u2500\u2500 auto-extending to ${Y} turns \u2500\u2500${S.reset}`);continue e}if(console.log(`
|
|
516
|
+
${S.yellow}\u26A0 Max iterations (${Y}) reached.${S.reset}`),await Ec(" Continue for 20 more turns?")){Y+=20;continue e}console.log(`${S.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${S.reset}`)}break e}}Mc.exports={processInput:Eh,clearConversation:bh,getConversationLength:_h,getConversationMessages:kh,setConversationMessages:vh,setAbortSignalGetter:eh,setMaxIterations:Zp,invalidateSystemPromptCache:ah,clearToolFilterCache:ih,getCachedFilteredTools:Rc,buildSystemPrompt:Oc,getProjectContextHash:Ac,buildUserContent:Tc,injectMidRunNote:gh}});var fe=N((M$,jc)=>{var{OllamaProvider:Ch}=Tr(),{OpenAIProvider:Th}=Kr(),{AnthropicProvider:Rh}=Vr(),{GeminiProvider:Ah}=ti(),{LocalProvider:Oh}=oi(),{checkBudget:Mh}=xt(),Nc={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"}},Pc={};for(let[t,e]of Object.entries(Nc))for(let s of Object.values(e))Pc[s]=t;function Lc(t,e){let s=Pc[t];return s&&Nc[s][e]||t}var ue={},be=null,ae=null,dn=[];function Se(){if(Object.keys(ue).length>0)return;Pt("ollama",new Ch),Pt("openai",new Th),Pt("anthropic",new Rh),Pt("gemini",new Ah),Pt("local",new Oh);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;ue[t]?(be=t,ae=e||ue[t].defaultModel):(be="ollama",ae="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(dn=s.split(",").map(n=>n.trim()).filter(Boolean))}function Pt(t,e){ue[t]=e}function Nh(t){return Se(),ue[t]||null}function Ho(){return Se(),ue[be]||null}function Ph(){return Se(),be}function Lh(){return Se(),ae}function Ih(){Se();let t=Ho();if(!t)return{id:ae,name:ae,provider:be};let e=t.getModel(ae);return e?{...e,provider:be}:{id:ae,name:ae,provider:be}}function Ic(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(ue[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function qh(t){Se();let{provider:e,model:s}=Ic(t);if(e){let o=ue[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(be=e,ae=s,fs(),!0):!1}let n=Ho();if(n&&n.getModel(s))return ae=s,fs(),!0;for(let[o,r]of Object.entries(ue))if(r.getModel(s))return be=o,ae=s,fs(),!0;return!1}function fs(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=ie();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Te();t()}catch{}}function jh(){Se();let t=new Set;for(let e of Object.values(ue))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function Dh(){return Se(),Object.entries(ue).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===be&&s.id===ae}))}))}function Fh(){Se();let t=[];for(let[e,s]of Object.entries(ue)){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 Uh(t){dn=Array.isArray(t)?t:[]}function Wh(){return[...dn]}function Bh(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 qc(t){let e=[be,...dn.filter(r=>r!==be)],s,n=0,o=0;for(let r=0;r<e.length;r++){let a=e[r],c=ue[a];if(!c||!c.isConfigured())continue;o++;let l=Mh(a);if(!l.allowed){n++,s=new Error(`Budget limit reached for ${a}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?Lc(ae,a):ae;return u&&d!==ae&&process.stderr.write(` [fallback: ${a}:${d}]
|
|
517
|
+
`),await t(c,a,d)}catch(u){if(s=u,Bh(u)&&r<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 Hh(t,e,s={}){return Se(),qc((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function Gh(t,e,s={}){if(Se(),s.provider){let n=ue[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||ae,...s};try{return await n.chat(t,e,o)}catch(r){if(typeof n.stream=="function")try{return await n.stream(t,e,{...o,onToken:()=>{}})}catch{}throw r}}return qc(async(n,o,r)=>{try{return await n.chat(t,e,{model:r,...s})}catch(a){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw a}})}function zh(){Se();let t=[];for(let[e,s]of Object.entries(ue))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function Kh(){for(let t of Object.keys(ue))delete ue[t];be=null,ae=null,dn=[]}jc.exports={registerProvider:Pt,getProvider:Nh,getActiveProvider:Ho,getActiveProviderName:Ph,getActiveModelId:Lh,getActiveModel:Ih,setActiveModel:qh,getModelNames:jh,parseModelSpec:Ic,listProviders:Dh,listAllModels:Fh,callStream:Hh,callChat:Gh,getConfiguredProviders:zh,setFallbackChain:Uh,getFallbackChain:Wh,resolveModelForProvider:Lc,_reset:Kh}});var Wc=N((N$,Uc)=>{"use strict";var Dc="\x1B[2m",Fc="\x1B[0m";function Jh(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Go=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 Dc+"\u2500".repeat(this._cols)+Fc}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(l,...u){if(s._active&&typeof l=="string"){if(s._cursorOnInputRow){let f=l.replace(/\n/g,"");return f?n(f,...u):!0}let d=(l.match(/\n/g)||[]).length;d>0&&(s._lastOutputRow=Math.min(s._lastOutputRow+d,s._scrollEnd))}return n(l,...u)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(l,...u){if(!s._active)return s._origStderrWrite(l,...u);if(typeof l=="string"&&l.includes("\r")){let d=Math.min(s._lastOutputRow+1,s._scrollEnd);s._origWrite(s._goto(d))}return s._origStderrWrite(l,...u)},this._origLog=console.log,this._origError=console.error;function o(...l){if(!s._active){s._origLog(...l);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origLog(...l),s.drawFooter()}function r(...l){if(!s._active){s._origError(...l);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origError(...l),s.drawFooter()}console.log=o,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(l){s._origSetPr(l),s._active&&s.drawFooter(l)},this._origPrompt=e.prompt.bind(e),e.prompt=function(l){if(!s._active)return s._origPrompt(l);e._prevPos=null,s._origWrite(s._goto(s._rowInput)),s._origPrompt(l),s._cursorOnInputRow=!0};let a=e._refreshLine?e._refreshLine.bind(e):null;this._origRefreshLine=a,a&&(e._refreshLine=function(){if(!s._active)return a();let l=s._cols,u=Jh(e._prompt||""),d=l-u-1;if(e.line.length<=d)return a();let f=e.line,m=e.cursor,h=Math.max(1,d-1),g=Math.max(0,m-h),w=(g>0?"\xAB":"")+f.slice(g,g+h+(g>0?0:1));e.line=w,e.cursor=w.length,a(),e.line=f,e.cursor=m}),e.on("line",l=>{s._active&&(s._cursorOnInputRow=!1,s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),l&&l.trim()&&process.stdout.write(Dc+"\u203A "+l+Fc+`
|
|
518
|
+
`),s.drawFooter())});let c=()=>{this._setScrollRegion(),this.drawFooter()};process.stdout.on("resize",c),this._offResize=()=>process.stdout.off("resize",c)}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)}};Uc.exports={StickyFooter:Go}});var Gc=N((P$,Hc)=>{var{C:J}=oe(),{listProviders:Yh,getActiveProviderName:Xh,getActiveModelId:Vh,setActiveModel:Qh}=fe();function Bc(t,e,s={}){let{title:n="Select",hint:o="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=s;return new Promise(r=>{let a=e.map(($,x)=>$.isHeader?-1:x).filter($=>$>=0);if(a.length===0){r(null);return}let c=e.findIndex($=>$.isCurrent),l=c>=0?a.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 $=a[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 k=0;k<m;k++)process.stdout.write(`\x1B[2K
|
|
519
|
+
`);process.stdout.write(`\x1B[${m}A`)}let $=[];$.push(` ${J.bold}${J.cyan}${n}${J.reset}`),$.push(` ${J.dim}${o}${J.reset}`),$.push("");let{start:x,end:O}=f();x>0&&$.push(` ${J.dim}\u2191 more${J.reset}`);for(let k=x;k<O;k++){let C=e[k];if(C.isHeader){$.push(` ${J.bold}${J.dim}${C.label}${J.reset}`);continue}let v=a[l]===k,T=v?`${J.cyan}> `:" ",F=C.isCurrent?` ${J.yellow}<current>${J.reset}`:"";v?$.push(`${T}${J.bold}${C.label}${J.reset}${F}`):$.push(`${T}${J.dim}${C.label}${J.reset}${F}`)}O<e.length&&$.push(` ${J.dim}\u2193 more${J.reset}`);let _=$.join(`
|
|
518
520
|
`);process.stdout.write(_+`
|
|
519
|
-
`),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",w),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function w($,x){if(x){if(x.name==="up"||x.ctrl&&x.name==="p"){l>0&&(l--,h());return}if(x.name==="down"||x.ctrl&&x.name==="n"){l<a.length-1&&(l++,h());return}if(x.name==="return"){let
|
|
521
|
+
`),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",w),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function w($,x){if(x){if(x.name==="up"||x.ctrl&&x.name==="p"){l>0&&(l--,h());return}if(x.name==="down"||x.ctrl&&x.name==="n"){l<a.length-1&&(l++,h());return}if(x.name==="return"){let O=e[a[l]];g(),r(O?O.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",w),h()})}async function Zh(t){let e=Yh(),s=Xh(),n=Vh(),o=[];for(let a of e)if(a.models.length!==0){o.push({label:a.provider,value:null,isHeader:!0});for(let c of a.models){let l=a.provider===s&&c.id===n;o.push({label:` ${c.name} (${a.provider}:${c.id})`,value:`${a.provider}:${c.id}`,isCurrent:l})}}let r=await Bc(t,o,{title:"Select Model"});return r?(Qh(r),console.log(`${J.green}Switched to ${r}${J.reset}`),!0):(console.log(`${J.dim}Cancelled${J.reset}`),!1)}Hc.exports={pickFromList:Bc,showModelPicker:Zh}});var Jo=N((I$,Qc)=>{var zo=require("fs"),eg=require("path"),{callChat:zc}=fe(),{remember:tg,listMemories:L$,recall:ng}=Ve(),Ko=4,sg=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
520
522
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
521
523
|
|
|
522
524
|
Return ONLY valid JSON in this exact format:
|
|
@@ -542,15 +544,15 @@ Rules:
|
|
|
542
544
|
- value: concise actionable instruction, max 120 chars
|
|
543
545
|
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
544
546
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
545
|
-
- Return ONLY the JSON, no markdown, no explanation`;function
|
|
547
|
+
- Return ONLY the JSON, no markdown, no explanation`;function Kc(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(`
|
|
546
548
|
|
|
547
|
-
`)}async function
|
|
549
|
+
`)}async function Jc(t){if(t.filter(o=>o.role==="user").length<Ko)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=Kc(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=[{role:"system",content:sg},{role:"user",content:`Conversation to analyze:
|
|
548
550
|
|
|
549
|
-
${s}`}];try{let a=((await
|
|
551
|
+
${s}`}];try{let a=((await zc(n,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!a)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let c=JSON.parse(a[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 Yc(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),r=n.trim().substring(0,200);if(!o||!r)continue;let a=ng(o);a!==r&&(tg(o,r),e.push({key:o,value:r,action:a?"updated":"added"}))}return e}function Xc(t){if(!t||t.length===0)return[];let e=eg.join(process.cwd(),"NEX.md"),s="";try{zo.existsSync(e)&&(s=zo.readFileSync(e,"utf-8"))}catch{}let n=[],o=s;for(let r of t){if(!r||typeof r!="string")continue;let a=r.trim();if(!a)continue;let c=a.substring(0,35).toLowerCase();s.toLowerCase().includes(c)||(n.push(a),o=o?o.endsWith(`
|
|
550
552
|
`)?o+a:o+`
|
|
551
553
|
`+a:a)}return n.length>0&&(o.endsWith(`
|
|
552
554
|
`)||(o+=`
|
|
553
|
-
`),
|
|
555
|
+
`),zo.writeFileSync(e,o,"utf-8")),n}async function og(t){let e=await Jc(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=Yc(e.memories),n=Xc(e.nex_additions);return{applied:s,nexAdded:n,summary:e.summary}}var rg=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
554
556
|
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
555
557
|
|
|
556
558
|
Return ONLY valid JSON in this exact format:
|
|
@@ -584,37 +586,37 @@ Rules:
|
|
|
584
586
|
---
|
|
585
587
|
- Maximum 3 documents per session. Quality over quantity.
|
|
586
588
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
587
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function
|
|
589
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function Vc(t){if(t.filter(o=>o.role==="user").length<Ko)return{documents:[],skip_reason:"Session too short"};let s=Kc(t);if(!s.trim())return{documents:[],skip_reason:"No usable content"};let n=[{role:"system",content:rg},{role:"user",content:`Conversation to analyze:
|
|
588
590
|
|
|
589
|
-
${s}`}];try{let a=((await
|
|
591
|
+
${s}`}];try{let a=((await zc(n,[],{temperature:0,maxTokens:2e3})).content||"").trim().match(/\{[\s\S]*\}/);if(!a)return{documents:[],error:"No JSON in response"};let c=JSON.parse(a[0]);return{documents:Array.isArray(c.documents)?c.documents:[],skip_reason:c.skip_reason}}catch(o){return{documents:[],error:o.message}}}async function ig(t){let e=await Vc(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}=tn(),o=[],r=[];for(let a of e.documents){if(!a.name||!a.content)continue;let c=a.name.trim().replace(/\.md$/,"").replace(/[^a-z0-9-]/g,"-").substring(0,60);if(!c)continue;let l=n(c);if(l.content){let d=`
|
|
590
592
|
|
|
591
593
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
592
594
|
|
|
593
|
-
${a.content}`;s(c,l.content+d),o.push({name:c,reason:a.reason||"",action:"updated"})}else s(c,a.content),o.push({name:c,reason:a.reason||"",action:"created"})}return{written:o,skipped:r}}
|
|
594
|
-
${
|
|
595
|
-
`);let n=Object.keys(s);if(n.length>0&&(console.log(`${
|
|
595
|
+
${a.content}`;s(c,l.content+d),o.push({name:c,reason:a.reason||"",action:"updated"})}else s(c,a.content),o.push({name:c,reason:a.reason||"",action:"created"})}return{written:o,skipped:r}}Qc.exports={learnFromSession:og,learnBrainFromSession:ig,reflectOnSession:Jc,reflectBrain:Vc,applyMemories:Yc,applyNexAdditions:Xc,LEARN_MIN_MESSAGES:Ko}});var sl=N((j$,nl)=>{var he=require("fs"),It=require("path"),q$=require("os"),ag=require("readline"),{C:R}=oe(),Zc=".nex",Yo=null;function cg(t){Yo=t}function _e(t,e=""){let s=e?` ${R.dim}[${e}]${R.reset}`:"",n=` ${R.cyan}${t}${s}${R.reset}: `;return new Promise(o=>{let r=a=>{let c=a.trim()||e;o(c)};if(Yo)Yo.question(n,r);else{let a=ag.createInterface({input:process.stdin,output:process.stdout});a.question(n,c=>{a.close(),r(c)})}})}function Lt(t,e=!0){return _e(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(n=>n.toLowerCase()!=="n"&&n.toLowerCase()!=="no")}async function el(t,e,s){let n=e.map((c,l)=>`${R.dim}${l+1})${R.reset} ${c}`).join(" ");console.log(` ${R.cyan}${t}${R.reset}`),console.log(` ${n}`);let o=s?e.indexOf(s)+1:1,r=await _e("Enter number",String(o)),a=parseInt(r,10)-1;return e[Math.max(0,Math.min(a,e.length-1))]}async function lg(){let t=It.join(process.cwd(),Zc),e=It.join(t,"servers.json"),s={};if(he.existsSync(e))try{s=JSON.parse(he.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
596
|
+
${R.bold}${R.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${R.reset}`),console.log(`${R.bold}${R.cyan}\u2551 nex-code Server Setup Wizard \u2551${R.reset}`),console.log(`${R.bold}${R.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${R.reset}
|
|
597
|
+
`);let n=Object.keys(s);if(n.length>0&&(console.log(`${R.dim}Existing profiles: ${n.join(", ")}${R.reset}`),!await Lt("Add or update a server profile?",!0))){console.log(`${R.dim}No changes made.${R.reset}
|
|
596
598
|
`);return}let o={...s},r=!0;for(;r;){console.log(`
|
|
597
|
-
${
|
|
598
|
-
${
|
|
599
|
+
${R.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${R.reset}`);let l=await _e("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${R.red} Name is required.${R.reset}`);continue}let u=await _e("Host / IP address");if(!u){console.log(`${R.red} Host is required.${R.reset}`);continue}let d=await _e("SSH user","root"),f=await _e("SSH port","22"),m=parseInt(f,10)||22,h=await _e("SSH key path (leave empty for SSH agent)",""),p=await el("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await Lt("Allow sudo commands?",!0),w={host:u,user:d};m!==22&&(w.port=m),h&&(w.key=h),p!=="other"&&(w.os=p),g&&(w.sudo=!0),o[l]=w,console.log(`
|
|
600
|
+
${R.green}\u2713${R.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${p!=="other"?` [${p}]`:""}`),r=await Lt(`
|
|
599
601
|
Add another server?`,!1)}he.existsSync(t)||he.mkdirSync(t,{recursive:!0}),he.writeFileSync(e,JSON.stringify(o,null,2)+`
|
|
600
602
|
`,"utf-8"),console.log(`
|
|
601
|
-
${
|
|
603
|
+
${R.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${R.reset}`);let a=It.join(process.cwd(),".gitignore");he.existsSync(a)&&(he.readFileSync(a,"utf-8").includes(".nex/")||await Lt("Add .nex/ to .gitignore?",!0)&&(he.appendFileSync(a,`
|
|
602
604
|
# nex-code server profiles
|
|
603
605
|
.nex/
|
|
604
|
-
`),console.log(`${
|
|
605
|
-
Set up deploy configs (.nex/deploy.json)?`,!1)&&await
|
|
606
|
-
${
|
|
607
|
-
`)}async function
|
|
608
|
-
${
|
|
609
|
-
`);let a=Object.keys(o);a.length>0&&console.log(`${
|
|
610
|
-
${
|
|
611
|
-
${
|
|
606
|
+
`),console.log(`${R.green}\u2713 Added .nex/ to .gitignore${R.reset}`))),await Lt(`
|
|
607
|
+
Set up deploy configs (.nex/deploy.json)?`,!1)&&await tl(o,t),console.log(`
|
|
608
|
+
${R.dim}Use /servers to list profiles, /servers ping to check connectivity.${R.reset}
|
|
609
|
+
`)}async function tl(t,e){let s=e||It.join(process.cwd(),Zc),n=It.join(s,"deploy.json"),o={};if(he.existsSync(n))try{o=JSON.parse(he.readFileSync(n,"utf-8"))}catch{}if(!t){let u=It.join(s,"servers.json");if(he.existsSync(u))try{t=JSON.parse(he.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
610
|
+
${R.bold}${R.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${R.reset}`),console.log(`${R.bold}${R.cyan}\u2551 Deploy Config Wizard \u2551${R.reset}`),console.log(`${R.bold}${R.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${R.reset}
|
|
611
|
+
`);let a=Object.keys(o);a.length>0&&console.log(`${R.dim}Existing deploy configs: ${a.join(", ")}${R.reset}`);let c={...o},l=!0;for(;l;){console.log(`
|
|
612
|
+
${R.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${R.reset}`);let u=await _e("Config name (e.g. prod, staging)");if(!u){console.log(`${R.red} Name is required.${R.reset}`);continue}let d;r.length>0?d=await el("Target server",r,r[0]):d=await _e("Target server (profile name or user@host)");let f=await _e("Local path to sync (e.g. dist/ or ./build)","dist/"),m=await _e("Remote destination path (e.g. /var/www/app)");if(!m){console.log(`${R.red} Remote path is required.${R.reset}`);continue}let h=await _e("Deploy script to run after sync (leave empty to skip)",""),p=await _e("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env"),g=p?p.split(",").map(x=>x.trim()).filter(Boolean):[],w={server:d,local_path:f,remote_path:m};h&&(w.deploy_script=h),g.length>0&&(w.exclude=g),c[u]=w;let $=f.endsWith("/")?f:`${f}/`;console.log(`
|
|
613
|
+
${R.green}\u2713${R.reset} Deploy config "${u}": ${$} \u2192 ${d}:${m}`),h&&console.log(` ${R.dim} Then: ${h}${R.reset}`),l=await Lt(`
|
|
612
614
|
Add another deploy config?`,!1)}he.existsSync(s)||he.mkdirSync(s,{recursive:!0}),he.writeFileSync(n,JSON.stringify(c,null,2)+`
|
|
613
615
|
`,"utf-8"),console.log(`
|
|
614
|
-
${
|
|
615
|
-
`)}
|
|
616
|
+
${R.green}\u2713 Saved .nex/deploy.json (${Object.keys(c).length} config${Object.keys(c).length!==1?"s":""})${R.reset}`),console.log(`${R.dim}Use: deploy prod (or with explicit params)${R.reset}
|
|
617
|
+
`)}nl.exports={runServerWizard:lg,runDeployWizard:tl,setWizardRL:cg}});var il=N((D$,rl)=>{var ug=require("axios"),fn=require("fs"),ol=require("path"),dg="nex-code",Xo=ol.join(process.cwd(),".nex"),Vo=ol.join(Xo,"last-version-check");fn.existsSync(Xo)||fn.mkdirSync(Xo,{recursive:!0});async function fg(){try{let t=pg(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};hg(e);let s=mg(),o=(await ug.get(`https://registry.npmjs.org/${dg}/latest`,{timeout:5e3})).data.version,r=gg(o,s);return{hasNewVersion:r,latestVersion:r?o:void 0,currentVersion:r?s:void 0}}catch{return{hasNewVersion:!1}}}function mg(){return $n().version}function pg(){try{if(fn.existsSync(Vo)){let t=fn.readFileSync(Vo,"utf8");return parseInt(t,10)}}catch{}return null}function hg(t){try{fn.writeFileSync(Vo,t.toString())}catch{}}function gg(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}}rl.exports={checkForNewVersion:fg}});var xl=N((U$,bl)=>{var $g=require("readline"),et=require("fs"),Ie=require("path"),{C:i,banner:yg,cleanupTerminal:al}=oe(),{listProviders:Zo,getActiveProviderName:Qe,listAllModels:F$,setFallbackChain:wg,getFallbackChain:bg,getProvider:xg}=fe(),{flushAutoSave:cl}=lt(),{getActiveModel:Ze,setActiveModel:ll}=Rn(),{printContext:ul}=wo(),{loadAllSkills:_g,getSkillCommands:er,handleSkillCommand:kg}=Ht(),{setReadlineInterface:vg,setAutoConfirm:Sg,getAutoConfirm:dl}=Oe(),{StickyFooter:Eg}=Wc(),ps=process.cwd(),ze=null;function fl(){return ze?.signal??null}var hs=[{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 ml(){let t=er(),e=[...hs,...t],s=Math.max(...e.map(n=>n.cmd.length));console.log("");for(let{cmd:n,desc:o}of hs)console.log(` ${i.cyan}${n.padEnd(s+2)}${i.reset}${i.dim}${o}${i.reset}`);for(let{cmd:n,desc:o}of t)console.log(` ${i.cyan}${n.padEnd(s+2)}${i.reset}${i.dim}${o} ${i.yellow}[skill]${i.reset}`);console.log(`
|
|
616
618
|
${i.dim}Type /help for detailed usage${i.reset}
|
|
617
|
-
`)}function
|
|
619
|
+
`)}function pl(t){try{let e,s;t.endsWith("/")||t.endsWith(Ie.sep)?(e=t,s=""):(e=Ie.dirname(t),s=Ie.basename(t)),e.startsWith("~")&&(e=Ie.join(require("os").homedir(),e.slice(1)));let n=Ie.isAbsolute(e)?e:Ie.resolve(ps,e);if(!et.existsSync(n)||!et.statSync(n).isDirectory())return[];let o=et.readdirSync(n,{withFileTypes:!0}),r=[];for(let a of o){if(a.name.startsWith(".")||a.name==="node_modules"||s&&!a.name.startsWith(s))continue;let c=t.endsWith("/")||t.endsWith(Ie.sep)?t:Ie.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?a.name:c+a.name;r.push(a.isDirectory()?l+"/":l)}return r}catch{return[]}}function hl(t){if(t.startsWith("/")){let n=[...hs,...er()],o=n.map(r=>r.cmd).filter(r=>r.startsWith(t));return[o.length?o:n.map(r=>r.cmd),t]}let e=t.split(/\s+/),s=e[e.length-1]||"";return s&&(s.includes("/")||s.startsWith("./")||s.startsWith("../")||s.startsWith("~"))?[pl(s),s]:[[],t]}function gl(){console.log(`
|
|
618
620
|
${i.bold}${i.cyan}Commands:${i.reset}
|
|
619
621
|
${i.cyan}/help${i.reset} ${i.dim}Show this help${i.reset}
|
|
620
622
|
${i.cyan}/model [spec]${i.reset} ${i.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${i.reset}
|
|
@@ -675,61 +677,100 @@ ${i.bold}${i.cyan}Undo / Redo:${i.reset}
|
|
|
675
677
|
${i.cyan}/history${i.reset} ${i.dim}Show file change history${i.reset}
|
|
676
678
|
|
|
677
679
|
${i.cyan}/exit${i.reset} ${i.dim}Quit${i.reset}
|
|
678
|
-
`)}function
|
|
679
|
-
${i.bold}${i.cyan}Providers:${i.reset}`);for(let n of t){let o=n.provider===e,r=n.configured?`${i.green}\u2713${i.reset}`:`${i.red}\u2717${i.reset}`,a=o?` ${i.cyan}(active)${i.reset}`:"";console.log(` ${r} ${i.bold}${n.provider}${i.reset}${a}`);for(let c of n.models){let l=c.id===s.id&&o?` ${i.yellow}\u25C4${i.reset}`:"";console.log(` ${i.dim}${c.id}${i.reset} \u2014 ${c.name}${l}`)}}console.log()}async function
|
|
680
|
-
${i.bold}${i.cyan}Token Usage:${i.reset}`),console.log(` ${i.dim}Model:${i.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${i.dim}Used:${i.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f
|
|
681
|
-
${i.dim}Breakdown:${i.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:r}=
|
|
680
|
+
`)}function $l(t){let s=Math.round(t/100*30),n=30-s;return` ${t>80?i.red:t>50?i.yellow:i.green}${"\u2588".repeat(s)}${i.dim}${"\u2591".repeat(n)}${i.reset} ${t}%`}function Qo(){let t=Zo(),e=Qe(),s=Ze();console.log(`
|
|
681
|
+
${i.bold}${i.cyan}Providers:${i.reset}`);for(let n of t){let o=n.provider===e,r=n.configured?`${i.green}\u2713${i.reset}`:`${i.red}\u2717${i.reset}`,a=o?` ${i.cyan}(active)${i.reset}`:"";console.log(` ${r} ${i.bold}${n.provider}${i.reset}${a}`);for(let c of n.models){let l=c.id===s.id&&o?` ${i.yellow}\u25C4${i.reset}`:"";console.log(` ${i.dim}${c.id}${i.reset} \u2014 ${c.name}${l}`)}}console.log()}async function yl(t,e){let[s,...n]=t.split(/\s+/);switch(s){case"/help":return gl(),!0;case"/model":{let o=n.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=Gc();await r(e)}else{let r=Ze(),a=Qe();console.log(`${i.bold}${i.cyan}Active model:${i.reset} ${i.dim}${a}:${r.id} (${r.name})${i.reset}`),console.log(`${i.gray}Use /model <provider:model> to switch. /providers to see all.${i.reset}`)}return!0}if(o==="list")return Qo(),!0;if(ll(o)){let r=Ze(),a=Qe();console.log(`${i.green}Switched to ${a}:${r.id} (${r.name})${i.reset}`)}else console.log(`${i.red}Unknown model: ${o}${i.reset}`),console.log(`${i.gray}Use /providers to see available models${i.reset}`);return!0}case"/providers":return Qo(),!0;case"/fallback":{let o=n.join(" ").trim();if(!o){let a=bg();return a.length===0?(console.log(`${i.dim}No fallback chain configured${i.reset}`),console.log(`${i.dim}Use /fallback anthropic,openai,local to set${i.reset}`)):console.log(`${i.bold}${i.cyan}Fallback chain:${i.reset} ${a.join(" \u2192 ")}`),!0}let r=o.split(",").map(a=>a.trim()).filter(Boolean);return wg(r),console.log(`${i.green}Fallback chain: ${r.join(" \u2192 ")}${i.reset}`),!0}case"/tokens":{let{getConversationMessages:o}=ie(),{getUsage:r}=Te(),{TOOL_DEFINITIONS:a}=Fe(),c=o(),l=r(c,a),u=Ze(),d=Qe();console.log(`
|
|
682
|
+
${i.bold}${i.cyan}Token Usage:${i.reset}`),console.log(` ${i.dim}Model:${i.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${i.dim}Used:${i.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f=$l(l.percentage);return console.log(` ${f}`),console.log(`
|
|
683
|
+
${i.dim}Breakdown:${i.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:r}=xt();return n.join(" ").trim()==="reset"?(r(),console.log(`${i.green}Cost tracking reset${i.reset}`),!0):(console.log(`
|
|
682
684
|
${o()}
|
|
683
|
-
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:a,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=
|
|
684
|
-
${i.bold}${i.cyan}Cost Limits:${i.reset}`);let g=!1;for(let w of p){let $=r(w.provider),x=h[w.provider];if(x!==void 0){g=!0;let
|
|
685
|
+
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:a,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=xt(),d=n[0];if(!d){let h=o(),p=Zo();console.log(`
|
|
686
|
+
${i.bold}${i.cyan}Cost Limits:${i.reset}`);let g=!1;for(let w of p){let $=r(w.provider),x=h[w.provider];if(x!==void 0){g=!0;let O=Math.min(100,Math.round($/x*100)),_=10,k=Math.round(O/100*_),C=_-k,T=`${O>=100?i.red:O>=80?i.yellow:i.green}${"\u2588".repeat(k)}${i.dim}${"\u2591".repeat(C)}${i.reset}`;console.log(` ${i.bold}${w.provider}:${i.reset} $${$.toFixed(2)} / $${x.toFixed(2)} (${O}%) ${T}`)}else w.provider==="ollama"||w.provider==="local"?console.log(` ${i.bold}${w.provider}:${i.reset} ${i.dim}free (no limit)${i.reset}`):$>0&&console.log(` ${i.bold}${w.provider}:${i.reset} $${$.toFixed(2)} ${i.dim}(no limit)${i.reset}`)}return g||console.log(` ${i.dim}No limits set. Use /budget <provider> <amount> to set one.${i.reset}`),console.log(),!0}let f=n[1];if(!f){let h=a(d);return h.limit!==null?console.log(`${i.bold}${d}:${i.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${i.bold}${d}:${i.reset} $${h.spent.toFixed(2)} ${i.dim}(no limit)${i.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return c(d),l(),console.log(`${i.green}Removed cost limit for ${d}${i.reset}`),!0;let m=parseFloat(f);return isNaN(m)||m<=0?(console.log(`${i.red}Invalid amount: ${f}. Use a positive number or 'off'.${i.reset}`),!0):(u(d,m),l(),console.log(`${i.green}Set ${d} budget limit: $${m.toFixed(2)}${i.reset}`),!0)}case"/clear":{let{clearConversation:o,getConversationMessages:r}=ie(),{clearHistory:a}=kt(),c=r();if(c.filter(u=>u.role==="user").length>=4){process.stdout.write(`${i.dim}Reflecting on session...${i.reset} `);let{learnFromSession:u}=Jo();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(`${i.green}${f} learning(s) saved${i.reset}
|
|
685
687
|
`)}else process.stdout.write(`${i.dim}nothing new${i.reset}
|
|
686
688
|
`)}).catch(()=>process.stdout.write(`
|
|
687
|
-
`))}return o(),a(),console.log(`${i.green}Conversation cleared${i.reset}`),!0}case"/context":return await
|
|
688
|
-
${i.bold}${i.cyan}Sessions:${i.reset}`);for(let a of r){let c=a.updatedAt?new Date(a.updatedAt).toLocaleString():"?",l=a.name==="_autosave"?` ${i.dim}(auto)${i.reset}`:"";console.log(` ${i.cyan}${a.name}${i.reset}${l} \u2014 ${a.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=
|
|
689
|
+
`))}return o(),a(),console.log(`${i.green}Conversation cleared${i.reset}`),!0}case"/context":return await ul(ps),!0;case"/autoconfirm":{let o=!dl();return Sg(o),console.log(`${i.green}Auto-confirm: ${o?"ON":"OFF"}${i.reset}`),o&&console.log(`${i.yellow} \u26A0 File changes will be applied without confirmation${i.reset}`),!0}case"/save":{let{saveSession:o}=lt(),{getConversationMessages:r}=ie(),a=n.join(" ").trim()||`session-${Date.now()}`,c=r();if(c.length===0)return console.log(`${i.yellow}No conversation to save${i.reset}`),!0;let l=Ze(),u=Qe();return o(a,c,{model:l.id,provider:u}),console.log(`${i.green}Session saved: ${a} (${c.length} messages)${i.reset}`),!0}case"/load":{let{loadSession:o}=lt(),{setConversationMessages:r}=ie(),a=n.join(" ").trim();if(!a)return console.log(`${i.red}Usage: /load <name>${i.reset}`),!0;let c=o(a);return c?(r(c.messages),console.log(`${i.green}Loaded session: ${c.name} (${c.messageCount} messages)${i.reset}`),!0):(console.log(`${i.red}Session not found: ${a}${i.reset}`),!0)}case"/sessions":{let{listSessions:o}=lt(),r=o();if(r.length===0)return console.log(`${i.dim}No saved sessions${i.reset}`),!0;console.log(`
|
|
690
|
+
${i.bold}${i.cyan}Sessions:${i.reset}`);for(let a of r){let c=a.updatedAt?new Date(a.updatedAt).toLocaleString():"?",l=a.name==="_autosave"?` ${i.dim}(auto)${i.reset}`:"";console.log(` ${i.cyan}${a.name}${i.reset}${l} \u2014 ${a.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=lt(),{setConversationMessages:r}=ie(),a=o();return a?(r(a.messages),console.log(`${i.green}Resumed: ${a.name} (${a.messageCount} messages)${i.reset}`),!0):(console.log(`${i.yellow}No session to resume${i.reset}`),!0)}case"/remember":{let{remember:o}=Ve(),r=n.join(" ").trim();if(!r)return console.log(`${i.red}Usage: /remember <key>=<value> or /remember <text>${i.reset}`),!0;let a=r.indexOf("="),c,l;return a>0?(c=r.substring(0,a).trim(),l=r.substring(a+1).trim()):(c=r.substring(0,40).replace(/\s+/g,"-"),l=r),o(c,l),console.log(`${i.green}Remembered: ${c}${i.reset}`),!0}case"/forget":{let{forget:o}=Ve(),r=n.join(" ").trim();return r?(o(r)?console.log(`${i.green}Forgotten: ${r}${i.reset}`):console.log(`${i.red}Memory not found: ${r}${i.reset}`),!0):(console.log(`${i.red}Usage: /forget <key>${i.reset}`),!0)}case"/memory":{let{listMemories:o}=Ve(),r=o();if(r.length===0)return console.log(`${i.dim}No memories saved${i.reset}`),!0;console.log(`
|
|
689
691
|
${i.bold}${i.cyan}Memory:${i.reset}`);for(let a of r)console.log(` ${i.cyan}${a.key}${i.reset} = ${a.value}`);return console.log(),!0}case"/brain":{let{listDocuments:o,readDocument:r,writeDocument:a,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=tn(),m=n[0],h=n.slice(1).join(" ").trim();switch(m){case"add":{if(!h)return console.log(`${i.red}Usage: /brain add <name> [content]${i.reset}`),console.log(`${i.dim} /brain add api-notes \u2014 creates empty file${i.reset}`),console.log(`${i.dim} /brain add api-notes This is content \u2014 writes directly${i.reset}`),!0;let p=h.indexOf(" ");if(p<0){a(h,`# ${h}
|
|
690
692
|
|
|
691
693
|
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${i.green}Created .nex/brain/${h}.md${i.reset}`),console.log(`${i.dim}Edit it directly at: ${g}${i.reset}`)}else{let g=h.substring(0,p),w=h.substring(p+1);a(g,w),console.log(`${i.green}Added to brain: ${g}${i.reset}`)}return!0}case"list":{let p=o();if(p.length===0)return console.log(`${i.dim}No brain documents yet. Use /brain add <name> to create one.${i.reset}`),!0;console.log(`
|
|
692
|
-
${i.bold}${i.cyan}Brain Documents:${i.reset}`);let g=Math.max(8,...p.map($=>$.name.length)),w=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd(w)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat(w)}${"-".repeat(7)} --------`);for(let $ of p){let{frontmatter:x}=r($.name),
|
|
694
|
+
${i.bold}${i.cyan}Brain Documents:${i.reset}`);let g=Math.max(8,...p.map($=>$.name.length)),w=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd(w)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat(w)}${"-".repeat(7)} --------`);for(let $ of p){let{frontmatter:x}=r($.name),O=Array.isArray(x.tags)?x.tags.join(", "):"",_=$.size<1024?`${$.size}B`:`${($.size/1024).toFixed(1)}K`,k=$.modified.toLocaleDateString();console.log(` ${i.cyan}${$.name.padEnd(g+2)}${i.reset}${i.dim}${O.substring(0,w-1).padEnd(w)}${_.padStart(7)} ${k}${i.reset}`)}return console.log(),!0}case"search":{if(!h)return console.log(`${i.red}Usage: /brain search <query>${i.reset}`),!0;let p=await f(h,{topK:5});if(p.length===0)return console.log(`${i.dim}No matching brain documents for: ${h}${i.reset}`),!0;console.log(`
|
|
693
695
|
${i.bold}${i.cyan}Brain Search: "${h}"${i.reset}`);for(let g of p){let w=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
|
|
694
696
|
${i.cyan}${g.name}${i.reset} ${i.dim}(score: ${w})${i.reset}`),console.log(` ${i.dim}${g.excerpt||""}${i.reset}`)}return console.log(),!0}case"show":{if(!h)return console.log(`${i.red}Usage: /brain show <name>${i.reset}`),!0;let p=r(h);return p.content?(console.log(`
|
|
695
697
|
${i.bold}${i.cyan}${h}.md${i.reset}
|
|
696
|
-
`),console.log(p.content),!0):(console.log(`${i.red}Document not found: ${h}${i.reset}`),!0)}case"remove":{if(!h)return console.log(`${i.red}Usage: /brain remove <name>${i.reset}`),!0;let{confirm:p}=
|
|
697
|
-
${i.bold}${i.cyan}Brain Status${i.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync($)?i.green+"present"+i.reset:i.dim+"not built"+i.reset}`),console.log(` Embeddings: ${g.existsSync(x)?i.green+"present"+i.reset:i.dim+"not built (run /brain embed)"+i.reset}`),p.length>0){let
|
|
698
|
+
`),console.log(p.content),!0):(console.log(`${i.red}Document not found: ${h}${i.reset}`),!0)}case"remove":{if(!h)return console.log(`${i.red}Usage: /brain remove <name>${i.reset}`),!0;let{confirm:p}=Oe();if(!await p(`Remove brain document "${h}"?`))return console.log(`${i.dim}Cancelled${i.reset}`),!0;let w=c(h);return console.log(w?`${i.green}Removed: ${h}.md${i.reset}`:`${i.red}Document not found: ${h}${i.reset}`),!0}case"rebuild":{let p=l(),g=Object.keys(p.documents).length;return console.log(`${i.green}Index rebuilt: ${g} document(s)${i.reset}`),!0}case"embed":{if(!await d())return console.log(`${i.yellow}Ollama embedding model not available.${i.reset}`),console.log(`${i.dim}Set NEX_EMBED_MODEL env var (default: nomic-embed-text) and ensure Ollama is running.${i.reset}`),!0;console.log(`${i.dim}Building embedding index...${i.reset}`);try{let g=await u(),w=Object.keys(g.documents||{}).length;console.log(`${i.green}Embedding index built: ${w} document(s)${i.reset}`)}catch(g){console.log(`${i.red}Embedding failed: ${g.message}${i.reset}`)}return!0}case"status":{let p=o(),g=require("fs"),w=require("path"),$=w.join(process.cwd(),".nex","brain",".brain-index.json"),x=w.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
|
|
699
|
+
${i.bold}${i.cyan}Brain Status${i.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync($)?i.green+"present"+i.reset:i.dim+"not built"+i.reset}`),console.log(` Embeddings: ${g.existsSync(x)?i.green+"present"+i.reset:i.dim+"not built (run /brain embed)"+i.reset}`),p.length>0){let O=p.reduce((_,k)=>_+k.size,0);console.log(` Total size: ${O<1024?O+"B":(O/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:p}=require("child_process"),{promisify:g}=require("util"),w=g(p);try{let{stdout:$}=await w("git diff .nex/brain/",{cwd:process.cwd()});$.trim()?(console.log(`
|
|
698
700
|
${i.bold}${i.cyan}Brain Changes (git diff):${i.reset}
|
|
699
|
-
`),console.log($)):console.log(`${i.dim}No pending brain changes (clean git state)${i.reset}`)}catch{console.log(`${i.dim}Not a git repo or no brain dir${i.reset}`)}return!0}case"undo":{let p=require("fs"),w=require("path").join(process.cwd(),".nex","brain");if(!p.existsSync(w))return console.log(`${i.dim}No brain directory found${i.reset}`),!0;let $=o();if($.length===0)return console.log(`${i.dim}No brain documents to undo${i.reset}`),!0;let x=$[0],{exec:
|
|
701
|
+
`),console.log($)):console.log(`${i.dim}No pending brain changes (clean git state)${i.reset}`)}catch{console.log(`${i.dim}Not a git repo or no brain dir${i.reset}`)}return!0}case"undo":{let p=require("fs"),w=require("path").join(process.cwd(),".nex","brain");if(!p.existsSync(w))return console.log(`${i.dim}No brain directory found${i.reset}`),!0;let $=o();if($.length===0)return console.log(`${i.dim}No brain documents to undo${i.reset}`),!0;let x=$[0],{exec:O}=require("child_process"),{promisify:_}=require("util"),k=_(O);try{await k(`git checkout -- ".nex/brain/${x.name}.md"`,{cwd:process.cwd()}),l(),console.log(`${i.green}Undone: restored ${x.name}.md from git${i.reset}`)}catch{console.log(`${i.red}Could not undo \u2014 not tracked in git or no prior version${i.reset}`)}return!0}default:{let p=o();if(p.length===0)console.log(`
|
|
700
702
|
${i.bold}${i.cyan}Brain Knowledge Base${i.reset}`),console.log(`${i.dim}No documents yet. Create with /brain add <name>${i.reset}`),console.log(`
|
|
701
703
|
${i.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${i.reset}
|
|
702
704
|
`);else{console.log(`
|
|
703
705
|
${i.bold}${i.cyan}Brain: ${p.length} document(s)${i.reset}`);for(let g of p){let{frontmatter:w}=r(g.name),$=Array.isArray(w.tags)?` [${w.tags.join(", ")}]`:"";console.log(` ${i.cyan}${g.name}${i.reset}${i.dim}${$}${i.reset}`)}console.log(`
|
|
704
706
|
${i.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${i.reset}
|
|
705
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=
|
|
707
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=Jo(),{getConversationMessages:a}=ie(),c=a(),l=c.filter(u=>u.role==="user").length;if(l<4)return console.log(`${i.yellow}Session too short to learn from (need 4+ user messages, have ${l})${i.reset}`),!0;console.log(`${i.dim}Analyzing session for learnings...${i.reset}`);try{let[u,d]=await Promise.all([o(c),r(c)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${i.dim}Session too short${i.reset}`),!0;u.error&&console.log(`${i.red}Reflection error: ${u.error}${i.reset}`),console.log(""),u.summary&&(console.log(`${i.bold}Session:${i.reset} ${i.dim}${u.summary}${i.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(`${i.dim}No new learnings extracted from this session${i.reset}`);else{if(f){console.log(`${i.bold}${i.cyan}Memory updates:${i.reset}`);for(let{key:p,value:g,action:w}of u.applied){let $=w==="updated"?`${i.yellow}~${i.reset}`:`${i.green}+${i.reset}`;console.log(` ${$} ${i.bold}${p}${i.reset} = ${g}`)}}if(m){console.log(`${i.bold}${i.cyan}Added to NEX.md:${i.reset}`);for(let p of u.nexAdded)console.log(` ${i.green}+${i.reset} ${p}`)}if(h){console.log(`${i.bold}${i.cyan}Brain documents:${i.reset}`);for(let{name:p,reason:g,action:w}of d.written){let $=w==="updated"?`${i.yellow}~${i.reset}`:`${i.green}+${i.reset}`;console.log(` ${$} ${i.bold}${p}.md${i.reset}${g?i.dim+" \u2014 "+g+i.reset:""}`)}}}console.log("")}catch(u){console.log(`${i.red}Learn failed: ${u.message}${i.reset}`)}return!0}case"/optimize":{let{getConversationMessages:o}=ie(),{getUsage:r}=Te(),{TOOL_DEFINITIONS:a}=Fe(),{listMemories:c}=Ve(),l=o(),u=r(l,a),d=Ze(),f=Qe(),m=c();console.log(`
|
|
706
708
|
${i.bold}${i.cyan}Optimization Report${i.reset}
|
|
707
709
|
`);let h=u.percentage>80?i.red:u.percentage>50?i.yellow:i.green;if(console.log(`${i.bold}Context Window:${i.reset} ${h}${u.percentage}%${i.reset} used (${u.used.toLocaleString()} / ${u.limit.toLocaleString()} tokens)`),u.percentage>75?console.log(` ${i.yellow}\u2192 Tip: Use /clear to free context (auto-learns first)${i.reset}`):u.percentage>50?console.log(` ${i.dim}\u2192 Context is filling up, consider /clear soon${i.reset}`):console.log(` ${i.green}\u2192 Context healthy${i.reset}`),console.log(`
|
|
708
|
-
${i.bold}Memory:${i.reset} ${m.length} entries`),m.length===0)console.log(` ${i.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${i.reset}`);else{let
|
|
710
|
+
${i.bold}Memory:${i.reset} ${m.length} entries`),m.length===0)console.log(` ${i.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${i.reset}`);else{let O=[...m].sort((C,v)=>new Date(v.updatedAt)-new Date(C.updatedAt))[0],_=O?Math.round((Date.now()-new Date(O.updatedAt))/6e4):null,k=_!==null?_<60?`${_}m ago`:`${Math.round(_/60)}h ago`:"?";console.log(` ${i.dim}Latest update: ${k}${i.reset}`),m.length>30&&console.log(` ${i.yellow}\u2192 Many memories (${m.length}) \u2014 consider pruning with /forget${i.reset}`)}console.log(`
|
|
709
711
|
${i.bold}Active Model:${i.reset} ${f}:${d.id}`);let p=d.contextWindow||d.maxTokens||0;p>0&&p<32e3&&l.length>10?console.log(` ${i.yellow}\u2192 Small context window (${(p/1e3).toFixed(0)}k). Consider /model for larger context${i.reset}`):p>=128e3&&console.log(` ${i.green}\u2192 Large context window (${(p/1e3).toFixed(0)}k) \u2014 good for long sessions${i.reset}`);let g=l.filter(x=>x.role==="user").length;console.log(`
|
|
710
712
|
${i.bold}Session:${i.reset} ${g} turns, ${l.length} messages total`),g>=4&&g%10===0&&console.log(` ${i.cyan}\u2192 Good time to /learn and capture session insights${i.reset}`);let w=[],$=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync($)||w.push("Create NEX.md in project root to give nex-code project-specific instructions"),w.length>0){console.log(`
|
|
711
|
-
${i.bold}Quick Wins:${i.reset}`);for(let x of w)console.log(` ${i.cyan}\u2192${i.reset} ${x}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:r,startExecution:a,setPlanMode:c,getPlanContent:l,formatPlan:u}=
|
|
713
|
+
${i.bold}Quick Wins:${i.reset}`);for(let x of w)console.log(` ${i.cyan}\u2192${i.reset} ${x}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:r,startExecution:a,setPlanMode:c,getPlanContent:l,formatPlan:u}=At(),{invalidateSystemPromptCache:d}=ie(),f=n.join(" ").trim();if(f==="status"){let m=o();return console.log(u(m)),!0}if(f==="approve"){if(r()){a(),c(!1),d();let m=!!l();console.log(`${i.green}${i.bold}Plan approved!${i.reset} ${m?"Executing the planned steps...":"Starting execution..."}`),console.log(`${i.dim}Plan mode disabled \u2014 all tools now available.${i.reset}`)}else console.log(`${i.red}No plan to approve. Enter plan mode first with /plan${i.reset}`);return!0}return c(!0),d(),console.log(`
|
|
712
714
|
${i.cyan}${i.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${i.reset}
|
|
713
715
|
${i.cyan}${i.bold}\u2502${i.reset} Analysis only \u2014 no file changes until approved ${i.cyan}${i.bold}\u2502${i.reset}
|
|
714
716
|
${i.cyan}${i.bold}\u2502${i.reset} ${i.dim}Read-only tools only \xB7 /plan approve to execute${i.reset} ${i.cyan}${i.bold}\u2502${i.reset}
|
|
715
|
-
${i.cyan}${i.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${i.reset}`),f&&console.log(`${i.dim}Task: ${f}${i.reset}`),!0}case"/plans":{let{listPlans:o}=
|
|
716
|
-
${i.bold}${i.cyan}Plans:${i.reset}`);for(let a of r){let c=a.status==="completed"?`${i.green}\u2713`:a.status==="executing"?`${i.blue}\u2192`:`${i.dim}\u25CB`;console.log(` ${c} ${i.reset}${i.bold}${a.name}${i.reset} \u2014 ${a.task||"?"} (${a.steps} steps, ${a.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:o,setAutonomyLevel:r,AUTONOMY_LEVELS:a}=
|
|
717
|
+
${i.cyan}${i.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${i.reset}`),f&&console.log(`${i.dim}Task: ${f}${i.reset}`),!0}case"/plans":{let{listPlans:o}=At(),r=o();if(r.length===0)return console.log(`${i.dim}No saved plans${i.reset}`),!0;console.log(`
|
|
718
|
+
${i.bold}${i.cyan}Plans:${i.reset}`);for(let a of r){let c=a.status==="completed"?`${i.green}\u2713`:a.status==="executing"?`${i.blue}\u2192`:`${i.dim}\u25CB`;console.log(` ${c} ${i.reset}${i.bold}${a.name}${i.reset} \u2014 ${a.task||"?"} (${a.steps} steps, ${a.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:o,setAutonomyLevel:r,AUTONOMY_LEVELS:a}=At(),c=n.join(" ").trim();return c?(r(c)?console.log(`${i.green}Autonomy: ${c}${i.reset}`):console.log(`${i.red}Unknown level: ${c}. Use: ${a.join(", ")}${i.reset}`),!0):(console.log(`${i.bold}${i.cyan}Autonomy:${i.reset} ${o()}`),console.log(`${i.dim}Levels: ${a.join(", ")}${i.reset}`),!0)}case"/permissions":{let{listPermissions:o}=cn(),r=o();console.log(`
|
|
717
719
|
${i.bold}${i.cyan}Tool Permissions:${i.reset}`);for(let a of r){let c=a.mode==="allow"?`${i.green}\u2713`:a.mode==="deny"?`${i.red}\u2717`:`${i.yellow}?`;console.log(` ${c} ${i.reset}${i.bold}${a.tool}${i.reset} ${i.dim}(${a.mode})${i.reset}`)}return console.log(`
|
|
718
720
|
${i.dim}Use /allow <tool> or /deny <tool> to change${i.reset}
|
|
719
|
-
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=cn(),a=n.join(" ").trim();return a?(o(a,"allow"),r(),console.log(`${i.green}${a}: allow${i.reset}`),!0):(console.log(`${i.red}Usage: /allow <tool>${i.reset}`),!0)}case"/deny":{let{setPermission:o,savePermissions:r}=cn(),a=n.join(" ").trim();return a?(o(a,"deny"),r(),console.log(`${i.red}${a}: deny${i.reset}`),!0):(console.log(`${i.red}Usage: /deny <tool>${i.reset}`),!0)}case"/commit":{let{isGitRepo:o,commit:r,analyzeDiff:a,formatDiffSummary:c}=
|
|
721
|
+
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=cn(),a=n.join(" ").trim();return a?(o(a,"allow"),r(),console.log(`${i.green}${a}: allow${i.reset}`),!0):(console.log(`${i.red}Usage: /allow <tool>${i.reset}`),!0)}case"/deny":{let{setPermission:o,savePermissions:r}=cn(),a=n.join(" ").trim();return a?(o(a,"deny"),r(),console.log(`${i.red}${a}: deny${i.reset}`),!0):(console.log(`${i.red}Usage: /deny <tool>${i.reset}`),!0)}case"/commit":{let{isGitRepo:o,commit:r,analyzeDiff:a,formatDiffSummary:c}=it(),{confirm:l}=Oe();if(!o())return console.log(`${i.red}Not a git repository${i.reset}`),!0;let u=n.join(" ").trim();if(u){let p=await r(u);return console.log(p?`${i.green}Committed: ${p} \u2014 ${u}${i.reset}`:`${i.red}Commit failed${i.reset}`),!0}if(!a())return console.log(`${i.yellow}No changes to commit${i.reset}`),!0;let f=await c();if(console.log(f),!await l(" Commit changes?"))return!0;let h=await r("nex-code update");return h&&console.log(`${i.green} \u2713 Committed: ${h}${i.reset}`),!0}case"/diff":{let{isGitRepo:o,formatDiffSummary:r}=it();return o()?(console.log(r()),!0):(console.log(`${i.red}Not a git repository${i.reset}`),!0)}case"/review":{let{isGitRepo:o,getDiff:r}=it(),{processInput:a}=ie(),c=n.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),f=`## Review Protocol
|
|
722
|
+
|
|
723
|
+
**Phase 1 \u2014 Broad Scan:** Read the target code and identify all issues at a high level.
|
|
724
|
+
|
|
725
|
+
**Phase 2 \u2014 Deep Dive:** Select the 2-3 files or sections you consider most critical (highest risk or complexity). For each, run a targeted grep for specific anti-patterns:
|
|
726
|
+
- Error swallowing: \`catch.*{\\s*}\` or \`catch.*console\`
|
|
727
|
+
- Missing awaits, unhandled promises
|
|
728
|
+
- Hardcoded secrets or credentials
|
|
729
|
+
- Input validation gaps
|
|
730
|
+
Briefly report what each grep found or confirmed.
|
|
731
|
+
|
|
732
|
+
**Phase 3 \u2014 Report:** Present findings in this format:
|
|
733
|
+
|
|
734
|
+
### Score
|
|
735
|
+
|
|
736
|
+
| Category | Score | Notes |
|
|
737
|
+
|---|---|---|
|
|
738
|
+
| Security | X/10 | ... |
|
|
739
|
+
| Error Handling | X/10 | ... |
|
|
740
|
+
| Code Quality | X/10 | ... |
|
|
741
|
+
| Correctness | X/10 | ... |
|
|
742
|
+
| **Overall** | **X/10** | ... |
|
|
743
|
+
|
|
744
|
+
### Findings
|
|
745
|
+
|
|
746
|
+
For each issue, include:
|
|
747
|
+
- **Severity**: \u{1F534} Critical / \u{1F7E1} Warning / \u{1F535} Suggestion
|
|
748
|
+
- **Location**: file:line
|
|
749
|
+
- **Issue**: description
|
|
750
|
+
- **Fix**:
|
|
751
|
+
\`\`\`diff
|
|
752
|
+
- old code
|
|
753
|
+
+ fixed code
|
|
754
|
+
\`\`\`${l?`
|
|
755
|
+
|
|
756
|
+
\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}\`.
|
|
757
|
+
|
|
758
|
+
${f}`;else{if(!o())return console.log(`${i.red}Not a git repository \u2014 try /review <file>${i.reset}`),!0;let[h,p]=await Promise.all([r(!1),r(!0)]),g=p||h;if(!g||!g.trim())return console.log(`${i.yellow}No changes to review \u2014 commit something or specify a file: /review <file>${i.reset}`),!0;m=`Review the following code diff.
|
|
759
|
+
|
|
760
|
+
${f}
|
|
720
761
|
|
|
721
762
|
\`\`\`diff
|
|
722
|
-
${
|
|
723
|
-
\`\`\``}return await a(
|
|
763
|
+
${g.substring(0,2e4)}
|
|
764
|
+
\`\`\``}return await a(m),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:a}=it();if(!o())return console.log(`${i.red}Not a git repository${i.reset}`),!0;let c=n.join(" ").trim();if(!c){let u=r();return console.log(`${i.bold}${i.cyan}Branch:${i.reset} ${u||"(detached)"}`),!0}let l=a(c);return console.log(l?`${i.green}Created and switched to: ${l}${i.reset}`:`${i.red}Failed to create branch${i.reset}`),!0}case"/mcp":{let{listServers:o,connectAll:r,disconnectAll:a}=Pn(),c=n.join(" ").trim();if(c==="connect")return console.log(`${i.dim}Connecting MCP servers...${i.reset}`),r().then(u=>{for(let d of u)d.error?console.log(` ${i.red}\u2717${i.reset} ${d.name}: ${d.error}`):console.log(` ${i.green}\u2713${i.reset} ${d.name}: ${d.tools} tools`);u.length===0&&console.log(`${i.dim}No MCP servers configured in .nex/config.json${i.reset}`)}).catch(u=>{console.log(`${i.red}MCP connection error: ${u.message}${i.reset}`)}),!0;if(c==="disconnect")return a(),console.log(`${i.green}All MCP servers disconnected${i.reset}`),!0;let l=o();if(l.length===0)return console.log(`${i.dim}No MCP servers configured${i.reset}`),console.log(`${i.dim}Add servers to .nex/config.json under "mcpServers"${i.reset}`),!0;console.log(`
|
|
724
765
|
${i.bold}${i.cyan}MCP Servers:${i.reset}`);for(let u of l){let d=u.connected?`${i.green}\u2713 connected${i.reset}`:`${i.dim}\u25CB disconnected${i.reset}`;console.log(` ${d} ${i.bold}${u.name}${i.reset} (${u.command}) \u2014 ${u.toolCount} tools`)}return console.log(`
|
|
725
766
|
${i.dim}Use /mcp connect to connect all servers${i.reset}
|
|
726
|
-
`),!0}case"/hooks":{let{listHooks:o}=
|
|
767
|
+
`),!0}case"/hooks":{let{listHooks:o}=Mo(),r=o();if(r.length===0)return console.log(`${i.dim}No hooks configured${i.reset}`),console.log(`${i.dim}Add hooks to .nex/config.json or .nex/hooks/${i.reset}`),!0;console.log(`
|
|
727
768
|
${i.bold}${i.cyan}Hooks:${i.reset}`);for(let a of r){console.log(` ${i.cyan}${a.event}${i.reset}`);for(let c of a.commands)console.log(` ${i.dim}\u2192 ${c}${i.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:o,enableSkill:r,disableSkill:a}=Ht(),c=n.join(" ").trim();if(c.startsWith("enable ")){let u=c.substring(7).trim();return r(u)?console.log(`${i.green}Skill enabled: ${u}${i.reset}`):console.log(`${i.red}Skill not found: ${u}${i.reset}`),!0}if(c.startsWith("disable ")){let u=c.substring(8).trim();return a(u)?console.log(`${i.yellow}Skill disabled: ${u}${i.reset}`):console.log(`${i.red}Skill not found: ${u}${i.reset}`),!0}let l=o();if(l.length===0)return console.log(`${i.dim}No skills loaded${i.reset}`),console.log(`${i.dim}Add .md or .js files to .nex/skills/${i.reset}`),!0;console.log(`
|
|
728
769
|
${i.bold}${i.cyan}Skills:${i.reset}`);for(let u of l){let d=u.enabled?`${i.green}\u2713${i.reset}`:`${i.red}\u2717${i.reset}`,f=u.type==="prompt"?`${i.dim}(prompt)${i.reset}`:`${i.dim}(script)${i.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} ${i.bold}${u.name}${i.reset} ${f}${h}`)}return console.log(`
|
|
729
770
|
${i.dim}Use /skills enable <name> or /skills disable <name>${i.reset}
|
|
730
|
-
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=
|
|
771
|
+
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=Hn();return n.join(" ").trim()==="clear"?(r(),console.log(`${i.green}Tasks cleared${i.reset}`),!0):(console.log(`
|
|
731
772
|
`+o()+`
|
|
732
|
-
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=
|
|
773
|
+
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=kt(),a=o();if(!a)return console.log(`${i.yellow}Nothing to undo${i.reset}`),!0;a.wasCreated?console.log(`${i.green}Undone: deleted ${a.filePath} (was created by ${a.tool})${i.reset}`):console.log(`${i.green}Undone: restored ${a.filePath} (${a.tool})${i.reset}`);let c=r();return c>0&&console.log(`${i.dim}${c} more change(s) to undo${i.reset}`),!0}case"/redo":{let{redo:o,getRedoCount:r}=kt(),a=o();if(!a)return console.log(`${i.yellow}Nothing to redo${i.reset}`),!0;console.log(`${i.green}Redone: ${a.filePath} (${a.tool})${i.reset}`);let c=r();return c>0&&console.log(`${i.dim}${c} more change(s) to redo${i.reset}`),!0}case"/history":{let{getHistory:o,getUndoCount:r,getRedoCount:a}=kt(),c=o(20);if(c.length===0)return console.log(`${i.dim}No file changes in this session${i.reset}`),!0;console.log(`
|
|
733
774
|
${i.bold}File Change History${i.reset}
|
|
734
775
|
`);for(let l of c){let u=new Date(l.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${i.dim}${u}${i.reset} ${i.yellow}${l.tool}${i.reset} ${l.filePath}`)}return console.log(`
|
|
735
776
|
${i.dim}${r()} undo / ${a()} redo available${i.reset}
|
|
@@ -741,49 +782,49 @@ ${i.bold}${i.cyan}Kubernetes Overview${i.reset}${l?i.dim+" (remote: "+l+")"+i.re
|
|
|
741
782
|
`).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(`${i.bold}Pods: ${m.length} total ${i.green}${h} running${i.reset} ${i.yellow}${p} pending${i.reset} ${i.red}${g} unhealthy${i.reset}
|
|
742
783
|
`);let w=m.filter($=>!$.includes("Running")&&!$.includes("<none>"));if(w.length>0){console.log(`${i.bold}${i.red}Unhealthy Pods:${i.reset}`);for(let $ of w)console.log(` ${i.red}${$}${i.reset}`);console.log()}console.log(`${i.dim}Use k8s_pods / k8s_logs / k8s_exec tools for details${i.reset}`),console.log(`${i.dim}Or: /k8s user@host to query a remote cluster${i.reset}
|
|
743
784
|
`)}catch(f){console.log(`${i.dim}Could not list pods: ${f.message}${i.reset}
|
|
744
|
-
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:r,sshExec:a}=
|
|
785
|
+
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:r,sshExec:a}=Et(),c=o(),l=Object.keys(c);if(l.length===0)return console.log(`
|
|
745
786
|
${i.dim}No servers configured. Create .nex/servers.json:${i.reset}`),console.log(`${i.dim} { "prod": { "host": "1.2.3.4", "user": "jarvis", "os": "almalinux9" } }${i.reset}
|
|
746
787
|
`),!0;if(n[0]==="ping"){let f=n[1]?[n[1]]:l;return console.log(`
|
|
747
|
-
${i.bold}${i.cyan}Server connectivity:${i.reset}`),await Promise.all(f.map(async m=>{if(!c[m]){console.log(` ${i.red}\u2717${i.reset} ${m} \u2014 unknown profile`);return}try{let h={...c[m],_name:m},{exitCode:p}=await a(h,"echo ok",{timeout:8e3});console.log(p===0?` ${i.green}\u2713${i.reset} ${m} (${h.user?h.user+"@":""}${h.host})`:` ${i.red}\u2717${i.reset} ${m} (${h.host}) \u2014 SSH failed (exit ${p})`)}catch(h){console.log(` ${i.red}\u2717${i.reset} ${m} \u2014 ${h.message}`)}})),console.log(""),!0}let{formatProfile:d}=
|
|
788
|
+
${i.bold}${i.cyan}Server connectivity:${i.reset}`),await Promise.all(f.map(async m=>{if(!c[m]){console.log(` ${i.red}\u2717${i.reset} ${m} \u2014 unknown profile`);return}try{let h={...c[m],_name:m},{exitCode:p}=await a(h,"echo ok",{timeout:8e3});console.log(p===0?` ${i.green}\u2713${i.reset} ${m} (${h.user?h.user+"@":""}${h.host})`:` ${i.red}\u2717${i.reset} ${m} (${h.host}) \u2014 SSH failed (exit ${p})`)}catch(h){console.log(` ${i.red}\u2717${i.reset} ${m} \u2014 ${h.message}`)}})),console.log(""),!0}let{formatProfile:d}=Et();console.log(`
|
|
748
789
|
${i.bold}${i.cyan}Configured servers (${l.length}):${i.reset}`);for(let f of l)console.log(` ${i.green}${f}${i.reset} ${i.dim}${d(f,c[f])}${i.reset}`);return console.log(`
|
|
749
790
|
${i.dim}/servers ping \u2014 check SSH connectivity for all servers${i.reset}`),console.log(`${i.dim}/servers ping <name> \u2014 check a specific server${i.reset}
|
|
750
|
-
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=
|
|
791
|
+
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=Et(),{exec:a}=require("child_process"),{promisify:c}=require("util"),l=c(a),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(`
|
|
751
792
|
${i.bold}${i.cyan}Docker Containers:${i.reset}`);for(let[m,h]of f){let p=m==="local"?`${i.dim}local${i.reset}`:`${i.cyan}${m}${i.reset}`;try{let g;if(m==="local"){let{stdout:w}=await l(u,{timeout:8e3});g=(w||"").trim()}else{let w=await r(h,u,{timeout:1e4});if(g=[w.stdout,w.stderr].filter(Boolean).join("").trim(),w.exitCode!==0){console.log(` ${p}: ${i.red}SSH error (${w.exitCode})${i.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${p}: ${i.dim}(no containers)${i.reset}`):(console.log(` ${p}:`),g.split(`
|
|
752
|
-
`).forEach(w=>console.log(` ${i.dim}${w}${i.reset}`)))}catch(g){console.log(` ${p}: ${i.red}${g.message}${i.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=
|
|
793
|
+
`).forEach(w=>console.log(` ${i.dim}${w}${i.reset}`)))}catch(g){console.log(` ${p}: ${i.red}${g.message}${i.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=Vs(),r=o(),a=Object.keys(r),c=n[0];if(c&&a.includes(c)){let l=n.includes("--dry-run")||n.includes("-n"),u=r[c],{executeTool:d}=Fe();console.log(`
|
|
753
794
|
${i.bold}Running deploy: ${c}${l?" (dry run)":""}${i.reset}`);let f=await d("deploy",{...u,dry_run:l});return console.log(f),!0}if(a.length===0)return console.log(`
|
|
754
795
|
${i.dim}No deploy configs. Run /init to create .nex/deploy.json${i.reset}
|
|
755
796
|
`),!0;console.log(`
|
|
756
797
|
${i.bold}${i.cyan}Deploy configs (${a.length}):${i.reset}`);for(let[l,u]of Object.entries(r)){let d=u.local_path||"",f=`${u.server}:${u.remote_path}`,m=u.deploy_script?` ${i.dim}\u2192 ${u.deploy_script}${i.reset}`:"";console.log(` ${i.green}${l}${i.reset} ${i.dim}${d} \u2192 ${f}${i.reset}${m}`)}return console.log(`
|
|
757
798
|
${i.dim}/deploy <name> \u2014 run a named deploy${i.reset}`),console.log(`${i.dim}/deploy <name> --dry-run \u2014 preview without syncing${i.reset}
|
|
758
|
-
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:a}=
|
|
759
|
-
${i.dim}Bye!${i.reset}`),process.exit(0);default:return
|
|
760
|
-
`).filter(Boolean).slice(-
|
|
761
|
-
`)}catch{}}function ke(){let{isPlanMode:t,getAutonomyLevel:e}=
|
|
762
|
-
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:
|
|
799
|
+
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:a}=sl();return a(e),n[0]==="deploy"?await r():await o(),!0}case"/exit":case"/quit":console.log(`
|
|
800
|
+
${i.dim}Bye!${i.reset}`),process.exit(0);default:return kg(t)||console.log(`${i.red}Unknown command: ${s}. Type /help${i.reset}`),!0}}var tr=1e3;function nr(){return Ie.join(process.cwd(),".nex","repl_history")}function wl(){try{let t=nr();if(et.existsSync(t))return et.readFileSync(t,"utf-8").split(`
|
|
801
|
+
`).filter(Boolean).slice(-tr)}catch{}return[]}function ms(t){try{let e=nr(),s=Ie.dirname(e);et.existsSync(s)||et.mkdirSync(s,{recursive:!0}),et.appendFileSync(e,t+`
|
|
802
|
+
`)}catch{}}function ke(){let{isPlanMode:t,getAutonomyLevel:e}=At(),s=[];t()&&s.push("plan");let n=e();n!=="interactive"&&s.push(n);let o=Qe(),r=Ze(),a=o==="ollama"?r.id:`${o}:${r.id}`;return s.push(a),`${s.length>0?`${i.dim}[${s.join(" \xB7 ")}]${i.reset} `:""}${i.bold}${i.cyan}>${i.reset} `}var sr="\x1B[200~",or="\x1B[201~";function Cg(t){return typeof t=="string"&&t.includes(sr)}function Tg(t){return typeof t=="string"&&t.includes(or)}function mn(t){return typeof t!="string"?t:t.split(sr).join("").split(or).join("")}async function Rg(){if(!xg("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"),ll("local:llama3"),!0}catch{return!1}}async function Ag(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=ie();t(fl);let o=Zo().some(A=>A.configured),r=(async()=>{_g();let A=Ze(),L=Qe();return{model:A,providerName:L}})(),a=(async()=>o?!0:await Rg()?(console.log(`${i.green}\u2713 Local Ollama detected \u2014 using local models${i.reset}`),console.log(`${i.dim}Tip: Set API keys for cloud providers for more model options (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${i.reset}
|
|
803
|
+
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:A}=il();return await A()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,a,c]);!u&&!o&&(console.error(`
|
|
763
804
|
${i.red}\u2717 No provider configured and no local Ollama detected.${i.reset}
|
|
764
|
-
`),process.exit(1));let f=
|
|
765
|
-
`),await
|
|
805
|
+
`),process.exit(1));let f=wl(),m=$g.createInterface({input:process.stdin,output:process.stdout,prompt:ke(),completer:hl,history:f,historySize:tr});vg(m);let h=new Eg;h.activate(m);let p=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;yg(p,ps,{yolo:dl()}),d.hasNewVersion&&console.log(`${i.yellow}\u{1F4A1} New version available!${i.reset} Run ${i.cyan}npm update -g nex-code${i.reset} to upgrade from ${i.dim}${d.currentVersion}${i.reset} to ${i.green}${d.latestVersion}${i.reset}
|
|
806
|
+
`),await ul(ps);let g=!1,w=0,$=!1,x=null;function O(){cl(),h.deactivate(),al(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write(`
|
|
766
807
|
${i.dim}Bye!${i.reset}
|
|
767
|
-
`),process.exit(0)}process.on("SIGTERM",
|
|
768
|
-
${i.yellow} Task cancelled. Press Ctrl+C again to exit.${i.reset}`),g=!1,m.setPrompt(ke()),m.prompt();return}$?
|
|
808
|
+
`),process.exit(0)}process.on("SIGTERM",O),process.on("exit",()=>{cl()}),m.on("SIGINT",()=>{if(al(),g){if(w++,w>=2){O();return}ze&&ze.abort();let{cancelPendingAskUser:A}=Fe();A(),console.log(`
|
|
809
|
+
${i.yellow} Task cancelled. Press Ctrl+C again to exit.${i.reset}`),g=!1,m.setPrompt(ke()),m.prompt();return}$?O():($=!0,process.stdout.write(`
|
|
769
810
|
${i.dim} (Press Ctrl+C again to exit)${i.reset}
|
|
770
|
-
`),m.setPrompt(ke()),m.prompt(),x&&clearTimeout(x),x=setTimeout(()=>{$=!1,x=null},2e3))}),process.on("SIGINT",()=>{process.stdin.isTTY||
|
|
771
|
-
`).replace(/\r/g,"").trim();if(k=[],_=!1,!
|
|
772
|
-
`).length,
|
|
773
|
-
`)),
|
|
774
|
-
`)),!0}if(
|
|
775
|
-
`)),
|
|
776
|
-
`)),!0}return
|
|
777
|
-
\x1B[2K ${i.cyan}${
|
|
778
|
-
\x1B[2K ${i.dim}\u2026 +${L.length-
|
|
779
|
-
`)}return}if(
|
|
780
|
-
`).trim();if(
|
|
781
|
-
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${
|
|
782
|
-
`).trim();if(
|
|
783
|
-
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${
|
|
784
|
-
`),
|
|
785
|
-
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${
|
|
786
|
-
${i.dim}Bye!${i.reset}`),process.exit(0)})}
|
|
811
|
+
`),m.setPrompt(ke()),m.prompt(),x&&clearTimeout(x),x=setTimeout(()=>{$=!1,x=null},2e3))}),process.on("SIGINT",()=>{process.stdin.isTTY||O()});let _=!1,k=[],C=0,v={},T=!1;function F(){let A=k.join(`
|
|
812
|
+
`).replace(/\r/g,"").trim();if(k=[],_=!1,!A)return!0;C++,T=!0;let L=C;v[L]=A;let ne=A.split(`
|
|
813
|
+
`).length,z=ne>1?`[Pasted content #${L} \u2014 ${ne} lines]`:`[Pasted content #${L}]`,I=m.line||"",U=I&&!I.endsWith(" ")?" ":"",H=I+U+z;return m.setPrompt(ke()),m.prompt(),m.line=H,m.cursor=H.length,m._refreshLine(),!0}function q(A){return A.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(L,ne)=>v[Number(ne)]||"")}function Q(){C=0,v={},T=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let A=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(L,...ne){if(L!=="data")return A.call(process.stdin,L,...ne);let z=ne[0];if(Buffer.isBuffer(z)&&(z=z.toString("utf8")),typeof z!="string")return A.call(process.stdin,L,...ne);let I=z.includes(sr),U=z.includes(or);if(I&&U){let H=mn(z);return H&&k.push(...H.split(`
|
|
814
|
+
`)),F()}if(I){_=!0,k=[];let H=mn(z);return H&&k.push(...H.split(`
|
|
815
|
+
`)),!0}if(U){let H=mn(z);return H&&k.push(...H.split(`
|
|
816
|
+
`)),F()}if(_){let H=mn(z);return H&&k.push(...H.split(`
|
|
817
|
+
`)),!0}return A.call(process.stdin,L,...ne)}}let j=0;function Y(){if(j>0){let A="";for(let L=0;L<j;L++)A+="\x1B[1B\x1B[2K";A+=`\x1B[${j}A`,process.stdout.write(A),j=0}}function qe(A){let L=[...hs,...er()].filter(le=>le.cmd.startsWith(A));if(!L.length||L.length===1&&L[0].cmd===A)return;let ne=10,z=L.slice(0,ne),I=Math.max(...z.map(le=>le.cmd.length)),U="";for(let{cmd:le,desc:tt}of z){let pn=le.substring(0,A.length),ge=le.substring(A.length),Ee=" ".repeat(Math.max(0,I-le.length+2));U+=`
|
|
818
|
+
\x1B[2K ${i.cyan}${pn}${i.reset}${i.dim}${ge}${Ee}${tt}${i.reset}`}j=z.length,L.length>ne&&(U+=`
|
|
819
|
+
\x1B[2K ${i.dim}\u2026 +${L.length-ne} more${i.reset}`,j++);let H=m._prompt.replace(/\x1b\[[0-9;]*m/g,"").length;U+=`\x1B[${j}A\x1B[${H+m.cursor+1}G`,process.stdout.write(U)}process.stdin.isTTY&&process.stdin.on("keypress",(A,L)=>{Y(),!(L&&(L.name==="tab"||L.name==="return"))&&setImmediate(()=>{m.line&&m.line.startsWith("/")&&qe(m.line)})});let me=null,ce=`${i.dim}...${i.reset} `;m.setPrompt(ke()),m.prompt(),m.on("line",async A=>{if(Y(),Object.keys(v).length>0&&(A=q(A),Q(),m.setPrompt(ke())),g){let I=A.trim();if(I){let{injectMidRunNote:U}=ie();U(I),process.stdout.write(`${i.cyan} \u270E Wird im n\xE4chsten Schritt ber\xFCcksichtigt${i.reset}
|
|
820
|
+
`)}return}if(me!==null){if(me._mode==="triple"){if(A.trim()==='"""'){let I=me.join(`
|
|
821
|
+
`).trim();if(me=null,I){ms(I.replace(/\n/g,"\\n")),g=!0,w=0,$=!1,x&&(clearTimeout(x),x=null),ze=new AbortController;try{await s(I)}catch(H){if(!ze?.signal?.aborted){let le=H.message?.split(`
|
|
822
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${le}${i.reset}`)}}g=!1;let U=ne();U>0&&process.stdout.write(`${i.gray}[${U} messages] ${i.reset}`)}m.setPrompt(ke()),m.prompt();return}me.push(A),m.setPrompt(ce),m.prompt();return}if(A.endsWith("\\"))me.push(A.slice(0,-1));else{me.push(A);let I=me.join(`
|
|
823
|
+
`).trim();if(me=null,I){ms(I.replace(/\n/g,"\\n")),g=!0,w=0,$=!1,x&&(clearTimeout(x),x=null),ze=new AbortController;try{await s(I)}catch(le){if(!ze?.signal?.aborted){let tt=le.message?.split(`
|
|
824
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${tt}${i.reset}`)}}let{getConversationLength:U}=ie();g=!1;let H=U();H>0&&process.stdout.write(`${i.gray}[${H} messages] ${i.reset}`)}m.setPrompt(ke()),m.prompt();return}m.setPrompt(ce),m.prompt();return}if(A.trim()==='"""'||A.trim().startsWith('"""')){let I=A.trim().substring(3);me=I?[I]:[],me._mode="triple",m.setPrompt(ce),m.prompt();return}if(A.endsWith("\\")){me=[A.slice(0,-1)],me._mode="backslash",m.setPrompt(ce),m.prompt();return}let L=A.trim();if(!L){m.setPrompt(ke()),m.prompt();return}if(ms(L),L==="/"){ml(),m.setPrompt(ke()),m.prompt();return}if(L.startsWith("/")){await yl(L,m),m.setPrompt(ke()),m.prompt();return}if(T){let I=L.split(`
|
|
825
|
+
`),U=I.length,H=I[0].length>120?I[0].substring(0,117)+"\u2026":I[0],le=U>1?` ${i.cyan}[+${U-1} lines]${i.reset}`:"";console.log(`${i.dim} \u2570 ${H}${le}${i.reset}`)}g=!0,w=0,$=!1,x&&(clearTimeout(x),x=null),ze=new AbortController;try{await s(L)}catch(I){if(!ze?.signal?.aborted){let U=I.message?.split(`
|
|
826
|
+
`)[0]||"An unexpected error occurred";console.log(`${i.red}Error: ${U}${i.reset}`)}}g=!1;let{getConversationLength:ne}=ie(),z=ne();z>0&&process.stdout.write(`${i.gray}[${z} messages] ${i.reset}`),m.setPrompt(ke()),m.prompt()}),m.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),console.log(`
|
|
827
|
+
${i.dim}Bye!${i.reset}`),process.exit(0)})}bl.exports={startREPL:Ag,getPrompt:ke,loadHistory:wl,appendHistory:ms,getHistoryPath:nr,HISTORY_MAX:tr,showCommandList:ml,completer:hl,completeFilePath:pl,handleSlashCommand:yl,showProviders:Qo,showHelp:gl,renderBar:$l,hasPasteStart:Cg,hasPasteEnd:Tg,stripPasteSequences:mn,getAbortSignal:fl}});var vl=require("path");require("dotenv").config({path:vl.join(__dirname,"..",".env")});require("dotenv").config();var te=process.argv.slice(2);(te.includes("--help")||te.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
787
828
|
|
|
788
829
|
Options:
|
|
789
830
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -796,4 +837,4 @@ Options:
|
|
|
796
837
|
--json Output result as JSON (for CI parsing)
|
|
797
838
|
-h, --help Show this help
|
|
798
839
|
-v, --version Show version
|
|
799
|
-
`),process.exit(0));if(
|
|
840
|
+
`),process.exit(0));if(te.includes("-v")||te.includes("--version")){let t=$n();console.log(t.version),process.exit(0)}var Og=te.includes("--yolo")||te.includes("-yolo");if(Og){let{setAutoConfirm:t}=Oe();t(!0)}var rr=te.indexOf("--model");if(rr!==-1&&te[rr+1]){let{setActiveModel:t}=fe();t(te[rr+1])}var ir=te.indexOf("--max-turns");if(ir!==-1&&te[ir+1]){let t=parseInt(te[ir+1],10);if(t>0){let{setMaxIterations:e}=ie();e(t)}}else try{let t=require("fs"),e=vl.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}=ie();o(n)}}}catch{}function ar(){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 _l(t){if(te.includes("--auto")){let{setAutoConfirm:o}=Oe();o(!0)}if(!te.includes("--model")){let{setActiveModel:o}=fe(),r=process.env.HEADLESS_MODEL||"devstral-small-2:24b";o(r)}let{processInput:s,getConversationMessages:n}=ie();s(t).then(()=>{if(te.includes("--json")){let r=n().filter(a=>a.role==="assistant").pop();console.log(JSON.stringify({success:!0,response:r?.content||""}))}process.exit(0)}).catch(o=>{te.includes("--json")?console.log(JSON.stringify({success:!1,error:o.message})):console.error(o.message),process.exit(1)})}var kl=te.indexOf("--prompt-file");if(kl!==-1){let t=te[kl+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)),te.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}ar(),_l(s)}else{let t=te.indexOf("--task");if(t!==-1){let e=te[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),ar(),_l(e)}else{ar();let{startREPL:e}=xl();e()}}
|