nex-code 0.3.33 → 0.3.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/nex-code.js +206 -206
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var M=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var xn=M((Ig,El)=>{El.exports={name:"nex-code",version:"0.3.35",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 br=M((qg,wr)=>{var N={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"},gr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],$r=["\u273D","\u2726","\u2727","\u2726"],_s=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=gr[this.frame%gr.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=` ${N.dim}${o}m ${String(r).padStart(2,"0")}s${N.reset}`}else n>=1&&(s=` ${N.dim}${n}s${N.reset}`)}process.stderr.write(`\x1B[2K\r${N.cyan}${e}${N.reset} ${N.dim}${this.text}${N.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}},yr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ks=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=yr[this.frame%yr.length],s=this._formatElapsed(),n=s?` ${N.dim}${s}${N.reset}`:"",o="";for(let r=0;r<this.labels.length;r++){let i,c;switch(this.statuses[r]){case"done":i=`${N.green}\u2713${N.reset}`,c=N.dim;break;case"error":i=`${N.red}\u2717${N.reset}`,c=N.dim;break;default:i=`${N.cyan}${e}${N.reset}`,c=""}let l=r===this.labels.length-1?n:"";o+=`\x1B[2K ${i} ${c}${this.labels[r]}${N.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?` ${N.dim}${e}${N.reset}`:"",n="";for(let o=0;o<this.labels.length;o++){let r;switch(this.statuses[o]){case"done":r=`${N.green}\u2713${N.reset}`;break;case"error":r=`${N.red}\u2717${N.reset}`;break;default:r=`${N.yellow}\u25CB${N.reset}`}let i=o===this.labels.length-1?s:"";n+=`\x1B[2K ${r} ${N.dim}${this.labels[o]}${N.reset}${i}
|
|
5
|
+
`}process.stderr.write(n)}},_n={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},kn={done:N.green,in_progress:N.cyan,pending:N.dim,failed:N.red},Ye=null,vs=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=$r[this.frame%$r.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${N.dim}(${o})${N.reset}`:"",i=`\x1B[2K${N.cyan}${e}${N.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=_n[l.status]||_n.pending,f=kn[l.status]||kn.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${N.dim}${u}${N.reset} ${f}${d}${N.reset} ${m}
|
|
7
7
|
`}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
8
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),
|
|
8
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Ye=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,Ye===this&&(Ye=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`,i=`\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(i)}};function
|
|
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`,i=`\x1B[2K${N.green}\u2714${N.reset} ${this.name} ${N.dim}(${e} \xB7 ${r})${N.reset}
|
|
11
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=_n[l.status]||_n.pending,f=kn[l.status]||kn.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${N.dim}${u}${N.reset} ${f}${d}${N.reset} ${N.dim}${m}${N.reset}
|
|
12
|
+
`}process.stderr.write(i)}};function Tl(t){Ye=t}function Cl(){return Ye}function Rl(){Ye&&(Ye.stop(),Ye=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}wr.exports={C:N,Spinner:_s,MultiProgress:ks,TaskProgress:vs,setActiveTaskProgress:Tl,getActiveTaskProgress:Cl,cleanupTerminal:Rl}});var _r=M((jg,xr)=>{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"},Al={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"},Ol={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 Nl(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=>Ol[r.fnName]||r.fnName))],o;if(n.length===1&&s.length===1){o=n[0];let i=s[0].args||{},c=` ${G.reset}${G.dim}`;i.path?o+=`${c}${i.path.split("/").pop()}`:i.command?o+=`${c}${String(i.command).substring(0,50)}`:i.query?o+=`${c}${String(i.query).substring(0,50)}`:i.pattern&&(o+=`${c}${String(i.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=Al[t]||t.replace(/_/g," "),o=s?` ${G.dim}${s}${G.reset}`:"";return`${G.cyan} \u23FA${G.reset} ${G.bold}${n}${G.reset}${o}`}function Pl(t,e=8){let s=t.split(`
|
|
13
13
|
`),n=s.slice(0,e),o=s.length-e,r=`${G.dim} \u23BF ${G.reset}`,i=" ",c=n.map((l,u)=>`${u===0?r:i}${G.green}${l}${G.reset}`).join(`
|
|
14
14
|
`);return o>0&&(c+=`
|
|
15
15
|
${G.gray} \u2026+${o} more lines${G.reset}`),c}function Ll(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 Il(t,e,s,n){let o=String(s||"");if(n){let i=o.split(`
|
|
@@ -25,110 +25,114 @@ ${G.gray} \u2026+${o} more lines${G.reset}`),c}function Ll(t,e){switch(t){ca
|
|
|
25
25
|
`).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;r=i?`${i[1]} \xB7 ${c} change${c!==1?"s":""}`:"Done";break}case"git_diff":{let i=(o.match(/^\+[^+]/gm)||[]).length,c=(o.match(/^-[^-]/gm)||[]).length;r=i||c?`+${i} \u2212${c} lines`:"No diff";break}case"git_log":{let i=o.split(`
|
|
26
26
|
`).filter(c=>/^commit\s+[0-9a-f]{7}/.test(c)).length;r=i>0?`${i} commit${i!==1?"s":""}`:"Log retrieved";break}case"web_fetch":r="Fetched";break;case"web_search":{let i=o.split(`
|
|
27
27
|
|
|
28
|
-
`).filter(Boolean).length;r=`${i} result${i!==1?"s":""}`;break}case"task_list":r="Done";break;case"spawn_agents":{let i=(o.match(/✓ Agent/g)||[]).length,c=(o.match(/✗ Agent/g)||[]).length;r=c>0?`${i} done, ${c} failed`:`${i} agent${i!==1?"s":""} done`;break}case"switch_model":{let i=o.match(/Switched to (.+)/);r=i?`\u2192 ${i[1]}`:"Done";break}default:r="Done"}return` ${G.dim}\u23BF ${r}${G.reset}`}
|
|
29
|
-
`),u=s.yolo?` ${n}${
|
|
28
|
+
`).filter(Boolean).length;r=`${i} result${i!==1?"s":""}`;break}case"task_list":r="Done";break;case"spawn_agents":{let i=(o.match(/✓ Agent/g)||[]).length,c=(o.match(/✗ Agent/g)||[]).length;r=c>0?`${i} done, ${c} failed`:`${i} agent${i!==1?"s":""} done`;break}case"switch_model":{let i=o.match(/Switched to (.+)/);r=i?`\u2192 ${i[1]}`:"Done";break}default:r="Done"}return` ${G.dim}\u23BF ${r}${G.reset}`}xr.exports={C:G,formatToolCall:Ml,formatResult:Pl,getToolSpinnerText:Ll,formatToolSummary:Il,formatSectionHeader:Nl}});var oe=M((Dg,kr)=>{var xt={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 ql(t,e){return[...t].map(s=>s===" "?s:`\x1B[38;2;${e[0]};${e[1]};${e[2]}m${s}`).join("")+xt.reset}function jl(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 Dl(t,e,s={}){let n=xt.bold,o=xt.dim,r=xt.reset,i=["\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=i.map((d,f)=>{let m=f/(i.length-1||1);return ql(d,jl(c,m))}).join(`
|
|
29
|
+
`),u=s.yolo?` ${n}${xt.yellow}\u26A1 YOLO${r}`:"";console.log(`
|
|
30
30
|
${l}
|
|
31
|
-
${o}Agentic Coding CLI v${
|
|
31
|
+
${o}Agentic Coding CLI v${xn().version}${r}
|
|
32
32
|
${o}Model: ${t}${r} ${o}\xB7 /help${r}${u}
|
|
33
|
-
`)}var{Spinner:Fl,MultiProgress:Ul,TaskProgress:Wl,setActiveTaskProgress:Bl,getActiveTaskProgress:Hl,cleanupTerminal:Gl}=
|
|
34
|
-
`)
|
|
35
|
-
`)
|
|
33
|
+
`)}var{Spinner:Fl,MultiProgress:Ul,TaskProgress:Wl,setActiveTaskProgress:Bl,getActiveTaskProgress:Hl,cleanupTerminal:Gl}=br(),{formatToolCall:zl,formatResult:Kl,getToolSpinnerText:Jl,formatToolSummary:Yl,formatSectionHeader:Xl}=_r();kr.exports={C:xt,banner:Dl,Spinner:Fl,MultiProgress:Ul,TaskProgress:Wl,setActiveTaskProgress:Bl,getActiveTaskProgress:Hl,cleanupTerminal:Gl,formatToolCall:zl,formatResult:Kl,getToolSpinnerText:Jl,formatToolSummary:Yl,formatSectionHeader:Xl}});var Me=M((Fg,Cr)=>{var Vl=require("readline"),{C:Ne}=oe(),vr=[/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/],Ss=[/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 Sr(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 i=r.replace(/^sudo\s+(?:-[ugCD]\s+\S+\s+|-[A-Za-z]+\s+)*/,"");if(/^\s*(?:echo|printf)\s/.test(i))return!0;if(/^\s*for\s/.test(r)||/^\s*while\s/.test(r)){let c=r.match(/\bdo\s+([\s\S]*?)\s*(?:done|$)/)?.[1];return c?c.split(/\s*;\s*/).map(u=>u.trim()).filter(Boolean).every(u=>o(u)):Ss.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Ss.some(c=>c.test(i))};return n.every(o)}var Es=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],Er=[/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/],Tr=[...Es,...Er],Ts=!1,ot=null;function Ql(t){Ts=t}function Zl(){return Ts}function eu(t){ot=t}function tu(t){for(let e of vr)if(e.test(t))return e;return null}function nu(t){if(/ssh\s/.test(t)&&Sr(t))return!1;for(let e of Tr)if(e.test(t))return!0;return!1}function su(t){for(let e of Es)if(e.test(t))return!0;return!1}function ou(t,e={}){if(Ts)return Promise.resolve(!0);if(!process.stdout.isTTY||!process.stdin.isTTY)return ru(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0,r=!1;ot&&ot.pause();let i=()=>{r&&process.stdout.write(`\x1B[${s.length+1}A`),r=!0,process.stdout.write(`\r\x1B[K${Ne.yellow}${t}${Ne.reset}
|
|
34
|
+
`);for(let d=0;d<s.length;d++){let f=d===o,m=f?`${Ne.yellow}\u276F${Ne.reset}`:" ",h=f?`${Ne.yellow}${s[d]}${Ne.reset}`:s[d];process.stdout.write(`\r\x1B[K ${m} ${h}
|
|
35
|
+
`)}},c=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u),process.stdout.write(`\x1B[${s.length+1}A`);for(let f=0;f<s.length+1;f++)process.stdout.write(`\r\x1B[K
|
|
36
|
+
`);process.stdout.write(`\x1B[${s.length+1}A`),ot&&ot.resume(),n(d)},l=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&vn(e.toolName),c(!0)},u=d=>{if(d[0]===3){c(!1);return}let f=d.toString();if(f==="\r"||f===`
|
|
37
|
+
`){l(o);return}if(f==="\x1B[A"){o=(o-1+s.length)%s.length,i();return}if(f==="\x1B[B"){o=(o+1)%s.length,i();return}let m=f.toLowerCase().trim();if(m==="y"){c(!0);return}if(m==="n"){c(!1);return}if(m==="a"&&e.toolName){vn(e.toolName),c(!0);return}};i(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function ru(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(vn(e.toolName),n(!0)):n(i!=="n")};if(ot)ot.question(`${Ne.yellow}${t} ${s}${Ne.reset}`,o);else{let r=Vl.createInterface({input:process.stdin,output:process.stdout});r.question(`${Ne.yellow}${t} ${s}${Ne.reset}`,i=>{r.close(),o(i)})}})}var vn=()=>{};function iu(t){vn=t}Cr.exports={FORBIDDEN_PATTERNS:vr,SSH_SAFE_PATTERNS:Ss,isSSHReadOnly:Sr,DANGEROUS_BASH:Tr,CRITICAL_BASH:Es,NOTABLE_BASH:Er,isForbidden:tu,isDangerous:nu,isCritical:su,confirm:ou,setAutoConfirm:Ql,getAutoConfirm:Zl,setReadlineInterface:eu,setAllowAlwaysHandler:iu}});var _t=M((Ug,Rr)=>{var Cs=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`)}};Rr.exports={BaseProvider:Cs}});var Nr=M((Wg,Or)=>{var Sn=require("axios"),au=require("http"),cu=require("https"),{BaseProvider:lu}=_t(),En=new au.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Tn=new cu.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Ar={"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}},Rs=class extends lu{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Ar,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){Sn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:En,httpsAgent:Tn}).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 Sn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:En,httpsAgent:Tn})).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 i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
|
|
38
|
+
`)};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),i=n.maxTokens||r?.maxTokens||16384,c=await Sn.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:i}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:En,httpsAgent:Tn});return this.normalizeResponse(c.data)}async stream(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,c=n.onToken||(()=>{}),l;try{l=await Sn.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:i}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:En,httpsAgent:Tn})}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(`
|
|
39
|
+
`);h=g.pop()||"";for(let y of g){if(!y.trim())continue;let $;try{$=JSON.parse(y)}catch{continue}if($.message?.content&&(c($.message.content),f+=$.message.content),$.message?.tool_calls&&(m=m.concat($.message.tool_calls)),$.done){u({content:f,tool_calls:this._normalizeToolCalls(m)});return}}}),l.data.on("error",p=>{n.signal?.aborted||d(new Error(`Stream error: ${p.message}`))}),l.data.on("end",()=>{if(h.trim())try{let p=JSON.parse(h);p.message?.content&&(c(p.message.content),f+=p.message.content),p.message?.tool_calls&&(m=m.concat(p.message.tool_calls))}catch{}u({content:f,tool_calls:this._normalizeToolCalls(m)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`ollama-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};Or.exports={OllamaProvider:Rs,OLLAMA_MODELS:Ar}});var jr=M((Bg,qr)=>{var{callChat:uu}=ge(),{estimateTokens:As}=Re(),Mr=process.env.NEX_COMPACTION!=="false",Pr=6,Lr=500,du=`Summarize this conversation history concisely. Focus on:
|
|
36
40
|
- What files were read, created, or modified
|
|
37
41
|
- Key decisions made and their rationale
|
|
38
42
|
- Current state of the task (what's done, what's pending)
|
|
39
43
|
- Any errors encountered and how they were resolved
|
|
40
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
44
|
+
Be factual and brief. Use bullet points. Max 300 words.`;async function fu(t){if(!Mr||t.length<Pr)return null;let e=[{role:"system",content:du},{role:"user",content:Ir(t)}];try{let n=((await uu(e,[],{temperature:0,maxTokens:Lr})).content||"").trim();if(!n)return null;let o=t.reduce((i,c)=>i+As(c.content||"")+(c.tool_calls?As(JSON.stringify(c.tool_calls)):0),0),r=As(n);return r>=o*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
41
45
|
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function Ir(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
46
|
tools: ${o}`}return`[${s}] ${n}`}).join(`
|
|
43
47
|
|
|
44
|
-
`)}qr.exports={compactMessages:
|
|
48
|
+
`)}qr.exports={compactMessages:fu,formatMessagesForSummary:Ir,COMPACTION_ENABLED:Mr,COMPACTION_MIN_MESSAGES:Pr,COMPACTION_SUMMARY_BUDGET:Lr}});var Re=M((Hg,Gr)=>{function Fr(){return ge().getActiveModel()}var mu={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},Wt=new Map,Dr=1e3,Os=new WeakMap,Bt=null;function pu(){if(Bt!==null)return Bt;try{let e=Fr()?.provider||"ollama";return Bt=mu[e]||4,Bt}catch{return 4}}function hu(){Bt=null}function it(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=Wt.get(e);if(s!==void 0)return s;let n=Math.ceil(t.length/pu());if(Wt.size>=Dr){let o=Dr>>1,r=Wt.keys();for(let i=0;i<o;i++)Wt.delete(r.next().value)}return Wt.set(e,n),n}function gu(t){if(Os.has(t))return Os.get(t);let e=JSON.stringify(t);return Os.set(t,e),e}function kt(t){let s=4;if(t.content&&(s+=it(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=it(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=it(o):o&&(s+=it(JSON.stringify(o)))}return s}function Ae(t){let e=0;for(let s of t)e+=kt(s);return e}function $u(t,e){if(t&&t.length===e.length){let r=!1;for(let i=0;i<e.length;i++)if(t[i]!==e[i]){r=!0;break}if(!r)return 0}let s=t?t.length:0,n=e.length,o=0;for(let r=s;r<n;r++)o+=kt(e[r]);return o}function Cn(t){return!t||t.length===0?0:it(JSON.stringify(t))}function Rn(){return Fr()?.contextWindow||32768}function yu(t,e){let s=Ae(t),n=Cn(e),o=s+n,r=Rn(),i=r>0?o/r*100:0,c=0,l=0,u=0;for(let d of t){let f=kt(d);d.role==="system"?c+=f:d.role==="tool"?u+=f:l+=f}return{used:o,limit:r,percentage:Math.round(i*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:n},messageCount:t.length}}var Ur=.75,Wr=.1,Br=10,wu=200,bu=500;function Hr(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
49
|
`);if(o.length<=10){let p=Math.floor(n*.6),g=Math.floor(n*.4),y=t.substring(0,p),$=t.substring(t.length-g);return y+`
|
|
46
50
|
...(${t.length} chars total)...
|
|
47
51
|
`+$}let r=Math.floor(o.length*.4),i=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-i&&f<m;p--)d.push(o[p]),f+=o[p].length+1;d.reverse();let h=o.length-c.length-d.length;return c.join(`
|
|
48
52
|
`)+`
|
|
49
53
|
...(${h} lines omitted, ${o.length} total)...
|
|
50
54
|
`+d.join(`
|
|
51
|
-
`)}function
|
|
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
|
|
55
|
+
`)}function Ht(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:bu,n=e==="aggressive"?50:e==="medium"?100:wu;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:Hr(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
|
|
56
|
+
...(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 xu(t,e,s={}){let n=s.threshold??Ur,o=s.safetyMargin??Wr,r=s.keepRecent??Br,i=Rn(),c=Cn(e),l=Math.floor(i*(n-o)),u=l-c,d=Ae(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),y=t.slice(p,g),$=t.slice(g),x=y.filter(S=>!S._compacted);if(x.length>=6)try{let{compactMessages:S}=jr(),C=await S(x);if(C){let I=[...y.filter(ne=>ne._compacted),C.message],V=rt(h,I,$),D=Ae(V);if(D+c<=l)return{messages:V,compressed:!0,compacted:!0,tokensRemoved:m-D};y=I}}catch(S){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",S.message)}let O=(f-l)/l,k=y.map(S=>Ht(S,"light")),v=rt(h,k,$),T=Ae(v);if(T+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-T};if(k=y.map(S=>Ht(S,"medium")),v=rt(h,k,$),T=Ae(v),T+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-T};if(k=y.map(S=>Ht(S,"aggressive")),v=rt(h,k,$),T=Ae(v),T+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-T};for(;k.length>0&&T>u;){let S=k.shift();T-=kt(S)}return v=rt(h,k,$),T=Ae(v),{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-T}}function rt(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function _u(t,e){if(!t)return"";if(it(t)<=e)return t;let n=e*4,o=t.split(`
|
|
53
57
|
`),r=Math.floor(n*.6),i=Math.floor(n*.4),c="",l=0;for(let h of o){if(c.length+h.length+1>r)break;c+=(c?`
|
|
54
58
|
`:"")+h,l++}let u="",d=0;for(let h=o.length-1;h>=l;h--){let p=o[h]+(u?`
|
|
55
59
|
`:"")+u;if(p.length>i)break;u=p,d++}let m=`
|
|
56
60
|
|
|
57
61
|
... (${o.length-l-d} lines omitted, ${o.length} total) ...
|
|
58
62
|
|
|
59
|
-
`;return c+m+u}var
|
|
60
|
-
`);g=$.pop()||"";for(let x of $){let O=x.trim();if(!O||!O.startsWith("data: "))continue;let k=O.slice(6);if(k==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let v;try{v=JSON.parse(k)}catch{continue}let
|
|
63
|
+
`;return c+m+u}var ku=6;function vu(t,e){let s=Rn(),n=Cn(e),o=Math.floor(s*.5)-n,r=Ae(t),i=null,c=0;t.length>0&&t[0].role==="system"&&(i=t[0],c=1);let l=Math.max(c,t.length-ku),u=t.slice(c,l),d=t.slice(l),f=u.map(p=>Ht(p,"aggressive")),m=rt(i,f,d),h=Ae(m);for(;f.length>0&&h>o;){let p=f.shift();h-=kt(p)}return m=rt(i,f,d),h=Ae(m),{messages:m,tokensRemoved:r-h}}Gr.exports={estimateTokens:it,estimateMessageTokens:kt,estimateMessagesTokens:Ae,estimateDeltaTokens:$u,estimateToolsTokens:Cn,serializeMessage:gu,getContextWindow:Rn,getUsage:yu,compressMessage:Ht,compressToolResult:Hr,fitToContext:xu,forceCompress:vu,truncateFileContent:_u,invalidateTokenRatioCache:hu,COMPRESSION_THRESHOLD:Ur,SAFETY_MARGIN:Wr,KEEP_RECENT:Br}});var Yr=M((zg,Jr)=>{var zr=require("axios"),{BaseProvider:Su}=_t(),{serializeMessage:Gg}=Re(),Kr={"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}},Ns=class extends Su{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Kr,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 i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);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),i=n.maxTokens||r?.maxTokens||16384,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:i,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await zr.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),i=n.maxTokens||r?.maxTokens||16384,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:i,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await zr.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},g="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let $=g.split(`
|
|
64
|
+
`);g=$.pop()||"";for(let x of $){let O=x.trim();if(!O||!O.startsWith("data: "))continue;let k=O.slice(6);if(k==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let v;try{v=JSON.parse(k)}catch{continue}let T=v.choices?.[0]?.delta;if(T&&(T.content&&(c(T.content),h+=T.content),T.tool_calls))for(let S of T.tool_calls){let C=S.index??0;p[C]||(p[C]={id:S.id||"",name:"",arguments:""}),S.id&&(p[C].id=S.id),S.function?.name&&(p[C].name+=S.function.name),S.function?.arguments&&(p[C].arguments+=S.function.arguments)}}}),d.data.on("error",y=>{n.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`openai-${Date.now()}`,function:{name:s.name,arguments:s.arguments}}))}};Jr.exports={OpenAIProvider:Ns,OPENAI_MODELS:Kr}});var Zr=M((Jg,Qr)=>{var Xr=require("axios"),{BaseProvider:Eu}=_t(),{serializeMessage:Kg}=Re(),Vr={"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}},Tu="2023-06-01",Ms=class extends Eu{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Vr,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Tu}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
65
|
|
|
62
66
|
`:"")+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 i=this._getMessageCacheKey(o);this._messageStringCache.set(i,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),i=this.getModel(o),c=n.maxTokens||i?.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 Xr.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),i=this.getModel(o),c=n.maxTokens||i?.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 Xr.post(`${this.baseUrl}/messages`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let g=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${g}`)}return new Promise((p,g)=>{let y="",$=[],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",k=>{O+=k.toString();let v=O.split(`
|
|
63
|
-
`);O=v.pop()||"";for(let
|
|
64
|
-
`);g=$.pop()||"";for(let x of $){let O=x.trim();if(!O||!O.startsWith("data: "))continue;let k=O.slice(6);if(k==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let v;try{v=JSON.parse(k)}catch{continue}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}}}),i.data.on("error",m=>{n.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),i.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(r(m.message.content),u+=m.message.content),m.message?.tool_calls&&(d=d.concat(m.message.tool_calls))}catch{}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||{}}}))}};ri.exports={LocalProvider:
|
|
67
|
-
`)}}function
|
|
68
|
-
`)}function
|
|
69
|
-
`),c}catch(c){throw o.stop(),c}}async function
|
|
67
|
+
`);O=v.pop()||"";for(let T of v){let S=T.trim();if(S.startsWith("data: ")){let C=S.slice(6),F;try{F=JSON.parse(C)}catch{continue}switch(F.type){case"content_block_start":{let I=F.content_block;I?.type==="tool_use"&&(x=$.length,$.push({id:I.id,name:I.name,inputJson:""}));break}case"content_block_delta":{let I=F.delta;I?.type==="text_delta"&&I.text&&(l(I.text),y+=I.text),I?.type==="input_json_delta"&&I.partial_json!==void 0&&x>=0&&($[x].inputJson+=I.partial_json);break}case"content_block_stop":x=-1;break;case"message_stop":p({content:y,tool_calls:this._buildToolCalls($)});return}}}}),h.data.on("error",k=>{n.signal?.aborted||g(new Error(`Stream error: ${k.message}`))}),h.data.on("end",()=>{p({content:y,tool_calls:this._buildToolCalls($)})})})}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}_buildToolCalls(e){return e.filter(s=>s.name).map(s=>{let n={};if(s.inputJson)try{n=JSON.parse(s.inputJson)}catch{n=s.inputJson}return{id:s.id||`anthropic-${Date.now()}`,function:{name:s.name,arguments:n}}})}};Qr.exports={AnthropicProvider:Ms,ANTHROPIC_MODELS:Vr}});var si=M((Xg,ni)=>{var ei=require("axios"),{BaseProvider:Cu}=_t(),{serializeMessage:Yg}=Re(),ti={"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}},Ps=class extends Cu{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||ti,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 i=this._messageStringCache.get(o);this._messageFormatCache.set(n,i),s.push(i);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),i=n.maxTokens||r?.maxTokens||8192,{messages:c}=this.formatMessages(e),l={model:o,messages:c,max_tokens:i,temperature:n.temperature??this.temperature};s&&s.length>0&&(l.tools=s);let u=await ei.post(`${this.baseUrl}/chat/completions`,l,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(u.data)}async stream(e,s,n={}){let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||8192,c=n.onToken||(()=>{}),{messages:l}=this.formatMessages(e),u={model:o,messages:l,max_tokens:i,temperature:n.temperature??this.temperature,stream:!0};s&&s.length>0&&(u.tools=s);let d;try{d=await ei.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},g="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let $=g.split(`
|
|
68
|
+
`);g=$.pop()||"";for(let x of $){let O=x.trim();if(!O||!O.startsWith("data: "))continue;let k=O.slice(6);if(k==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let v;try{v=JSON.parse(k)}catch{continue}let T=v.choices?.[0]?.delta;if(T&&(T.content&&(c(T.content),h+=T.content),T.tool_calls))for(let S of T.tool_calls){let C=S.index??0;p[C]||(p[C]={id:S.id||"",name:"",arguments:""}),S.id&&(p[C].id=S.id),S.function?.name&&(p[C].name+=S.function.name),S.function?.arguments&&(p[C].arguments+=S.function.arguments)}}}),d.data.on("error",y=>{n.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:s.name,arguments:s.arguments}}))}};ni.exports={GeminiProvider:Ps,GEMINI_MODELS:ti}});var ii=M((Vg,ri)=>{var An=require("axios"),{BaseProvider:Ru}=_t(),oi="http://localhost:11434",Ls=class extends Ru{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||oi,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 An.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$/,""),i=32768;try{let c=await An.post(`${this.baseUrl}/api/show`,{name:o},{timeout:5e3}),l=c.data?.model_info||c.data?.details||{};i=l["general.context_length"]||l["llama.context_length"]||this._parseContextFromModelfile(c.data?.modelfile)||32768}catch{}this.models[r]={id:r,name:n.name,maxTokens:Math.min(8192,Math.floor(i*.1)),contextWindow:i}}!this.defaultModel&&Object.keys(this.models).length>0&&(this.defaultModel=Object.keys(this.models)[0]),this._modelsLoaded=!0}catch{this.models={},this._modelsLoaded=!1}return this.models}getModels(){return this.models}getModelNames(){return Object.keys(this.models)}_formatMessages(e){return e.map(s=>{if(s.role==="user"&&Array.isArray(s.content)){let n=[],o=[];for(let i of s.content)i.type==="text"?n.push(i.text??""):i.type==="image"&&i.data&&o.push(i.data);let r={role:"user",content:n.join(`
|
|
69
|
+
`)};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 An.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict: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||(()=>{}),i;try{i=await An.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict: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",()=>{i.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),i.data.on("data",m=>{f+=m.toString();let h=f.split(`
|
|
70
|
+
`);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let g;try{g=JSON.parse(p)}catch{continue}if(g.message?.content&&(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}}}),i.data.on("error",m=>{n.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),i.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(r(m.message.content),u+=m.message.content),m.message?.tool_calls&&(d=d.concat(m.message.tool_calls))}catch{}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||{}}}))}};ri.exports={LocalProvider:Ls,DEFAULT_LOCAL_URL:oi}});var vt=M((Qg,mi)=>{var at=require("fs"),Is=require("path"),ai={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:{}},On=[],Xe={};function Au(t,e,s,n){if(On.push({provider:t,model:e,input:s,output:n}),Xe[t]!==void 0){let o=di(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
|
|
71
|
+
`)}}function qs(t,e){let s=ai[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function ci(t){let e=qs(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function li(){let t={};for(let r of On){let i=`${r.provider}:${r.model}`;t[i]||(t[i]={provider:r.provider,model:r.model,input:0,output:0}),t[i].input+=r.input,t[i].output+=r.output}let e=Object.values(t).map(r=>({...r,cost:ci(r)})),s=e.reduce((r,i)=>r+i.cost,0),n=e.reduce((r,i)=>r+i.input,0),o=e.reduce((r,i)=>r+i.output,0);return{totalCost:s,totalInput:n,totalOutput:o,breakdown:e}}function Ou(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=li();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 i=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: ${i}`)}return o.push(""),o.push(` Total: ${e.toLocaleString()} in + ${s.toLocaleString()} out = $${t.toFixed(4)}`),o.join(`
|
|
72
|
+
`)}function Nu(t,e,s,n){let o=qs(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Mu(){On=[]}function Pu(t,e){Xe[t]=e}function Lu(t){delete Xe[t]}function Iu(){return{...Xe}}function ui(t){let e=0;for(let s of On)s.provider===t&&(e+=ci(s));return e}function di(t){let e=ui(t),s=Xe[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 fi(){let t=Is.join(process.cwd(),".nex","config.json");if(at.existsSync(t))try{let e=JSON.parse(at.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Xe={...e.costLimits})}catch{}}function qu(){let t=Is.join(process.cwd(),".nex"),e=Is.join(t,"config.json"),s={};if(at.existsSync(e))try{s=JSON.parse(at.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Xe,at.existsSync(t)||at.mkdirSync(t,{recursive:!0}),at.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function ju(){Xe={}}fi();mi.exports={PRICING:ai,trackUsage:Au,getSessionCosts:li,formatCosts:Ou,formatCostHint:Nu,resetCosts:Mu,getPricing:qs,setCostLimit:Pu,removeCostLimit:Lu,getCostLimits:Iu,getProviderSpend:ui,checkBudget:di,loadCostLimits:fi,saveCostLimits:qu,resetCostLimits:ju}});var Nn=M((Zg,pi)=>{var Gt=ge(),Du={"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 Fu(){return Gt.getActiveModel()}function Uu(t){return Gt.setActiveModel(t)}function Wu(){return Gt.getModelNames()}function Bu(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 Hu(t,e){let{C:s}=oe(),{Spinner:n}=oe(),o=new n("Thinking...");o.start();let r=!0,i="";try{let c=await Gt.callStream(t,e,{onToken:l=>{r&&(o.stop(),process.stdout.write(`${s.blue}`),r=!1),process.stdout.write(l),i+=l}});return r?o.stop():process.stdout.write(`${s.reset}
|
|
73
|
+
`),c}catch(c){throw o.stop(),c}}async function Gu(t,e){return Gt.callChat(t,e)}pi.exports={MODELS:Du,getActiveModel:Fu,setActiveModel:Uu,getModelNames:Wu,callOllamaStream:Hu,callOllama:Gu,parseToolArgs:Bu}});var $i=M((e$,gi)=>{var Mn=require("path"),{C:b}=oe(),{confirm:zu,getAutoConfirm:Ku}=Me(),hi=2e3;function zt(t,e){let s=t.split(`
|
|
70
74
|
`),n=e.split(`
|
|
71
|
-
`),o=[],r=s.length,i=n.length;if(r>hi||i>hi){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(i+1).fill(0));for(let f=1;f<=r;f++)for(let m=1;m<=i;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=i,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
|
|
72
|
-
${b.bold}${b.cyan} Diff: ${t}${b.reset}`);let o=
|
|
73
|
-
${b.bold}${b.cyan} File exists \u2014 showing changes: ${t}${b.reset}`);let n=
|
|
75
|
+
`),o=[],r=s.length,i=n.length;if(r>hi||i>hi){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(i+1).fill(0));for(let f=1;f<=r;f++)for(let m=1;m<=i;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=i,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 Ju(t,e,s,n=3){console.log(`
|
|
76
|
+
${b.bold}${b.cyan} Diff: ${t}${b.reset}`);let o=zt(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 i=Math.max(0,r[0]-n),c=Math.min(o.length,r[r.length-1]+n+1);i>0&&console.log(`${b.gray} ...${b.reset}`);for(let l=i;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 Yu(t,e,s){console.log(`
|
|
77
|
+
${b.bold}${b.cyan} File exists \u2014 showing changes: ${t}${b.reset}`);let n=zt(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${b.gray} (identical content)${b.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${b.gray} ...(${o-r} more changes)${b.reset}`);break}switch(i.type){case"remove":console.log(`${b.red} - ${i.line}${b.reset}`),r++;break;case"add":console.log(`${b.green} + ${i.line}${b.reset}`),r++;break;default:r>0&&console.log(`${b.gray} ${i.line}${b.reset}`)}}console.log()}function Xu(t,e){console.log(`
|
|
74
78
|
${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
|
|
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 i=
|
|
77
|
-
`)}function
|
|
79
|
+
`),n=s.slice(0,20);for(let o of n)console.log(`${b.green} + ${o}${b.reset}`);s.length>20&&console.log(`${b.gray} ...+${s.length-20} more lines${b.reset}`),console.log()}async function Vu(t){return Ku()?!0:zu(` ${t}?`)}function Qu(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
|
|
80
|
+
${b.bold}${b.cyan} Side-by-side: ${t}${b.reset}`),console.log(` ${b.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${b.reset}`);let i=zt(e,s),c=[],l=0;for(;l<i.length;)if(i[l].type==="same")c.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let h=[];for(;l<i.length&&i[l].type==="remove";)h.push(i[l].line),l++;let p=[];for(;l<i.length&&i[l].type==="add";)p.push(i[l].line),l++;let g=Math.max(h.length,p.length);for(let y=0;y<g;y++)c.push({left:y<h.length?h[y]:"",right:y<p.length?p[y]:"",type:"changed"})}else i[l].type==="add"&&(c.push({left:"",right:i[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)}`,y=p.right?`${b.green}${m(p.right,r)}${b.reset}`:`${m("",r)}`;console.log(` ${g}\u2502${y}`)}}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}
|
|
81
|
+
`)}function Zu(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],c=Mn.isAbsolute(t)?Mn.relative(process.cwd(),t):t,l=zt(e,s),u=1,d=1;for(let k of l)k.type==="same"?(k.oldLine=u++,k.newLine=d++):k.type==="remove"?(k.oldLine=u++,k.newLine=null):(k.oldLine=null,k.newLine=d++);let f=0,m=0;for(let k of l)k.type==="add"?f++:k.type==="remove"&&m++;if(console.log(`
|
|
78
82
|
${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":""}`),i.length>0){let k=i.filter(
|
|
83
|
+
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),i.length>0){let k=i.filter(C=>C.severity==="error").length,v=i.filter(C=>C.severity==="warn").length,T=i.filter(C=>C.severity==="info").length,S=[];k>0&&S.push(`${b.red}${k} error${k!==1?"s":""}${b.dim}`),v>0&&S.push(`${b.yellow}${v} warning${v!==1?"s":""}${b.dim}`),T>0&&S.push(`${b.cyan}${T} info${T!==1?"s":""}${b.dim}`),h.push(`found ${S.join(", ")}`)}console.log(` ${b.dim}\u23BF ${h.join(", ")}${b.reset}`);let g=[];l.forEach((k,v)=>{k.type!=="same"&&g.push(v)});let y=[],$=null,x=null;for(let k of g){let v=Math.max(0,k-r),T=Math.min(l.length-1,k+r);$===null?($=v,x=T):(v<=x+1||(y.push([$,x]),$=v),x=T)}$!==null&&y.push([$,x]);let O=" ";for(let k=0;k<y.length;k++){k>0&&console.log(`${O}${b.dim}\xB7\xB7\xB7${b.reset}`);let[v,T]=y[k];for(let S=v;S<=T;S++){let C=l[S],F=C.newLine!=null?C.newLine:C.oldLine,I=String(F).padStart(4),V=C.type!=="remove"?i.filter(D=>D.line===C.newLine):[];C.type==="remove"?console.log(`${O}${b.red}${I} -${C.line}${b.reset}`):C.type==="add"?console.log(`${O}${b.green}${I} +${C.line}${b.reset}`):console.log(`${O}${b.dim}${I}${b.reset} ${C.line}`);for(let D of V){let ne=b.cyan,ie="\u2139";D.severity==="error"?(ne=b.red,ie="\u2716"):D.severity==="warn"&&(ne=b.yellow,ie="\u26A0"),console.log(`${O} ${ne}${ie} ${D.message}${b.reset}`)}}}console.log()}function ed(t,e,s={}){let n=Mn.isAbsolute(t)?Mn.relative(process.cwd(),t):t,o=e.split(`
|
|
80
84
|
`),r=s.annotations||[];console.log(`
|
|
81
|
-
${b.cyan}\u23FA${b.reset} ${b.bold}Create(${n})${b.reset}`);let i=[`${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}`),i.push(`found ${h.join(", ")}`)}console.log(` ${b.dim}\u23BF ${i.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,y="\u2139";p.severity==="error"?(g=b.red,y="\u2716"):p.severity==="warn"&&(g=b.yellow,y="\u26A0"),console.log(`${l} ${g}${y} ${p.message}${b.reset}`)}}o.length>20&&console.log(`${l}${b.dim} ...+${o.length-20} more lines${b.reset}`),console.log()}gi.exports={diffLines:
|
|
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 i="chore",c=t.join(" ").toLowerCase();c.includes("test")?i="test":c.includes("readme")||c.includes("doc")?i="docs":o>r*2?i="feat":r>o?i="refactor":i="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function
|
|
85
|
+
${b.cyan}\u23FA${b.reset} ${b.bold}Create(${n})${b.reset}`);let i=[`${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}`),i.push(`found ${h.join(", ")}`)}console.log(` ${b.dim}\u23BF ${i.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,y="\u2139";p.severity==="error"?(g=b.red,y="\u2716"):p.severity==="warn"&&(g=b.yellow,y="\u26A0"),console.log(`${l} ${g}${y} ${p.message}${b.reset}`)}}o.length>20&&console.log(`${l}${b.dim} ...+${o.length-20} more lines${b.reset}`),console.log()}gi.exports={diffLines:zt,showEditDiff:Ju,showWriteDiff:Yu,showNewFilePreview:Xu,confirmFileChange:Vu,showSideBySideDiff:Qu,showClaudeDiff:Zu,showClaudeNewFile:ed}});var ct=M((t$,bi)=>{var yi=require("util").promisify(require("child_process").exec),td=require("util").promisify(require("child_process").execFile),{C:Q}=oe();async function js(t){try{let{stdout:e}=await yi(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Pn(...t){try{let{stdout:e}=await td("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function nd(){return await js("git rev-parse --is-inside-work-tree")==="true"}async function sd(){return await js("git branch --show-current")}async function Ds(){try{let{stdout:t}=await yi("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
86
|
+
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function Ln(t=!1){return await js(`git diff ${t?"--cached":""}`)||""}async function Fs(){return(await Ds()).map(e=>e.file)}async function wi(){let t=await Fs();if(t.length===0)return null;let e=await Ln(),n=await Ln(!0)||e,o=0,r=0;if(n){let d=n.split(`
|
|
87
|
+
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&r++}else o=t.length;let i="chore",c=t.join(" ").toLowerCase();c.includes("test")?i="test":c.includes("readme")||c.includes("doc")?i="docs":o>r*2?i="feat":r>o?i="refactor":i="fix";let l=t.slice(0,3).map(d=>d.split("/").pop());return{summary:`${i}: update ${l.join(", ")}${t.length>3?` (+${t.length-3} more)`:""}`,type:i,files:t,stats:{additions:o,deletions:r}}}async function od(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Pn("checkout","-b",s)!==null?s:null}async function rd(t){return await Pn("add","-A"),await Pn("commit","-m",t)?await Pn("rev-parse","--short","HEAD"):null}async function id(){let t=await wi();if(!t)return`${Q.dim}No changes${Q.reset}`;let e=[];e.push(`
|
|
84
88
|
${Q.bold}${Q.cyan}Git Diff Summary:${Q.reset}`),e.push(` ${Q.green}+${t.stats.additions}${Q.reset} ${Q.red}-${t.stats.deletions}${Q.reset} in ${t.files.length} file(s)`),e.push(`
|
|
85
89
|
${Q.bold}${Q.cyan}Files:${Q.reset}`);for(let s of t.files.slice(0,20))e.push(` ${Q.dim}${s}${Q.reset}`);return t.files.length>20&&e.push(` ${Q.dim}...+${t.files.length-20} more${Q.reset}`),e.push(`
|
|
86
90
|
${Q.bold}${Q.cyan}Suggested message:${Q.reset}`),e.push(` ${Q.cyan}${t.summary}${Q.reset}
|
|
87
91
|
`),e.join(`
|
|
88
|
-
`)}async function
|
|
92
|
+
`)}async function ad(){return(await Ds()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function cd(){let t=await Fs();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 Ln();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
|
|
89
93
|
...(truncated)`:s;e.push(`
|
|
90
94
|
DIFF:
|
|
91
95
|
${n}`)}return e.join(`
|
|
92
|
-
`)}bi.exports={isGitRepo:
|
|
96
|
+
`)}bi.exports={isGitRepo:nd,getCurrentBranch:sd,getStatus:Ds,getDiff:Ln,getChangedFiles:Fs,analyzeDiff:wi,createBranch:od,commit:rd,formatDiffSummary:id,getDiffContext:cd,getMergeConflicts:ad}});var Et=M((n$,xi)=>{var Us=require("fs").promises,ld=50,Fe=[],St=[];function ud(t,e,s,n){for(Fe.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});Fe.length>ld;)Fe.shift();St.length=0}async function dd(){if(Fe.length===0)return null;let t=Fe.pop();if(t.oldContent===null)try{await Us.unlink(t.filePath)}catch{}else await Us.writeFile(t.filePath,t.oldContent,"utf-8");return St.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function fd(){if(St.length===0)return null;let t=St.pop();return await Us.writeFile(t.filePath,t.newContent,"utf-8"),Fe.push(t),{tool:t.tool,filePath:t.filePath}}function md(t=10){return Fe.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function pd(){return Fe.length}function hd(){return St.length}function gd(){Fe.length=0,St.length=0}xi.exports={recordChange:ud,undo:dd,redo:fd,getHistory:md,getUndoCount:pd,getRedoCount:hd,clearHistory:gd}});var Kt=M((s$,Ti)=>{var ve=require("fs"),Tt=require("path"),we=[];function Ws(){return Tt.join(process.cwd(),".nex","skills")}function _i(){return Tt.join(process.cwd(),".nex","config.json")}function $d(){let t=Ws();return ve.existsSync(t)||ve.mkdirSync(t,{recursive:!0}),t}function Bs(){let t=_i();if(!ve.existsSync(t))return[];try{let e=JSON.parse(ve.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function ki(t){let e=_i(),s={};if(ve.existsSync(e))try{s=JSON.parse(ve.readFileSync(e,"utf-8"))}catch{s={}}s.skills||(s.skills={}),s.skills.disabled=t;let n=Tt.dirname(e);ve.existsSync(n)||ve.mkdirSync(n,{recursive:!0}),ve.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function vi(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 Si(t){try{let e=ve.readFileSync(t,"utf-8").trim();return e?{name:Tt.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function Ei(t){try{let e=require(t),{valid:s,errors:n}=vi(e,t);return s?{name:e.name||Tt.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
97
|
${n.join(`
|
|
94
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
98
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function yd(){we=[];let t=Ws();if(!ve.existsSync(t))return we;let e=Bs(),s;try{s=ve.readdirSync(t)}catch{return we}for(let n of s){let o=Tt.join(t,n),r;try{r=ve.statSync(o)}catch{continue}if(!r.isFile())continue;let i=null;n.endsWith(".md")?i=Si(o):n.endsWith(".js")&&(i=Ei(o)),i&&(i.enabled=!e.includes(i.name),we.push(i))}return we}function wd(){let t=[];for(let e of we)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
95
99
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
96
100
|
${t.join(`
|
|
97
101
|
|
|
98
|
-
`)}`}function
|
|
102
|
+
`)}`}function bd(){let t=[];for(let e of we)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function xd(){let t=[];for(let e of we)if(e.enabled)for(let s of e.tools)t.push({type:"function",function:{name:`skill_${s.function.name}`,description:`[Skill:${e.name}] ${s.function.description}`,parameters:s.function.parameters}});return t}async function _d(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of we)if(n.enabled){for(let o of n.tools)if(o.function.name===s&&o.execute)try{let 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 kd(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of we)if(o.enabled){for(let r of o.commands)if(r.cmd===e&&r.handler){try{r.handler(n)}catch(i){console.error(`Skill command error (${e}): ${i.message}`)}return!0}}return!1}function vd(){return we.map(t=>({name:t.name,type:t.type,enabled:t.enabled,description:t.description||"",commands:t.commands.length,tools:t.tools.length,filePath:t.filePath}))}function Sd(t){let e=we.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Bs().filter(n=>n!==t);return ki(s),!0}function Ed(t){let e=we.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Bs();return s.includes(t)||(s.push(t),ki(s)),!0}function Td(){return we}Ti.exports={initSkillsDir:$d,loadAllSkills:yd,getSkillInstructions:wd,getSkillCommands:bd,getSkillToolDefinitions:xd,routeSkillCall:_d,handleSkillCommand:kd,listSkills:vd,enableSkill:Sd,disableSkill:Ed,getLoadedSkills:Td,_getSkillsDir:Ws,_validateScriptSkill:vi,_loadMarkdownSkill:Si,_loadScriptSkill:Ei}});var qn=M((o$,Mi)=>{var{spawn:Cd}=require("child_process"),Rd=require("path"),Ci=require("fs"),Ue=new Map;function Ad(){return Rd.join(process.cwd(),".nex","config.json")}function Hs(){let t=Ad();if(!Ci.existsSync(t))return{};try{return JSON.parse(Ci.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function In(t,e,s={},n=1e4){return new Promise((o,r)=>{let i=`${Date.now()}-${Math.random().toString(36).slice(2,6)}`,c=JSON.stringify({jsonrpc:"2.0",id:i,method:e,params:s})+`
|
|
99
103
|
`,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===i){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 Ri(t,e){if(
|
|
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),i=[],c={...e},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=
|
|
104
|
+
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===i){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 Ri(t,e){if(Ue.has(t))return Ue.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let i of s)process.env[i]&&(n[i]=process.env[i]);let o=Cd(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await In(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await In(o,"tools/list",{});return r.tools=i&&i.tools||[],Ue.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Ai(t){let e=Ue.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Ue.delete(t),!0}function Od(){for(let[t]of Ue)Ai(t)}async function Oi(t,e,s={}){let n=Ue.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await In(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(`
|
|
105
|
+
`):JSON.stringify(o)}function Ni(){let t=[];for(let[e,s]of Ue)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 Nd(){return Ni().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Md(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 Oi(n,o,e)}function Pd(){let t=Hs();return Object.entries(t).map(([e,s])=>{let n=Ue.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function Ld(){let t=Hs(),e=[];for(let[s,n]of Object.entries(t))try{let o=await Ri(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Mi.exports={loadMCPConfig:Hs,sendRequest:In,connectServer:Ri,disconnectServer:Ai,disconnectAll:Od,callTool:Oi,getAllTools:Ni,getMCPToolDefinitions:Nd,routeMCPCall:Md,listServers:Pd,connectAll:Ld}});var Gs=M((r$,qi)=>{var{getSkillToolDefinitions:Id}=Kt(),{getMCPToolDefinitions:qd}=qn(),jn=new Map;function Pi(){let{TOOL_DEFINITIONS:t}=We();return[...t,...Id(),...qd()]}function Li(t){if(jn.has(t))return jn.get(t);let s=Pi().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return jn.set(t,n),n}function jd(){jn.clear()}function Dn(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=Ii(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Ii(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 i=1;i<=n;i++)o[r][i]=t[r-1]===e[i-1]?o[r-1][i-1]:1+Math.min(o[r-1][i],o[r][i-1],o[r-1][i-1]);return o[s][n]}function Dd(t,e){let s=Li(t);if(s===null){let d=Pi().map(m=>m.function.name),f=Dn(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
106
|
+
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),i=[],c={...e},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=Dn(u,r);d&&!o.includes(d)?(c[u]=e[d],delete c[d],l=!0):i.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=Dn(u,o);d&&!(d in c)?(c[d]=e[u],delete c[u],l=!0):l||i.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 i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
|
|
103
107
|
`+i.map(u=>` - ${u}`).join(`
|
|
104
108
|
`)+`
|
|
105
109
|
|
|
106
|
-
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}qi.exports={validateToolArgs:
|
|
110
|
+
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}qi.exports={validateToolArgs:Dd,closestMatch:Dn,levenshtein:Ii,getCachedSchema:Li,clearSchemaCache:jd}});var Ui=M((i$,Fi)=>{var{levenshtein:Fn}=Gs(),Fd=200,Ud=.3,Wd=2;function zs(t){return t.replace(/\r\n/g,`
|
|
107
111
|
`).replace(/\r/g,`
|
|
108
|
-
`).replace(/\t/g," ".repeat(
|
|
112
|
+
`).replace(/\t/g," ".repeat(Wd)).split(`
|
|
109
113
|
`).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
|
|
114
|
+
`)}function Bd(t,e){if(t.includes(e))return e;let s=zs(t),n=zs(e);if(!s.includes(n))return null;let o=t.split(`
|
|
111
115
|
`),r=s.split(`
|
|
112
116
|
`),i=n.split(`
|
|
113
117
|
`),c=i[0],l=i[i.length-1];for(let u=0;u<=r.length-i.length;u++){let d=!0;for(let f=0;f<i.length;f++)if(r[u+f]!==i[f]){d=!1;break}if(d)return o.slice(u,u+i.length).join(`
|
|
114
|
-
`)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(n)!==-1)return o[u]}return null}function
|
|
118
|
+
`)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(n)!==-1)return o[u]}return null}function Hd(t,e){if(!t||!e)return null;let s=t.split(`
|
|
115
119
|
`),o=e.split(`
|
|
116
|
-
`).length;return s.length===0||o===0?null:o===1?
|
|
117
|
-
`),u=
|
|
118
|
-
`),h=
|
|
119
|
-
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],c=r+1;for(let l of
|
|
120
|
-
`).filter(Boolean),
|
|
120
|
+
`).length;return s.length===0||o===0?null:o===1?Gd(s,e):Kd(s,e,o)}function ji(t){return Math.max(1,Math.floor(t/Fd))}function Di(t,e){return t<=Math.ceil(e*Ud)}function Gd(t,e){let s=e.trim(),n=ji(t.length),o=null,r=1/0;for(let i=0;i<t.length;i+=n){let c=t[i];if(!c.trim())continue;let l=Fn(c.trim(),s);l<r&&(r=l,o={text:c,distance:l,line:i+1})}return o&&n>1&&(o=zd(t,s,o,n)||o,r=o.distance),Di(r,e.length)?o:null}function zd(t,e,s,n){let o=s.line-1,r=Math.max(0,o-n),i=Math.min(t.length-1,o+n),c=s.distance,l=null;for(let u=r;u<=i;u++){let d=t[u];if(!d.trim())continue;let f=Fn(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function Kd(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=ji(n),r=null,i=1/0;for(let c=0;c<n;c+=o){let l=t.slice(c,c+s).join(`
|
|
121
|
+
`),u=Fn(l,e);u<i&&(i=u,r={text:l,distance:u,line:c+1})}return r&&o>1&&(r=Jd(t,e,r,o,s,n)||r,i=r.distance),Di(i,e.length)?r:null}function Jd(t,e,s,n,o,r){let i=s.line-1,c=Math.max(0,i-n),l=Math.min(r-1,i+n),u=s.distance,d=null;for(let f=c;f<=l;f++){let m=t.slice(f,f+o).join(`
|
|
122
|
+
`),h=Fn(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}Fi.exports={normalizeWhitespace:zs,fuzzyFindText:Bd,findMostSimilar:Hd}});var Bi=M((c$,Wi)=>{var{C:a$}=oe(),Yd=[{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}],Xd=[{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 Vd(t,e){let s=e.split(`
|
|
123
|
+
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],c=r+1;for(let l of Yd)l.regex.test(i)&&n.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of Xd)l.ext&&!l.ext.includes(o)||l.regex.test(i)&&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}Wi.exports={runDiagnostics:Vd}});var Ys=M((l$,zi)=>{var Qd=require("fs").promises,Hi=require("path"),{exec:Zd}=require("util").promisify(require("child_process").exec),Ct=[],Js=null,Un=!1,Ks=0,ef=6e4;function Gi(t){return!(Ct.length===0||Js!==t||Date.now()-Ks>ef)}async function tf(t){if(!Un&&!Gi(t)){Un=!0,Js=t;try{try{let{stdout:n}=await Zd("rg --files",{cwd:t,timeout:5e3});Ct=n.split(`
|
|
124
|
+
`).filter(Boolean),Ks=Date.now(),Un=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await Qd.readdir(n,{withFileTypes:!0})}catch{return}for(let i of r){if(i.name==="node_modules"||i.name===".git"||i.name.startsWith("."))continue;let c=o?`${o}/${i.name}`:i.name;i.isDirectory()?await s(Hi.join(n,i.name),c):e.push(c)}};await s(t,""),Ct=e,Ks=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Un=!1}}}function nf(){return Ct}function sf(){return Js}function of(t){return Ct.filter(e=>Hi.basename(e)===t)}function rf(t){let e=t.toLowerCase();return Ct.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}zi.exports={refreshIndex:tf,getFileIndex:nf,getIndexedCwd:sf,findFileInIndex:of,searchIndex:rf,isIndexValid:Gi}});var Rt=M((u$,Xi)=>{var Wn=require("fs"),Hn=require("path"),Xs=require("os"),{execFile:af}=require("child_process"),{promisify:cf}=require("util"),Vs=cf(af),lf=Hn.join(".nex","servers.json"),Bn=Hn.join(Xs.tmpdir(),"nex-ssh-sockets");function uf(){return Hn.join(process.cwd(),lf)}function Ki(){let t=uf();if(!Wn.existsSync(t))return{};try{return JSON.parse(Wn.readFileSync(t,"utf-8"))}catch{return{}}}function df(t){let e=Ki();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 ff(){Wn.existsSync(Bn)||Wn.mkdirSync(Bn,{recursive:!0})}function Ji(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Xs.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),ff();let s=t.user?`${t.user}@${t.host}`:t.host,n=Hn.join(Bn,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function Yi(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,Xs.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function mf(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=Ji(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:c}=await Vs("ssh",[...o,r],{timeout:s,maxBuffer:4194304});return{stdout:i||"",stderr:c||"",exitCode:0}}catch(i){let c=typeof i.code=="number"?i.code:1,l=(i.stderr||i.message||"").toString();return{stdout:(i.stdout||"").toString(),stderr:l,exitCode:c,error:Gn(l,t)}}}async function pf(t,e,s,{timeout:n=12e4}={}){let o=Yi(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:c}=await Vs("scp",o,{timeout:n,maxBuffer:1048576});return i||c||`Uploaded ${e} \u2192 ${r}:${s}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(Gn(c,t)||c)}}async function hf(t,e,s,{timeout:n=12e4}={}){let o=Yi(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:c}=await Vs("scp",o,{timeout:n,maxBuffer:1048576});return i||c||`Downloaded ${r}:${e} \u2192 ${s}`}catch(i){let c=(i.stderr||i.message||"").toString();throw new Error(Gn(c,t)||c)}}function Gn(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
|
|
121
125
|
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
126
|
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
127
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
124
128
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
125
129
|
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")}Qi.exports={loadDeployConfigs:Vi,resolveDeployConfig
|
|
130
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function gf(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}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${s}${n}${o}${r}${i}`}Xi.exports={loadServerProfiles:Ki,resolveProfile:df,buildSSHArgs:Ji,sshExec:mf,scpUpload:pf,scpDownload:hf,enrichSSHError:Gn,formatProfile:gf,SSH_SOCKET_DIR:Bn}});var eo=M((d$,Qi)=>{var Jt=require("fs"),Qs=require("path"),$f=Qs.join(".nex","deploy.json");function Zs(){return Qs.join(process.cwd(),$f)}function Vi(){let t=Zs();if(!Jt.existsSync(t))return{};try{return JSON.parse(Jt.readFileSync(t,"utf-8"))}catch{return{}}}function yf(t){let e=Vi();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 wf(t){let e=Qs.join(process.cwd(),".nex");Jt.existsSync(e)||Jt.mkdirSync(e,{recursive:!0}),Jt.writeFileSync(Zs(),JSON.stringify(t,null,2)+`
|
|
131
|
+
`,"utf-8")}Qi.exports={loadDeployConfigs:Vi,resolveDeployConfig:yf,saveDeployConfigs:wf,getDeployConfigPath:Zs}});var Xt=M((f$,ta)=>{var to=null,Be=null,Yt=null,Zi=`Playwright is not installed. Install with:
|
|
128
132
|
npm install playwright && npx playwright install chromium
|
|
129
|
-
Then restart nex-code.`;function ea(){if(
|
|
130
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function
|
|
131
|
-
`)}function
|
|
133
|
+
Then restart nex-code.`;function ea(){if(Yt!==null)return Yt;try{require("playwright"),Yt=!0}catch{Yt=!1}return Yt}async function zn(){if(!ea())throw new Error(Zi);return to||(to=require("playwright")),(!Be||!Be.isConnected())&&(Be=await to.chromium.launch({headless:!0})),Be}async function bf(){if(Be){try{await Be.close()}catch{}Be=null}}process.on("exit",()=>{if(Be)try{Be.close()}catch{}});async function xf(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await zn()).newPage();try{await o.goto(t,{waitUntil:s,timeout:e});let r=await o.title(),i=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:i.substring(0,8e3)+(i.length>8e3?`
|
|
134
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function _f(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await zn()).newPage();try{await i.setViewportSize({width:e,height:s}),await i.goto(t,{waitUntil:"networkidle",timeout:o});let c=await i.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 i.title(),url:i.url()}}finally{await i.close()}}async function kf(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await zn()).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 i=await r.title();return`Clicked \u2014 now at: ${r.url()} (${i})`}finally{await r.close()}}async function vf(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 i=await(await zn()).newPage();try{return await i.goto(t,{waitUntil:"domcontentloaded",timeout:o}),await i.fill(e,String(s)),n&&(await i.keyboard.press("Enter"),await i.waitForLoadState("domcontentloaded")),`Filled "${e}" with value. ${n?`Submitted \u2192 ${i.url()}`:"Not submitted."}`}finally{await i.close()}}ta.exports={isPlaywrightAvailable:ea,browserNavigate:xf,browserScreenshot:_f,browserClick:kf,browserFill:vf,closeBrowser:bf,INSTALL_MSG:Zi}});var Kn=M((m$,na)=>{var{C:K}=oe(),Qt="",$e=[],Vt=0,lt=null;function Sf(t){lt=t}function Ef(t,e){Qt=t,$e=[],Vt=0;for(let n of e){Vt++;let o=`t${Vt}`;$e.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${Vt}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=$e.map(n=>({...n}));return lt&<("create",{name:t,tasks:s}),s}function Tf(t,e,s){let n=$e.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),lt&<("update",{id:t,status:e,result:s}),{...n}):null}function Cf(){return{name:Qt,tasks:$e.map(t=>({...t}))}}function Rf(){Qt="",$e=[],Vt=0,lt&<("clear",{})}function Af(){return $e.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=$e.find(n=>n.id===e);return s&&s.status==="done"}))}function Of(){if($e.length===0)return`${K.dim}No active tasks${K.reset}`;let t=[];Qt&&(t.push(` ${K.bold}${K.cyan}Tasks: ${Qt}${K.reset}`),t.push(` ${K.dim}${"\u2500".repeat(40)}${K.reset}`));for(let o of $e){let r,i;switch(o.status){case"done":r="\u2713",i=K.green;break;case"in_progress":r="\u2192",i=K.cyan;break;case"failed":r="\u2717",i=K.red;break;default:r="\xB7",i=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(` ${i}${r}${K.reset} ${K.bold}${o.id}${K.reset} ${u.padEnd(40)} ${i}${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=$e.filter(o=>o.status==="done").length,s=$e.filter(o=>o.status==="failed").length,n=$e.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(`
|
|
135
|
+
`)}function Nf(){return $e.length>0&&$e.some(t=>t.status==="pending"||t.status==="in_progress")}na.exports={createTasks:Ef,updateTask:Tf,getTaskList:Cf,clearTasks:Rf,getReadyTasks:Af,renderTaskList:Of,setOnChange:Sf,hasActiveTasks:Nf}});var so=M((p$,oa)=>{var{getActiveModel:Mf,getActiveProviderName:Pf}=ge(),Zt={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},en={"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"},tn={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Pe={};function sa(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Pe=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Pe={}}}sa();function no(){let e=Mf()?.id,s=Pf();return e&&Pe[e]?Pe[e]:s&&Pe[`${s}:*`]?Pe[`${s}:*`]:e&&en[e]?en[e]:s&&tn[s]?tn[s]:"full"}function Lf(t,e){return t&&Pe[t]?Pe[t]:e&&Pe[`${e}:*`]?Pe[`${e}:*`]:t&&en[t]?en[t]:e&&tn[e]?tn[e]:"full"}function If(t,e){let s=e||no();if(s==="full"||!Zt[s])return t;let n=new Set(Zt[s]);return t.filter(o=>n.has(o.function.name))}function qf(){let t=no(),e=Zt[t]?Zt[t].length:"all";return{tier:t,toolCount:e}}oa.exports={filterToolsForModel:If,getActiveTier:no,getModelTier:Lf,getTierInfo:qf,TIERS:Zt,MODEL_TIERS:en,PROVIDER_DEFAULT_TIER:tn,loadConfigOverrides:sa}});var ga=M((g$,ha)=>{var{callStream:jf,getActiveProviderName:Yn,getActiveModelId:Df,getConfiguredProviders:Ff,getProvider:ra,getActiveProvider:ia,parseModelSpec:aa}=ge(),{parseToolArgs:Uf}=Nn(),{filterToolsForModel:Wf,getModelTier:Jn}=so(),{trackUsage:Bf}=vt(),{MultiProgress:Hf,C:h$}=oe(),Gf=15,ca=5,la=3,Xn=new Map;function zf(t,e){let s=Xn.get(t);return s&&s!==e?!1:(Xn.set(t,e),!0)}function nn(t){Xn.delete(t)}function oo(){Xn.clear()}function ua(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 da(t,e,s){let n;for(let o=0;o<=la;o++)try{return await jf(t,e,s)}catch(r){if(n=r,o<la&&ua(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 Kf=new Set(["ask_user","task_list","spawn_agents"]),Jf=new Set(["write_file","edit_file","patch_file"]),Yf=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Xf=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function fa(t){return Xf.test(t)?"full":Yf.test(t)?"essential":"standard"}function ma(t){let e=Ff(),s=Yn(),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(Jn(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Vf={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function ro(t){if(t.model){let{provider:o,model:r}=aa(t.model),i=o?ra(o):ia(),c=o||Yn();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=Jn(r,c);return{provider:c,model:r,tier:l}}}let e=fa(t.task),s=Vf[e];if(s){let{provider:o,model:r}=aa(s),i=o?ra(o):ia(),c=o||Yn();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=Jn(r,c);return{provider:c,model:r,tier:l}}}let n=ma(e);if(n){let o=Jn(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function pa(t,e={}){let s=Math.min(t.max_iterations||10,Gf),n=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,o=[],r={input:0,output:0},i=new Set,l=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
|
|
132
136
|
|
|
133
137
|
TASK: ${t.task}
|
|
134
138
|
${t.context?`
|
|
@@ -150,66 +154,66 @@ TOOL STRATEGY:
|
|
|
150
154
|
ERROR RECOVERY:
|
|
151
155
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
152
156
|
- 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 y={};d&&(y.provider=d),f&&(y.model=f);try{for(let $=0;$<s;$++){let x=await da(l,g,y);if(!x||typeof x!="object")throw new Error("Empty or invalid response from provider");if(x.usage){let
|
|
155
|
-
...(truncated)`:ie,tool_call_id:V}}).catch(ne=>(D&&(
|
|
156
|
-
`)}catch(r){return o.stop(),
|
|
157
|
-
`);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let c=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[c]=l.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[c]=l}s=n[2]}return{frontmatter:e,body:s}}function ya(t){let e=
|
|
158
|
-
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of
|
|
157
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=ro(t),d=u.provider,f=u.model,m=u.tier,{TOOL_DEFINITIONS:h,executeTool:p}=We(),g=Wf(h.filter($=>!Kf.has($.function.name)),m);if(f&&!t._skipLog){let $=m?` (${m})`:"";process.stderr.write(` [sub-agent: ${d}:${f}${$}]
|
|
158
|
+
`)}let y={};d&&(y.provider=d),f&&(y.model=f);try{for(let $=0;$<s;$++){let x=await da(l,g,y);if(!x||typeof x!="object")throw new Error("Empty or invalid response from provider");if(x.usage){let C=x.usage.prompt_tokens||0,F=x.usage.completion_tokens||0;r.input+=C,r.output+=F;let I=d||Yn(),V=f||Df();Bf(I,V,C,F)}let O=x.content||"",k=x.tool_calls,v={role:"assistant",content:O||""};if(k&&k.length>0&&(v.tool_calls=k),l.push(v),!k||k.length===0){for(let C of i)nn(C);return{task:t.task,status:"done",result:O||"(no response)",toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}let T=k.map(C=>{let F=C.function.name,I=Uf(C.function.arguments),V=C.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!I)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${F}`,tool_call_id:V});let D=null;if(Jf.has(F)&&I.path){let ne=require("path"),ie=ne.isAbsolute(I.path)?I.path:ne.resolve(process.cwd(),I.path);if(i.has(ie)||!zf(ie,n))return Promise.resolve({role:"tool",content:`ERROR: File '${I.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:V});i.add(ie),D=ie}return o.push(F),p(F,I,{autoConfirm:!0,silent:!0}).then(ne=>{D&&(nn(D),i.delete(D));let ie=String(ne??"");return{role:"tool",content:ie.length>2e4?ie.substring(0,2e4)+`
|
|
159
|
+
...(truncated)`:ie,tool_call_id:V}}).catch(ne=>(D&&(nn(D),i.delete(D)),{role:"tool",content:`ERROR: ${ne.message}`,tool_call_id:V}))}),S=await Promise.all(T);l.push(...S),e.onUpdate&&e.onUpdate(`step ${$+1}/${s}`)}for(let $ of i)nn($);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 i)nn(x);return{task:t.task,status:"failed",result:`Error: ${$.message}`,toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}}async function Qf(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>ca)return`ERROR: Max ${ca} parallel agents allowed, got ${e.length}`;let s=e.map(r=>ro(r)),n=e.map((r,i)=>{let c=s[i],l=c.model?` [${c.model}]`:"",u=r.task.substring(0,44-l.length);return`Agent ${i+1}${l}: ${u}${r.task.length>u.length?"...":""}`}),o=new Hf(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 pa(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}}))}),i=await Promise.all(r);o.stop(),oo();let c=["Sub-agent results:",""],l=0,u=0;for(let d=0;d<i.length;d++){let f=i[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(`
|
|
160
|
+
`)}catch(r){return o.stop(),oo(),`ERROR: Sub-agent execution failed: ${r.message}`}}ha.exports={runSubAgent:pa,executeSpawnAgents:Qf,clearAllLocks:oo,classifyTask:fa,pickModelForTier:ma,resolveSubAgentModel:ro,isRetryableError:ua,callWithRetry:da}});var rn=M(($$,Ra)=>{var Y=require("fs"),He=require("path"),Zf=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 At(){let t=He.join(process.cwd(),".nex","brain");return Y.existsSync(t)||Y.mkdirSync(t,{recursive:!0}),t}function $a(){return He.join(At(),".brain-index.json")}function co(){return He.join(At(),".embeddings.json")}function sn(){let t=He.join(process.cwd(),".nex","brain");if(!Y.existsSync(t))return[];try{return Y.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=He.join(t,e),n=Y.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 on(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(`
|
|
161
|
+
`);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let c=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[c]=l.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[c]=l}s=n[2]}return{frontmatter:e,body:s}}function ya(t){let e=He.join(At(),`${t}.md`);if(!Y.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=Y.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=on(s);return{name:t,content:s,body:o,frontmatter:n}}function em(t,e){let s=He.join(At(),`${t}.md`);Y.writeFileSync(s,e,"utf-8"),sm(t,e),tm()}function tm(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=co();Y.existsSync(t)&&setImmediate(async()=>{try{await Sa()}catch{}})}function nm(t){let e=He.join(At(),`${t}.md`);return Y.existsSync(e)?(Y.unlinkSync(e),om(t),!0):!1}function Vn(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Zf.has(e))}function lo(t){let e={},{frontmatter:s,body:n}=on(t),o=Array.isArray(s.tags)?s.tags:[];for(let i of o){let c=i.toLowerCase().replace(/[^a-z0-9-]/g,"");c.length>1&&(e[c]=(e[c]||0)+5)}let r=(n||t).split(`
|
|
162
|
+
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of Vn(c))e[l]=(e[l]||0)+3}for(let i of Vn(n||t))e[i]=(e[i]||0)+1;return e}function uo(){let t=$a();if(!Y.existsSync(t))return{documents:{}};try{return JSON.parse(Y.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function fo(t){Y.writeFileSync($a(),JSON.stringify(t,null,2),"utf-8")}function sm(t,e){let s=uo(),{frontmatter:n}=on(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:lo(e),tags:o,modified:new Date().toISOString()},fo(s)}function om(t){let e=uo();delete e.documents[t],fo(e)}function ao(){let t=sn(),e={documents:{}};for(let s of t){let n=Y.readFileSync(s.path,"utf-8"),{frontmatter:o}=on(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:lo(n),tags:r,modified:s.modified.toISOString()}}return fo(e),e}function wa(){let t=uo(),e=sn();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return ao()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return ao();return t}function ba(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=Vn(t);if(o.length===0)return[];let r=wa(),i=[];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&&i.push({name:c,score:u})}return i.sort((c,l)=>l.score-c.score),i.slice(0,s)}var xa=process.env.NEX_EMBED_MODEL||"nomic-embed-text",io=400,rm=50;async function _a(){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(xa.split(":")[0]))}catch{return!1}}async function mo(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,i=JSON.stringify({model:xa,prompt:t});return new Promise((c,l)=>{let u=r.request(o,{method:"POST",headers:{"Content-Type":"application/json","Content-Length":Buffer.byteLength(i)},timeout:3e4},d=>{let f="";d.on("data",m=>f+=m),d.on("end",()=>{try{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(i),u.end()})}function ka(t,e){if(!t||!e||t.length!==e.length)return 0;let s=0,n=0,o=0;for(let i=0;i<t.length;i++)s+=t[i]*e[i],n+=t[i]*t[i],o+=e[i]*e[i];let r=Math.sqrt(n)*Math.sqrt(o);return r===0?0:s/r}function va(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+io).join(" ");if(s.push({text:o,offset:n}),n+io>=e.length)break;n+=io-rm}return s}async function Sa(){let t=sn(),e={documents:{}},s=co();if(Y.existsSync(s))try{e=JSON.parse(Y.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=Y.readFileSync(n.path,"utf-8"),i=va(r),c=[];for(let l of i){let u=await mo(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 Y.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function Ea(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=co();if(!Y.existsSync(o))return[];let r;try{r=JSON.parse(Y.readFileSync(o,"utf-8"))}catch{return[]}let i=await mo(t),c=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,f="";for(let m of u.chunks||[]){let h=ka(i,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 Ta(t,e,s={}){let{k:n=60,topK:o=3}=s,r={};return t.forEach((i,c)=>{r[i.name]=(r[i.name]||0)+1/(n+c+1)}),e.forEach((i,c)=>{r[i.name]=(r[i.name]||0)+1/(n+c+1)}),Object.entries(r).map(([i,c])=>({name:i,score:c})).sort((i,c)=>c.score-i.score).slice(0,o)}async function Ca(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=ba(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await _a()){let c=await Ea(t,{topK:s});r=Ta(o,c,{topK:s})}}catch{}return r.map(i=>{let c=ya(i.name),l=(c.body||c.content||"").slice(0,300).replace(/\n+/g," ")+"...";return{name:i.name,score:i.score,content:c.content,excerpt:l}})}async function im(t){if(!t||!t.trim())return"";let e=He.join(process.cwd(),".nex","brain");if(!Y.existsSync(e)||sn().length===0)return"";let n;try{n=await Ca(t,{topK:3})}catch{return""}if(!n||n.length===0)return"";let o;try{o=Re().estimateTokens}catch{o=l=>Math.ceil(l.length/4)}let r=25e3,i=[],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
163
|
...(truncated)`}let f=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(i.push(`--- ${l.name} (relevance: ${f}) ---
|
|
160
164
|
${u}`),c+=o(u),c>=r)break}return i.length===0?"":`KNOWLEDGE BASE (auto-selected):
|
|
161
165
|
|
|
162
166
|
${i.join(`
|
|
163
167
|
|
|
164
|
-
`)}`}Ra.exports={getBrainDir:
|
|
168
|
+
`)}`}Ra.exports={getBrainDir:At,listDocuments:sn,readDocument:ya,writeDocument:em,removeDocument:nm,buildIndex:ao,getIndex:wa,query:Ca,getBrainContext:im,isEmbeddingAvailable:_a,generateEmbedding:mo,buildEmbeddingIndex:Sa,semanticQuery:Ea,cosineSimilarity:ka,_keywordQuery:ba,_extractKeywords:lo,_chunkText:va,parseFrontmatter:on,tokenize:Vn,_fuseResults:Ta}});var We=M((x$,Fa)=>{var X=require("fs").promises,Aa=require("fs"),xe=require("path"),Z=require("util").promisify(require("child_process").exec),Oa=require("util").promisify(require("child_process").execFile),{spawnSync:am}=require("child_process"),po=require("axios"),{isForbidden:cm,isDangerous:lm,isCritical:Na,confirm:Le}=Me(),{showClaudeDiff:Qn,showClaudeNewFile:um,showEditDiff:y$,confirmFileChange:an}=$i(),{C:P,Spinner:qa,getToolSpinnerText:dm}=oe(),{isGitRepo:ho,getCurrentBranch:Ma,getStatus:fm,getDiff:mm}=ct(),{recordChange:Zn}=Et(),{fuzzyFindText:Pa,findMostSimilar:$o}=Ui(),{runDiagnostics:cn}=Bi(),{findFileInIndex:pm,getFileIndex:w$}=Ys(),{resolveProfile:Ie,sshExec:Ve,scpUpload:hm,scpDownload:gm}=Rt(),{resolveDeployConfig:$m,loadDeployConfigs:b$}=eo(),ym=/^(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/,wm=/^ssh\s/,bm=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function es(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=be(e);if(s&&await X.access(s).then(()=>!0).catch(()=>!1))return{fixedPath:s,message:`(auto-fixed path: ${t} \u2192 ${e})`};let n=[".js",".ts",".jsx",".tsx",".mjs",".cjs",".json"],o=xe.extname(t);if(!o)for(let i of n){let c=be(t+i);if(c&&await X.access(c).then(()=>!0).catch(()=>!1))return{fixedPath:c,message:`(auto-fixed: added ${i} extension)`}}if(o){let i=t.replace(/\.[^.]+$/,"");for(let c of n){if(c===o)continue;let l=be(i+c);if(l&&await X.access(l).then(()=>!0).catch(()=>!1))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${c})`}}}let r=xe.basename(t);if(r&&r.length>2)try{let i=pm(r).map(c=>be(c));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${xe.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
165
169
|
${i.map(l=>xe.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
166
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
170
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function xm(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 ja(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
171
|
|
|
168
172
|
`+s.join(`
|
|
169
|
-
`)}function Da(t,e,s){let n=go(t,e);if(!n)return null;let o=Math.max(3,Math.ceil(e.length*.05));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var La=!1,cn=null;function xm(){cn&&(cn(),cn=null)}async function ho(){if(!La){La=!0;try{let{stdout:t}=await Z("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Z('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Z("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Z("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var _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 be(t){let e=xe.isAbsolute(t)?xe.resolve(t):xe.resolve(process.cwd(),t);for(let s of _m)if(s.test(e))return null;return e}var km=[{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 an(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function Ia(t,e,s={}){switch(t){case"bash":{let n=e.command,o=am(n);if(o){let u=bm(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=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await X.access(n).then(()=>!0).catch(()=>!1)){let m=await
|
|
173
|
+
`)}function Da(t,e,s){let n=$o(t,e);if(!n)return null;let o=Math.max(3,Math.ceil(e.length*.05));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var La=!1,un=null;function _m(){un&&(un(),un=null)}async function go(){if(!La){La=!0;try{let{stdout:t}=await Z("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Z('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Z("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Z("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var km=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function be(t){let e=xe.isAbsolute(t)?xe.resolve(t):xe.resolve(process.cwd(),t);for(let s of km)if(s.test(e))return null;return e}var vm=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Use this to find where functions/variables/classes are defined or used. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when requirements are ambiguous, you need to choose between approaches, or a decision has significant impact. Do not ask unnecessary questions \u2014 proceed if the intent is clear.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"deploy",description:'Deploy files to a remote server via rsync + optional remote script. Can use a named config from .nex/deploy.json (e.g. deploy("prod")) or explicit params. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},local_path:{type:"string",description:'Local directory or file to sync (e.g. "dist/", "./build"). Required if no config.'},remote_path:{type:"string",description:'Remote destination path (e.g. "/var/www/app"). Required if no config.'},deploy_script:{type:"string",description:"Shell command to run on the remote after sync. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from sync. Optional."},dry_run:{type:"boolean",description:"Show what would be synced without actually syncing. Default: false."}},required:[]}}}];function ln(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function Ia(t,e,s={}){switch(t){case"bash":{let n=e.command,o=cm(n);if(o){let u=xm(n);return`BLOCKED: Command matches forbidden pattern: ${o}${u?`
|
|
174
|
+
HINT: ${u}`:""}`}if(s.autoConfirm?Na(n):lm(n)){let u=Na(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
|
|
175
|
+
${P.yellow}${u}: ${n}${P.reset}`),!await Le(" Execute?"))return"CANCELLED: User declined to execute this command."}let i=process.cwd();try{Aa.accessSync(i)}catch{i=require("os").homedir(),s.silent||console.log(`${P.yellow} \u26A0 Working directory no longer exists \u2014 running in ${i}${P.reset}`)}let c=wm.test(n.trim())&&!bm.test(n.trim());if(ym.test(n.trim())||c){s.silent||console.log(`${P.dim} \u25B6 interactive: ${n}${P.reset}`);let u=am("sh",["-c",n],{stdio:"inherit",cwd:i});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 qa(`Running: ${n.substring(0,60)}${n.length>60?"...":""}`);l&&l.start();try{let{stdout:u,stderr:d}=await Z(n,{cwd:i,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=ja(d,n);return`EXIT ${u.code||1}
|
|
176
|
+
${f}`}}case"read_file":{let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await X.access(n).then(()=>!0).catch(()=>!1)){let m=await es(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${P.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${xe.relative(process.cwd(),n)}${P.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
173
177
|
`+m.message:""}`}let r=Buffer.alloc(8192),i=await Aa.promises.open(n,"r"),{bytesRead:c}=await i.read(r,0,8192,0);await i.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 X.readFile(n,"utf-8");if(!l&&(await X.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let u=l.split(`
|
|
174
178
|
`),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 X.readFile(n,"utf-8"),i=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let d=Pa(r,e.old_text);if(d)i=d,c=!0,console.log(`${P.dim} \u2713 fuzzy whitespace match applied${P.reset}`);else{let f=Da(r,e.old_text,e.new_text);if(f){if(!s.autoConfirm){let p=await
|
|
179
|
+
`)}case"write_file":{await go();let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await X.access(n).then(()=>!0).catch(()=>!1),r=null;if(s.autoConfirm)o&&(r=await X.readFile(n,"utf-8"));else if(o){r=await X.readFile(n,"utf-8");let l=await cn(n,e.content);if(Qn(n,r,e.content,{annotations:l}),!await an("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let l=await cn(n,e.content);if(um(n,e.content,{annotations:l}),!await an("Create"))return"CANCELLED: User declined to create file."}let i=xe.dirname(n);return await X.access(i).then(()=>!0).catch(()=>!1)||await X.mkdir(i,{recursive:!0}),await X.writeFile(n,e.content,"utf-8"),Zn("write_file",n,r,e.content),`Written: ${n} (${e.content.length} chars)`}case"edit_file":{await go();let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await X.access(n).then(()=>!0).catch(()=>!1)){let d=await es(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${P.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${xe.relative(process.cwd(),n)}${P.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
180
|
+
`+d.message:""}`}let r=await X.readFile(n,"utf-8"),i=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let d=Pa(r,e.old_text);if(d)i=d,c=!0,console.log(`${P.dim} \u2713 fuzzy whitespace match applied${P.reset}`);else{let f=Da(r,e.old_text,e.new_text);if(f){if(!s.autoConfirm){let p=await cn(n,f.content);if(Qn(n,r,f.content,{annotations:p}),!await an(`Apply (auto-fix, line ${f.line}, distance ${f.distance})`))return"CANCELLED: User declined to apply edit."}await X.writeFile(n,f.content,"utf-8"),Zn("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=$o(r,e.old_text);return m?`ERROR: old_text not found in ${n}
|
|
177
181
|
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(i).join(e.new_text),f=await
|
|
182
|
+
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=r.split(i).join(e.new_text),f=await cn(n,d);if(Qn(n,r,d,{annotations:f}),!await an(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(i).join(e.new_text);return await X.writeFile(n,u,"utf-8"),Zn("edit_file",n,r,u),c?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await X.access(n).then(()=>!0).catch(()=>!1)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=be(u),f=await X.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,i=null;if(e.pattern)try{let u=e.pattern.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");i=new RegExp(`^${u}$`)}catch{return`ERROR: Invalid pattern: ${e.pattern}`}let c=[],l=async(u,d,f)=>{if(d>r)return;let m;try{m=await X.readdir(u,{withFileTypes:!0})}catch{return}m=m.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of m){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let p=h.isDirectory()?"/":"";c.push(`${f}${h.name}${p}`),h.isDirectory()&&await l(xe.join(u,h.name),d+1,f+" ")}};return await l(n,1,""),c.join(`
|
|
179
183
|
`)||"(empty)"}case"search_files":{let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,n);try{let{stdout:r}=await Oa("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
180
184
|
`).slice(0,50).join(`
|
|
181
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?be(e.path):o,i=e.pattern,c=k=>{let v=k.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${v}$`)},l=c(i),u=i.split("/").pop(),d=c(u),{getFileIndex:f,getIndexedCwd:m,refreshIndex:h,isIndexValid:p}=
|
|
185
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?be(e.path):o,i=e.pattern,c=k=>{let v=k.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*\*\//g,"(.*/)?").replace(/\*\*/g,".*").replace(/\*/g,"[^/]*").replace(/\?/g,".");return new RegExp(`^${v}$`)},l=c(i),u=i.split("/").pop(),d=c(u),{getFileIndex:f,getIndexedCwd:m,refreshIndex:h,isIndexValid:p}=Ys(),g=f(),y=m();p(r)||(await h(r),g=f());let $=g.filter(k=>l.test(k)||d.test(xe.basename(k))).map(k=>xe.join(r,k));if($.length===0)return"(no matches)";let x=$.length>200,O=$.slice(0,200).join(`
|
|
182
186
|
`);return x?`${O}
|
|
183
187
|
|
|
184
188
|
\u26A0 Results truncated at 200. Use a more specific pattern.`:O}case"grep":{let n=e.path?be(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 Oa("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
185
189
|
`).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 i=await X.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(i.includes(h))c.push({old_text:h,new_text:p});else{let g=Pa(i,h);if(g)c.push({old_text:g,new_text:p}),l=!0;else{let y
|
|
190
|
+
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await go();let n=be(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await X.access(n).then(()=>!0).catch(()=>!1)){let m=await es(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${P.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${xe.relative(process.cwd(),n)}${P.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
191
|
+
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await X.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(i.includes(h))c.push({old_text:h,new_text:p});else{let g=Pa(i,h);if(g)c.push({old_text:g,new_text:p}),l=!0;else{let y=$o(i,h);if(y){let $=Math.max(3,Math.ceil(h.length*.05));if(y.distance<=$)c.push({old_text:y.text,new_text:p}),u=!0;else return`ERROR: Patch ${m+1} old_text not found in ${n}
|
|
188
192
|
Most similar text (line ${y.line}, distance ${y.distance}):
|
|
189
|
-
${y.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${n}`}}}let d=i;for(let{old_text:m,new_text:h}of c)d=d.split(m).join(h);if(!s.autoConfirm){let m=await
|
|
193
|
+
${y.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${n}`}}}let d=i;for(let{old_text:m,new_text:h}of c)d=d.split(m).join(h);if(!s.autoConfirm){let m=await cn(n,d);if(Qn(n,i,d,{annotations:m}),!await an(l?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await X.writeFile(n,d,"utf-8"),Zn("patch_file",n,i,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 po.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 po.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||"",i=o.data?.citations||[],c=`[Perplexity grounded search]
|
|
190
194
|
|
|
191
195
|
${r}`;return i.length>0&&(c+=`
|
|
192
196
|
|
|
193
197
|
Sources:
|
|
194
198
|
`+i.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
|
|
199
|
+
`)),c}catch(o){console.error(`${P.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${P.reset}`)}try{let r=(await po.get("https://html.duckduckgo.com/html/",{params:{q:e.query},timeout:1e4,responseType:"text",headers:{"User-Agent":"nex-code/0.2.0"}})).data,i=[],c=/<a[^>]*class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>/gi,l;for(;(l=c.exec(r))!==null&&i.length<n;){let u=l[1].replace(/.*uddg=/,"").split("&")[0],d=l[2].replace(/<[^>]+>/g,"").trim();try{i.push({title:d,url:decodeURIComponent(u)})}catch{i.push({title:d,url:u})}}return i.length===0?"(no results)":i.map((u,d)=>`${d+1}. ${u.title}
|
|
196
200
|
${u.url}`).join(`
|
|
197
201
|
|
|
198
|
-
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=
|
|
202
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=Xt();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
|
|
199
203
|
|
|
200
204
|
Links:
|
|
201
205
|
`+o.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
|
|
202
206
|
`):"";return`Title: ${o.title}
|
|
203
207
|
URL: ${o.url}
|
|
204
208
|
|
|
205
|
-
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=
|
|
209
|
+
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=Xt();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
|
|
206
210
|
Title: ${o.title}
|
|
207
211
|
URL: ${o.url}
|
|
208
212
|
|
|
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}=
|
|
210
|
-
${P.cyan}${P.bold} ? ${n}${P.reset}`),r.question(`${P.cyan} > ${P.reset}`,i=>{
|
|
213
|
+
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=Xt();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=Xt();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});un=()=>{r.close(),o("CANCELLED")},console.log(`
|
|
214
|
+
${P.cyan}${P.bold} ? ${n}${P.reset}`),r.question(`${P.cyan} > ${P.reset}`,i=>{un=null,r.close(),o(i.trim()||"(no response)")})})}case"git_status":{if(!await ho())return"ERROR: Not a git repository";let n=await Ma()||"(detached)",o=await fm();if(o.length===0)return`Branch: ${n}
|
|
211
215
|
Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let i of o){let c=i.status==="M"?"modified":i.status==="A"?"added":i.status==="D"?"deleted":i.status==="??"?"untracked":i.status;r.push(` ${c}: ${i.file}`)}return r.join(`
|
|
212
|
-
`)}case"git_diff":{if(!await
|
|
216
|
+
`)}case"git_diff":{if(!await ho())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 mm(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await ho())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:i,hasActiveTasks:c}=Kn(),{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
217
|
`+i()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
214
218
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
215
219
|
`)}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(`
|
|
@@ -219,47 +223,47 @@ Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.lengt
|
|
|
219
223
|
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await Z(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
|
|
220
224
|
...(truncated)`:"")}let{stdout:n}=await Z(`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 i of o.jobs||[]){let c=i.conclusion==="success"?"\u2713":i.conclusion==="failure"?"\u2717":"\u25CB";r.push(` ${c} ${i.name} (${i.conclusion||i.status})`);for(let l of i.steps||[]){if(l.conclusion==="failure"||l.conclusion==="skipped")continue;let u=l.conclusion==="success"?" \u2713":l.conclusion==="failure"?" \u2717":" \u25CB";r.push(` ${u} ${l.name}`)}}return r.join(`
|
|
221
225
|
`)}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}=Me(),o=e.branch||await
|
|
226
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Me(),o=e.branch||await Ma()||"main",r=e.inputs?Object.entries(e.inputs).map(([l,u])=>`-f ${l}=${u}`).join(" "):"",i=`gh workflow run ${e.workflow} --ref ${o} ${r}`.trim();if(console.log(`
|
|
223
227
|
${P.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${P.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await Z(i,{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=
|
|
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 i=
|
|
228
|
+
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=ln(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:c}=await Z(r,{timeout:3e4,maxBuffer:2097152});return(i||c||"(no pods)").trim()}catch(i){let c=(i.stderr||i.message||"").toString().split(`
|
|
229
|
+
`)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=ln(r,e);try{let{stdout:c,stderr:l}=await Z(i,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
|
|
226
230
|
...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
227
231
|
`)[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
|
|
232
|
+
${P.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${P.reset}`),console.log(`${P.dim} Command: ${e.command}${P.reset}`),!await Le(" 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 i=ln(r,e);try{let{stdout:c,stderr:l}=await Z(i,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
229
233
|
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let n=!!e.dry_run;if(!n){let i=e.file;if(console.log(`
|
|
230
|
-
${P.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${P.reset}`),!await
|
|
234
|
+
${P.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${P.reset}`),!await Le(" 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=ln(o,e);try{let{stdout:i,stderr:c}=await Z(r,{timeout:12e4,maxBuffer:2097152});return(i||c||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
|
|
231
235
|
`)[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
|
|
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}=
|
|
236
|
+
${P.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${n})${P.reset}`),!await Le(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=ln(r,e);try{let{stdout:c,stderr:l}=await Z(i,{timeout:12e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
237
|
+
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=rn(),{name:r,content:i,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
238
|
|
|
235
|
-
`+i:i;return n(r,u),`Appended to brain document: ${r}.md`}return n(r,i),`${c==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=
|
|
236
|
-
${P.yellow} \u26A0 Remote command on ${h}: ${o}${P.reset}`),!await
|
|
239
|
+
`+i:i;return n(r,u),`Appended to brain document: ${r}.md`}return n(r,i),`${c==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=Ie(e.server)}catch(h){return`ERROR: ${h.message}`}let o=e.command,r=!!e.sudo,i=(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(`
|
|
240
|
+
${P.yellow} \u26A0 Remote command on ${h}: ${o}${P.reset}`),!await Le(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await Ve(n,o,{timeout:i,sudo:r}),m=[l,u].filter(Boolean).join(`
|
|
237
241
|
`).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
|
|
241
|
-
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await
|
|
242
|
+
${f||m||"(no output)"}`:m||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=Ie(e.server)}catch(i){return`ERROR: ${i.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
243
|
+
${P.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${P.reset}`),!await Le(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await hm(n,e.local_path,e.remote_path)}catch(i){return`ERROR: ${i.message}`}}case"ssh_download":{if(!e.server||!e.remote_path||!e.local_path)return"ERROR: server, remote_path, and local_path are required";let n;try{n=Ie(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await gm(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",i=null;if(!o)try{i=Ie(e.server)}catch(l){return`ERROR: ${l.message}`}if(!r){let l=o?"local machine":i.user?`${i.user}@${i.host}`:i.host;if(console.log(`
|
|
244
|
+
${P.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${P.reset}`),!await Le(" 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 Z(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}
|
|
245
|
+
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await Ve(i,c,{timeout:15e3,sudo:!0}),m=[l,u].filter(Boolean).join(`
|
|
242
246
|
`).trim();return d!==0?/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${e.service}" not found on ${i.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${d}
|
|
243
247
|
${f||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${o} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:p,stderr:g}=await Z(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=
|
|
248
|
+
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=Ie(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await Ve(l,c,{timeout:2e4}),h=[u,d].filter(Boolean).join(`
|
|
245
249
|
`).trim();return f!==0?`EXIT ${f}
|
|
246
250
|
${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 Z(r,{timeout:1e4});return(m||h||"(no containers)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
247
|
-
${(m.stderr||m.message||"").toString().trim()}`}let i;try{i=
|
|
251
|
+
${(m.stderr||m.message||"").toString().trim()}`}let i;try{i=Ie(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await Ve(i,r,{timeout:15e3}),f=[c,l].filter(Boolean).join(`
|
|
248
252
|
`).trim();return u!==0?`EXIT ${u}
|
|
249
253
|
${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:h,stderr:p}=await Z(i,{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=
|
|
254
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Ie(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Ve(c,i,{timeout:2e4}),m=[l,u].filter(Boolean).join(`
|
|
251
255
|
`).trim();return d!==0?`EXIT ${d}
|
|
252
256
|
${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=
|
|
257
|
+
${P.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${P.reset}`),!await Le(" Execute?"))return"CANCELLED: User declined."}let i=`docker exec ${e.container} sh -c ${JSON.stringify(e.command)}`;if(n)try{let{stdout:h,stderr:p}=await Z(i,{timeout:3e4});return(h||p||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
258
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Ie(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Ve(c,i,{timeout:35e3}),m=[l,u].filter(Boolean).join(`
|
|
255
259
|
`).trim();return d!==0?`EXIT ${d}
|
|
256
260
|
${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=
|
|
261
|
+
${P.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${P.reset}`),!await Le(" Execute?"))return"CANCELLED: User declined."}let i=e.action==="remove"?"rm":e.action,c=e.action==="inspect"?`docker inspect ${e.container}`:`docker ${i} ${e.container}`;if(o)try{let{stdout:p,stderr:g}=await Z(c,{timeout:3e4});return(p||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(p){return`EXIT ${p.code||1}
|
|
262
|
+
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=Ie(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await Ve(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
|
|
259
263
|
`).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
|
|
262
|
-
${m||"(nothing to sync)"}`;let h="";if(e.deploy_script){let{stdout:p,stderr:g,exitCode:y,error:$}=await
|
|
264
|
+
${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...$m(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=Ie(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}"`:"",i=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(`
|
|
265
|
+
${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 Le(" Proceed with deployment?")))return"CANCELLED: User declined.";let m="";try{let{stdout:p,stderr:g}=await Z(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:
|
|
266
|
+
${m||"(nothing to sync)"}`;let h="";if(e.deploy_script){let{stdout:p,stderr:g,exitCode:y,error:$}=await Ve(n,e.deploy_script,{timeout:6e4}),x=[p,g].filter(Boolean).join(`
|
|
263
267
|
`).trim();if(y!==0)return`rsync OK
|
|
264
268
|
|
|
265
269
|
ERROR (deploy_script, exit ${y}):
|
|
@@ -267,29 +271,29 @@ ${$||x}`;h=`
|
|
|
267
271
|
|
|
268
272
|
Remote script output:
|
|
269
273
|
${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
|
|
274
|
+
${m}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function Sm(t,e,s={}){let n=s.silent?null:dm(t,e);if(!n)return Ia(t,e,s);let o=new qa(n);o.start();try{let r=await Ia(t,e,s);return o.stop(),r}catch(r){throw o.stop(),r}}Fa.exports={TOOL_DEFINITIONS:vm,executeTool:Sm,resolvePath:be,autoFixPath:es,autoFixEdit:Da,enrichBashError:ja,cancelPendingAskUser:_m}});var Wa=M((_$,Ua)=>{var{loadServerProfiles:wo}=Rt(),yo={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 Em(){let t=wo();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 i=r.user?`${r.user}@${r.host}`:r.host,c=r.port&&Number(r.port)!==22?`:${r.port}`:"",l=r.os?` \u2014 OS: ${r.os}`:"",u=r.sudo?", sudo available":"";s.push(`- **${o}**: ${i}${c}${l}${u}`)}let n=new Set;for(let o of Object.values(t))o.os&&yo[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 i of yo[o])s.push(`- ${i}`)}}return s.join(`
|
|
275
|
+
`)}function Tm(t){let e=wo();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function Cm(){return Object.keys(wo())}Ua.exports={getServerContext:Em,hasServerOS:Tm,getProfileNames:Cm,OS_HINTS:yo}});var xo=M((k$,Ha)=>{var Oe=require("fs").promises,Te=require("path"),ts=require("util").promisify(require("child_process").exec),{C:qe}=oe(),{getMergeConflicts:Ba}=ct(),{getServerContext:Rm}=Wa(),bo=new Map,Ot=new Map,ns=null,Am=3e4;async function Qe(t){try{return await t()}catch{return null}}async function Om(){if(!ns||Date.now()>ns)return!1;let t=[Te.join(process.cwd(),"package.json"),Te.join(process.cwd(),"README.md"),Te.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await Oe.stat(e),n=Ot.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(Ot.has(e))return!1}try{let e=Te.join(process.cwd(),".git","HEAD"),s=await Oe.stat(e),n=Ot.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function Nm(){let t=[Te.join(process.cwd(),"package.json"),Te.join(process.cwd(),"README.md"),Te.join(process.cwd(),".gitignore"),Te.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await Oe.stat(e);Ot.set(e,s.mtimeMs)}catch{Ot.delete(e)}}async function Mm(t){let e="fileContext",s=bo.get(e),n=!1;if(s&&await Om()&&(n=!0),!n){let u=[],d=Te.join(t,"package.json");if(await Qe(()=>Oe.access(d).then(()=>!0).catch(()=>!1)))try{let y=await Oe.readFile(d,"utf-8"),$=JSON.parse(y),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=Te.join(t,"README.md");if(await Qe(()=>Oe.access(m).then(()=>!0).catch(()=>!1))){let $=(await Oe.readFile(m,"utf-8")).split(`
|
|
272
276
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
273
277
|
${$.join(`
|
|
274
|
-
`)}`)}let p=
|
|
278
|
+
`)}`)}let p=Te.join(t,".gitignore");if(await Qe(()=>Oe.access(p).then(()=>!0).catch(()=>!1))){let y=await Oe.readFile(p,"utf-8");u.push(`GITIGNORE:
|
|
275
279
|
${y.trim()}`)}s=u.join(`
|
|
276
280
|
|
|
277
|
-
`),
|
|
281
|
+
`),bo.set(e,s),ns=Date.now()+Am,await Nm()}let o=[s],[r,i,c,l]=await Promise.all([Qe(async()=>{let{stdout:u}=await ts("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Qe(async()=>{let{stdout:u}=await ts("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Qe(async()=>{let{stdout:u}=await ts("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),Ba()]);if(r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
|
|
278
282
|
${i}`),c&&o.push(`RECENT COMMITS:
|
|
279
283
|
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
280
284
|
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
281
|
-
${u}`)}try{let u=
|
|
285
|
+
${u}`)}try{let u=Rm();u&&o.push(u)}catch{}return o.join(`
|
|
282
286
|
|
|
283
|
-
`)}async function
|
|
287
|
+
`)}async function Pm(t){let e=Te.join(t,"package.json"),s="";if(await Qe(()=>Oe.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Oe.readFile(e,"utf-8"),c=JSON.parse(i);s=`${c.name||"?"} v${c.version||"?"}`}catch{}let[o,r]=await Promise.all([Qe(async()=>{let{stdout:i}=await ts("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Ba()]);if(s&&console.log(`${qe.dim} project: ${s}${qe.reset}`),o&&console.log(`${qe.dim} branch: ${o}${qe.reset}`),r&&r.length>0){console.log(`${qe.red} \u26A0 ${r.length} unresolved merge conflict(s):${qe.reset}`);for(let i of r)console.log(`${qe.red} ${i.file}${qe.reset}`);console.log(`${qe.yellow} \u2192 Resolve conflicts before starting tasks${qe.reset}`)}console.log()}Ha.exports={gatherProjectContext:Mm,printContext:Pm,_clearContextCache:()=>{bo.clear(),Ot.clear(),ns=null}}});var dt=M((v$,Ja)=>{var ze=require("fs"),_o=require("path");function ss(){return _o.join(process.cwd(),".nex","sessions")}function Ga(){let t=ss();ze.existsSync(t)||ze.mkdirSync(t,{recursive:!0})}function ko(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return _o.join(ss(),`${e}.json`)}function vo(t,e,s={}){Ga();let n=ko(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 ze.writeFileSync(n,JSON.stringify(o,null,2),"utf-8"),{path:n,name:t}}function za(t){let e=ko(t);if(!ze.existsSync(e))return null;try{return JSON.parse(ze.readFileSync(e,"utf-8"))}catch{return null}}function Ka(){Ga();let t=ss(),e=ze.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(ze.readFileSync(_o.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 Lm(t){let e=ko(t);return ze.existsSync(e)?(ze.unlinkSync(e),!0):!1}function Im(){let t=Ka();return t.length===0?null:za(t[0].name)}var ut=null,Ge=null,dn=null;function qm(t,e={}){t.length!==0&&(ut&&clearTimeout(ut),Ge=t,dn=e||{},ut=setTimeout(()=>{Ge&&Ge.length>0&&vo("_autosave",Ge,dn),ut=null,Ge=null,dn=null},5e3))}function jm(){ut&&(clearTimeout(ut),ut=null),Ge&&Ge.length>0&&(vo("_autosave",Ge,dn),Ge=null,dn=null)}Ja.exports={saveSession:vo,loadSession:za,listSessions:Ka,deleteSession:Lm,getLastSession:Im,autoSave:qm,flushAutoSave:jm,_getSessionsDir:ss}});var Ze=M((S$,ec)=>{var Ke=require("fs"),os=require("path"),Dm=require("os");function So(){return os.join(process.cwd(),".nex","memory")}function Eo(){return os.join(So(),"memory.json")}function Fm(){return os.join(process.cwd(),"NEX.md")}function Ya(){return os.join(Dm.homedir(),".nex","NEX.md")}function Um(){let t=So();Ke.existsSync(t)||Ke.mkdirSync(t,{recursive:!0})}function rs(){let t=Eo();if(!Ke.existsSync(t))return{};try{return JSON.parse(Ke.readFileSync(t,"utf-8"))}catch{return{}}}function Xa(t){Um(),Ke.writeFileSync(Eo(),JSON.stringify(t,null,2),"utf-8")}function Wm(t,e){let s=rs();s[t]={value:e,updatedAt:new Date().toISOString()},Xa(s)}function Bm(t){let e=rs();return e[t]?e[t].value:null}function Hm(t){let e=rs();return t in e?(delete e[t],Xa(e),!0):!1}function Va(){let t=rs();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Qa(){let t=Ya();if(!Ke.existsSync(t))return"";try{return Ke.readFileSync(t,"utf-8").trim()}catch{return""}}function Za(){let t=Fm();if(!Ke.existsSync(t))return"";try{return Ke.readFileSync(t,"utf-8").trim()}catch{return""}}function Gm(){let t=[],e=Qa();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
284
288
|
${e}`);let s=Za();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
285
289
|
${s}`);let n=Va();if(n.length>0){let o=n.map(r=>` ${r.key}: ${r.value}`).join(`
|
|
286
290
|
`);t.push(`PROJECT MEMORY:
|
|
287
291
|
${o}`)}return t.join(`
|
|
288
292
|
|
|
289
|
-
`)}ec.exports={remember:
|
|
293
|
+
`)}ec.exports={remember:Wm,recall:Bm,forget:Hm,listMemories:Va,loadGlobalInstructions:Qa,loadProjectInstructions:Za,getMemoryContext:Gm,_getMemoryDir:So,_getMemoryFile:Eo,_getGlobalNexMdPath:Ya}});var fn=M((T$,sc)=>{var ft=require("fs"),To=require("path"),{C:E$}=oe(),is={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"},Nt={...is};function tc(){let t=To.join(process.cwd(),".nex","config.json");if(ft.existsSync(t))try{let e=JSON.parse(ft.readFileSync(t,"utf-8"));e.permissions&&(Nt={...is,...e.permissions})}catch{}}function zm(){let t=To.join(process.cwd(),".nex"),e=To.join(t,"config.json"),s={};if(ft.existsSync(e))try{s=JSON.parse(ft.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Nt,ft.existsSync(t)||ft.mkdirSync(t,{recursive:!0}),ft.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function nc(t){return Nt[t]||"ask"}function Km(t,e){return["allow","ask","deny"].includes(e)?(Nt[t]=e,!0):!1}function Jm(t){return nc(t)}function Ym(){return Object.entries(Nt).map(([t,e])=>({tool:t,mode:e}))}function Xm(){Nt={...is}}tc();sc.exports={getPermission:nc,setPermission:Km,checkPermission:Jm,listPermissions:Ym,loadPermissions:tc,savePermissions:zm,resetPermissions:Xm,DEFAULT_PERMISSIONS:is}});var Mt=M((R$,cc)=>{var mt=require("fs"),as=require("path"),C$=require("readline"),{C:B}=oe(),re=null,Co=!1,Ro=null,oc=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 cs(){return as.join(process.cwd(),".nex","plans")}function rc(){let t=cs();mt.existsSync(t)||mt.mkdirSync(t,{recursive:!0})}function Vm(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 Qm(){return re}function Zm(t){Co=t}function ep(){return Co}function tp(){return!re||re.status!=="draft"?!1:(re.status="approved",re.updatedAt=new Date().toISOString(),!0)}function np(){return!re||re.status!=="approved"?!1:(re.status="executing",!0)}function sp(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 op(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
294
|
${B.bold}${B.cyan}Plan: ${t.task}${B.reset}`),s.push(`${B.dim}Status: ${e[t.status]||t.status}${B.reset}
|
|
291
295
|
`);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
|
|
296
|
+
`)}function rp(t){if(t||(t=re),!t)return null;rc();let e=as.join(cs(),`${t.name}.json`);return mt.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function ip(t){let e=as.join(cs(),`${t}.json`);if(!mt.existsSync(e))return null;try{let s=JSON.parse(mt.readFileSync(e,"utf-8"));return re=s,s}catch{return null}}function ap(){rc();let t=cs(),e=mt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(mt.readFileSync(as.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 cp(t){Ro=t}function lp(){return Ro}function up(){re=null,Co=!1,Ro=null}function dp(){return`
|
|
293
297
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
294
298
|
|
|
295
299
|
# Allowed Tools (read-only)
|
|
@@ -324,42 +328,42 @@ Bullet list of potential issues and mitigations.
|
|
|
324
328
|
# Important
|
|
325
329
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
326
330
|
- 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 ic=["interactive","semi-auto","autonomous"],ac="interactive";function
|
|
328
|
-
`),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${w.dim}${"\u2500".repeat(40)}${w.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let i=o?` ${o} `:"";s.push(`${w.dim}${"\u2500".repeat(3)}${i}${"\u2500".repeat(Math.max(0,37-i.length))}${w.reset}`)}continue}if(n){s.push(` ${
|
|
329
|
-
`)}function
|
|
330
|
-
`)}function
|
|
331
|
+
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var ic=["interactive","semi-auto","autonomous"],ac="interactive";function fp(t){return ic.includes(t)?(ac=t,!0):!1}function mp(){return ac}cc.exports={createPlan:Vm,getActivePlan:Qm,setPlanMode:Zm,isPlanMode:ep,approvePlan:tp,startExecution:np,updateStep:sp,formatPlan:op,savePlan:rp,loadPlan:ip,listPlans:ap,clearPlan:up,getPlanModePrompt:dp,setPlanContent:cp,getPlanContent:lp,PLAN_MODE_ALLOWED_TOOLS:oc,setAutonomyLevel:fp,getAutonomyLevel:mp,AUTONOMY_LEVELS:ic}});var yc=M((A$,$c)=>{var{C:w}=oe();function pp(t){if(!t)return"";let e=t.split(`
|
|
332
|
+
`),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${w.dim}${"\u2500".repeat(40)}${w.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let i=o?` ${o} `:"";s.push(`${w.dim}${"\u2500".repeat(3)}${i}${"\u2500".repeat(Math.max(0,37-i.length))}${w.reset}`)}continue}if(n){s.push(` ${Oo(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${w.bold}${w.cyan} ${pt(r.substring(4))}${w.reset}`);continue}if(r.startsWith("## ")){s.push(`${w.bold}${w.cyan} ${pt(r.substring(3))}${w.reset}`);continue}if(r.startsWith("# ")){s.push(`${w.bold}${w.cyan}${pt(r.substring(2))}${w.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let i=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,"");s.push(`${i}${w.cyan}\u2022${w.reset} ${ht(c)}`);continue}if(/^\s*\d+\.\s/.test(r)){let i=r.match(/^(\s*)(\d+)\.\s(.*)/);if(i){s.push(`${i[1]}${w.cyan}${i[2]}.${w.reset} ${ht(i[3])}`);continue}}s.push(ht(r))}return s.join(`
|
|
333
|
+
`)}function pt(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function ht(t){return t?t.replace(/`([^`]+)`/g,`${w.cyan}$1${w.reset}`).replace(/\*\*([^*]+)\*\*/g,`${w.bold}$1${w.reset}`).replace(/\*([^*]+)\*/g,`${w.dim}$1${w.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${w.cyan}$1${w.reset} ${w.dim}($2)${w.reset}`):""}function Oo(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?lc(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?uc(t):e==="json"||e==="jsonc"?dc(t):e==="python"||e==="py"?fc(t):e==="go"||e==="golang"?mc(t):e==="rust"||e==="rs"?pc(t):e==="css"||e==="scss"||e==="less"?hc(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?gc(t):t:""}function lc(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,`${w.yellow}$1${w.reset}`),r=r.replace(e,`${w.magenta}$1${w.reset}`),r=r.replace(s,`${w.green}$&${w.reset}`),r=r.replace(n,`${w.dim}$1${w.reset}`),r}function uc(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${w.cyan}$1${w.reset}`),r=r.replace(e,`$1${w.green}$2${w.reset}`),r=r.replace(n,`${w.yellow}$&${w.reset}`),r=r.replace(o,`${w.dim}$1${w.reset}`),r}function dc(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,`${w.cyan}$1${w.reset}:`),r=r.replace(s,`: ${w.green}$1${w.reset}`),r=r.replace(n,`: ${w.yellow}$1${w.reset}`),r=r.replace(o,`: ${w.magenta}$1${w.reset}`),r}function fc(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+)/,i=t;return i=i.replace(o,`${w.yellow}$1${w.reset}`),i=i.replace(e,`${w.magenta}$1${w.reset}`),i=i.replace(r,`${w.cyan}$1${w.reset}`),i=i.replace(s,`${w.green}$&${w.reset}`),i=i.replace(n,`${w.dim}$1${w.reset}`),i}function mc(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,i=t;return i=i.replace(r,`${w.yellow}$1${w.reset}`),i=i.replace(s,`${w.cyan}$1${w.reset}`),i=i.replace(e,`${w.magenta}$1${w.reset}`),i=i.replace(n,`${w.green}$&${w.reset}`),i=i.replace(o,`${w.dim}$1${w.reset}`),i}function pc(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,i=/\b(\w+!)/g,c=t;return c=c.replace(r,`${w.yellow}$1${w.reset}`),c=c.replace(s,`${w.cyan}$1${w.reset}`),c=c.replace(e,`${w.magenta}$1${w.reset}`),c=c.replace(i,`${w.yellow}$1${w.reset}`),c=c.replace(n,`${w.green}$&${w.reset}`),c=c.replace(o,`${w.dim}$1${w.reset}`),c}function hc(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=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(i,`${w.yellow}$1${w.reset}`),c=c.replace(o,`${w.yellow}$1${w.reset}`),c=c.replace(e,`$1${w.cyan}$2${w.reset}:`),c=c.replace(n,`$1${w.magenta}$&${w.reset}`),c=c.replace(r,`${w.dim}$1${w.reset}`),c}function gc(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(o,`${w.dim}$1${w.reset}`),i=i.replace(n,`${w.green}$&${w.reset}`),i=i.replace(e,`<${w.magenta}$1${w.reset}`),i=i.replace(s,` ${w.cyan}$1${w.reset}=`),i=i.replace(r,`${w.yellow}$1${w.reset}`),i}function hp(t,e){if(!t||t.length===0)return"";let s=t.map((i,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(i.length,l)}),n=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),o=t.map((i,c)=>` ${w.bold}${i.padEnd(s[c])}${w.reset} `).join("\u2502"),r=[];r.push(`${w.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${w.reset}`),r.push(`${w.dim}\u2502${w.reset}${o}${w.dim}\u2502${w.reset}`),r.push(`${w.dim}\u251C${n}\u2524${w.reset}`);for(let i of e){let c=t.map((l,u)=>` ${(i[u]||"").padEnd(s[u])} `).join(`${w.dim}\u2502${w.reset}`);r.push(`${w.dim}\u2502${w.reset}${c}${w.dim}\u2502${w.reset}`)}return r.push(`${w.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${w.reset}`),r.join(`
|
|
334
|
+
`)}function gp(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),i=n-r,c=o>=100?w.green:o>50?w.yellow:w.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${w.dim}${"\u2591".repeat(i)}${w.reset} ${o}% (${e}/${s})`}var Ao=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
335
|
`))!==-1;){let n=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(n)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),120))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${w.dim}${"\u2500".repeat(40)}${w.reset}
|
|
332
336
|
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${w.dim}${"\u2500".repeat(40)}${w.reset}
|
|
333
337
|
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${w.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${w.reset}
|
|
334
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
335
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${w.bold}${w.cyan} ${
|
|
336
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${w.bold}${w.cyan} ${
|
|
337
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${w.bold}${w.cyan}${
|
|
338
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${w.cyan}\u2022${w.reset} ${
|
|
339
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${w.cyan}${s[2]}.${w.reset} ${
|
|
340
|
-
`);return}}this._safeWrite(`${
|
|
341
|
-
`)}};$c.exports={renderMarkdown:
|
|
338
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${Oo(e,this.codeBlockLang)}
|
|
339
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${w.bold}${w.cyan} ${pt(e.substring(4))}${w.reset}
|
|
340
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${w.bold}${w.cyan} ${pt(e.substring(3))}${w.reset}
|
|
341
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${w.bold}${w.cyan}${pt(e.substring(2))}${w.reset}
|
|
342
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${w.cyan}\u2022${w.reset} ${ht(n)}
|
|
343
|
+
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${w.cyan}${s[2]}.${w.reset} ${ht(s[3])}
|
|
344
|
+
`);return}}this._safeWrite(`${ht(e)}
|
|
345
|
+
`)}};$c.exports={renderMarkdown:pp,renderInline:ht,stripHeadingMarkers:pt,highlightCode:Oo,highlightJS:lc,highlightBash:uc,highlightJSON:dc,highlightPython:fc,highlightGo:mc,highlightRust:pc,highlightCSS:hc,highlightHTML:gc,renderTable:hp,renderProgress:gp,StreamRenderer:Ao}});var Po=M((O$,_c)=>{var{execSync:$p}=require("child_process"),No=require("path"),mn=require("fs"),Mo=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function wc(){return No.join(process.cwd(),".nex","hooks")}function yp(){return No.join(process.cwd(),".nex","config.json")}function bc(){let t=yp();if(!mn.existsSync(t))return{};try{return JSON.parse(mn.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function ls(t){if(!Mo.includes(t))return[];let e=[],s=wc(),n=No.join(s,t);mn.existsSync(n)&&e.push(n);let o=bc();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function xc(t,e={},s=3e4){try{return{success:!0,output:$p(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 wp(t,e={}){let s=ls(t);if(s.length===0)return[];let n={};for(let[r,i]of Object.entries(e))n[`NEX_${r.toUpperCase()}`]=String(i);let o=[];for(let r of s){let i=xc(r,n);if(o.push({command:r,...i}),!i.success&&t.startsWith("pre-"))break}return o}function bp(t){return ls(t).length>0}function xp(){let t=[];for(let e of Mo){let s=ls(e);s.length>0&&t.push({event:e,commands:s})}return t}function _p(){let t=wc();return mn.existsSync(t)||mn.mkdirSync(t,{recursive:!0}),t}_c.exports={HOOK_EVENTS:Mo,loadHookConfig:bc,getHooksForEvent:ls,executeHook:xc,runHooks:wp,hasHooks:bp,listHooks:xp,initHooksDir:_p}});var ce=M((P$,Lc)=>{var{C:_,Spinner:Pt,TaskProgress:kp,formatToolCall:vp,formatResult:Sp,formatToolSummary:Cc,formatSectionHeader:Ep,setActiveTaskProgress:N$}=oe(),{callStream:Tp}=ge(),{parseToolArgs:Cp}=Nn(),{executeTool:Rp}=We(),{gatherProjectContext:Ap}=xo(),{fitToContext:Op,forceCompress:Lo,getUsage:Np,estimateTokens:Mp}=Re(),{autoSave:gt}=dt(),{getMemoryContext:Pp}=Ze(),{checkPermission:Lp,setPermission:Ip,savePermissions:qp}=fn(),{confirm:Rc,setAllowAlwaysHandler:jp}=Me(),{isPlanMode:ms,getPlanModePrompt:Dp,PLAN_MODE_ALLOWED_TOOLS:Ac,setPlanContent:Fp}=Mt(),{StreamRenderer:Up}=yc(),{runHooks:kc}=Po(),{routeMCPCall:Wp,getMCPToolDefinitions:Bp}=qn(),{getSkillInstructions:Hp,getSkillToolDefinitions:Gp,routeSkillCall:zp}=Kt(),{trackUsage:Kp}=vt(),{validateToolArgs:Jp}=Gs(),{filterToolsForModel:vc,getModelTier:Yp,PROVIDER_DEFAULT_TIER:M$}=so(),{getConfiguredProviders:Xp,getActiveProviderName:pn,getActiveModelId:Bo,setActiveModel:Sc,MODEL_EQUIVALENTS:ps}=ge(),zo=require("fs"),Ko=require("path"),Ec=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function Vp(t){let e=[],s;for(Ec.lastIndex=0;(s=Ec.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):Ko.resolve(n);zo.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Qp(t){let e=zo.readFileSync(t),s=Ko.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 Oc(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 Io=null,qo=null,jo=null;function Lt(){if(Io===null){let{TOOL_DEFINITIONS:t}=We();Io=t}return qo===null&&(qo=Gp()),jo===null&&(jo=Bp()),[...Io,...qo,...jo]}var Ho=50;function Zp(t){Number.isFinite(t)&&t>0&&(Ho=t)}var us=()=>null;function eh(t){us=t}var hn=null,Go=null,It=null,ds=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(Mp(e)>th)try{let{compressToolResult:n}=Re();return n(e,nh)}catch{return e}return e}function Nc(t){try{let{getActiveModel:e}=ge(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(ds.has(n))return ds.get(n);let o=vc(t);return ds.set(n,o),o}catch{return vc(t)}}function ih(){ds.clear()}async function Mc(){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(i=>`${r}:${i.mtimeMs}`)))).filter(r=>r.status==="fulfilled").map(r=>r.value);try{let{getMemoryContextHash:r}=Ze(),i=r();i&&o.push(`memory:${i}`)}catch{}try{let r=e.join(process.cwd(),".nex","brain");if(zo.existsSync(r)){let i=await t.stat(r);o.push(`brain:${i.mtimeMs}`)}}catch{}return o.join("|")}catch{return`fallback:${Date.now()}`}}function ah(){hn=null,Go=null,It=null}var ch=new Set(["spawn_agents"]),Do=5,Fo=3,Uo=2,lh=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),uh=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10),dh=process.env.NEX_STALE_AUTO_SWITCH!=="0";function fh(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{}}jp(t=>{Ip(t,"allow"),qp(),console.log(`${_.green} \u2713 ${t}: always allow${_.reset}`)});async function mh(t){let e=t.function.name,s=Cp(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let l=Lt().find(d=>d.function.name===e),u=l?JSON.stringify(l.function.parameters,null,2):"unknown";return console.log(`${_.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${_.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
346
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
343
347
|
|
|
344
348
|
Expected JSON schema for "${e}":
|
|
345
349
|
${u}
|
|
346
350
|
|
|
347
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=
|
|
348
|
-
`)[0]}${_.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(`${_.dim} \u2713 ${e}: corrected args (${u.join(", ")})${_.reset}`)}if(
|
|
351
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=Jp(e,s);if(!o.valid)return console.log(`${_.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
352
|
+
`)[0]}${_.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(`${_.dim} \u2713 ${e}: corrected args (${u.join(", ")})${_.reset}`)}if(ms()&&!Ac.has(e))return console.log(`${_.yellow} \u2717 ${e}: blocked in plan mode${_.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 i=Lp(e);if(i==="deny")return console.log(`${_.red} \u2717 ${e}: denied by permissions${_.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(i==="ask"){let c=` Allow ${e}?`;return e==="bash"&&r.command&&(c=` bash: \`${r.command.substring(0,80)}${r.command.length>80?"\u2026":""}\`?`),await Rc(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 ph(t,e,s={}){let n=await zp(t,e);if(n!==null)return n;let o=await Wp(t,e);return o!==null?o:Rp(t,e,s)}function hh(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 Wo(t,e=!1){e||console.log(vp(t.fnName,t.args)),kc("pre-tool",{tool_name:t.fnName});let s=await ph(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(s??""),o=n.length>5e4?n.substring(0,5e4)+`
|
|
349
353
|
...(truncated ${n.length-5e4} chars)`:n,r=o.split(`
|
|
350
|
-
`)[0],i=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),c=
|
|
351
|
-
`)}function
|
|
354
|
+
`)[0],i=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),c=Cc(t.fnName,t.args,o,i);return e||(console.log(Sp(o)),console.log(c)),kc("post-tool",{tool_name:t.fnName}),{msg:{role:"tool",content:rh(o),tool_call_id:t.callId},summary:c}}async function gh(t,e=!1,s={}){let n=new Array(t.length),o=[],r=[],i=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=hh(d.fnName,d.args);u=`\u23FA ${d.fnName}${f?`(${f})`:""}`}else{let d=l.map(f=>f.fnName).join(", ");u=`\u23FA ${l.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}i=new Pt(u),i.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await Wo(t[l],e);n[l]=u,o.push(d)}else{let l=r.map(d=>Wo(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(Cc(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(ch.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await Wo(u,e);n[l]=d,o.push(f)}else r.push(l)}if(await c(),i&&i.stop(),e&&o.length>0&&!s.skipSummaries)for(let l of o)console.log(l);return{results:n,summaries:o}}var ee=[],Tc=300,fs=[];function $h(t){fs.push(t.trim())}function yh(){return fs.length===0?null:fs.splice(0,fs.length).join(`
|
|
355
|
+
`)}function wh(){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
356
|
`];n?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),o.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),o.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),o.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),o.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),o.push(" \u2022 For Makefiles, always display the actual .PHONY declarations and dependency chains"),o.push(" \u2022 For dataclasses, always show the complete class definition with field types and defaults");let r=e||(n?"English":null);r&&o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let i=s||(n?"English":null);return i&&o.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),n&&o.push(`
|
|
353
357
|
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
358
|
`)+`
|
|
355
359
|
|
|
356
|
-
`}function
|
|
360
|
+
`}function bh(){if(It!==null)return It;try{let e=Xp().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:Yp(r.id,o.name),name:r.name})));if(e.length<2)return It="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
|
|
357
361
|
# Sub-Agent Model Routing
|
|
358
362
|
|
|
359
363
|
`;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
364
|
|---|---|---|
|
|
361
365
|
`;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
|
|
362
|
-
`;return
|
|
366
|
+
`;return It=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),It="",""}}async function Pc(){let t=await Mc();if(hn!==null&&t===Go)return hn;let e=await Ap(process.cwd()),s=Pp(),n=Hp(),o=ms()?Dp():"",r=wh();return hn=`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
367
|
|
|
364
368
|
WORKING DIRECTORY: ${process.cwd()}
|
|
365
369
|
All relative paths resolve from this directory.
|
|
@@ -480,7 +484,7 @@ When performing audits, code reviews, bug hunts, or security reviews:
|
|
|
480
484
|
- Good for: reading multiple files, analyzing separate modules.
|
|
481
485
|
- Bad for: tasks that depend on each other or modify the same file.
|
|
482
486
|
- Max 5 parallel agents.
|
|
483
|
-
${
|
|
487
|
+
${bh()}
|
|
484
488
|
|
|
485
489
|
# Edit Reliability (Critical)
|
|
486
490
|
|
|
@@ -531,20 +535,20 @@ You have access to a persistent knowledge base in .nex/brain/.
|
|
|
531
535
|
- Include tags in frontmatter for better retrieval
|
|
532
536
|
- The user reviews all brain writes via /brain review or git diff
|
|
533
537
|
|
|
534
|
-
`,
|
|
535
|
-
`):[]).filter(f=>{let m=f.split(".").pop();return r.has(m)});if(i.length<3)return null;let c={};for(let f of i){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=
|
|
536
|
-
\u{1F4E6} ${h}${p}`}}catch{}return u}function
|
|
537
|
-
${_.dim} ${i}${_.reset}`),s.size>0?console.log(`${_.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${_.reset}`):n.size>=5&&s.size===0&&t>=3?console.log(`${_.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${_.reset}`):n.size>0&&t>=2&&console.log(`${_.dim} \u{1F4A1} /save \xB7 /clear${_.reset}`)}async function
|
|
538
|
-
`),m==="")return c({action:"quit"});let p=i.find(g=>g.key===h);!p||p.key==="q"||!p.model&&p.key!=="r"?c({action:"quit"}):p.key==="r"?c({action:"retry"}):c({action:"switch",model:p.model,provider:t})};l.on("data",f)})}async function Ch(t){let e=Oc(t);ee.push({role:"user",content:e}),
|
|
538
|
+
`,Go=t,hn}function xh(){ee=[]}function _h(){ee.length>Tc&&ee.splice(0,ee.length-Tc)}function kh(){return ee.length}function vh(){return ee}function Sh(t){ee=t}async function Eh(){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"]),i=(o?o.split(`
|
|
539
|
+
`):[]).filter(f=>{let m=f.split(".").pop();return r.has(m)});if(i.length<3)return null;let c={};for(let f of i){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=Ko.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+=`
|
|
540
|
+
\u{1F4E6} ${h}${p}`}}catch{}return u}function $t(t,e,s,n,o){if(t<1)return;let r=[...e.values()].reduce((c,l)=>c+l,0),i=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${r} ${r===1?"tool":"tools"}`;if(s.size>0&&(i+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),o){let c=Date.now()-o,l=Math.round(c/1e3);i+=l>=60?` \xB7 ${Math.floor(l/60)}m ${l%60}s`:` \xB7 ${l}s`}i+=" \u2500\u2500",console.log(`
|
|
541
|
+
${_.dim} ${i}${_.reset}`),s.size>0?console.log(`${_.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${_.reset}`):n.size>=5&&s.size===0&&t>=3?console.log(`${_.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${_.reset}`):n.size>0&&t>=2&&console.log(`${_.dim} \u{1F4A1} /save \xB7 /clear${_.reset}`)}async function Th(){if(!process.stdout.isTTY)return{action:"quit"};let t=pn(),e=Bo(),s=ps.fast?.[t],n=ps.strong?.[t],o=s&&s!==e,r=n&&n!==e&&n!==s,i=[];i.push({key:"r",label:`Retry with current model ${_.dim}(${e})${_.reset}`}),o&&i.push({key:"f",label:`Switch to ${_.bold}${s}${_.reset} ${_.dim}\u2014 fast, low latency${_.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${_.bold}${n}${_.reset} ${_.dim}\u2014 reliable tool-calling, medium speed${_.reset}`,model:n}),i.push({key:"q",label:`${_.dim}Quit${_.reset}`}),console.log(),console.log(`${_.yellow} Stream stale \u2014 all retries exhausted.${_.reset} What would you like to do?`);for(let c of i)console.log(` ${_.cyan}[${c.key}]${_.reset} ${c.label}`);return process.stdout.write(` ${_.yellow}> ${_.reset}`),new Promise(c=>{let l=process.stdin,u=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let d=!1,f=m=>{if(d)return;d=!0,l.removeListener("data",f),l.setRawMode(u||!1),l.pause();let h=m.toLowerCase().trim();if(process.stdout.write(`${h}
|
|
542
|
+
`),m==="")return c({action:"quit"});let p=i.find(g=>g.key===h);!p||p.key==="q"||!p.model&&p.key!=="r"?c({action:"quit"}):p.key==="r"?c({action:"retry"}):c({action:"switch",model:p.model,provider:t})};l.on("data",f)})}async function Ch(t){let e=Oc(t);ee.push({role:"user",content:e}),_h();let{setOnChange:s}=Kn(),n=null,o=0;s((de,A)=>{de==="create"?(n&&n.stop(),n=new kp(A.name,A.tasks),n.setStats({tokens:o}),n.start()):de==="update"&&n?n.updateTask(A.id,A.status):de==="clear"&&n&&(n.stop(),n=null)});let r=await Pc(),i=r;try{let{getBrainContext:de}=rn(),A=await de(t);A&&(i=r+`
|
|
539
543
|
`+A+`
|
|
540
|
-
`)}catch(de){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",de.message)}let c=[{role:"system",content:i},...ee],l=new
|
|
541
|
-
${_.cyan}${_.bold}Plan ready.${_.reset} ${_.dim}Type ${_.reset}${_.cyan}/plan approve${_.reset}${_.dim} to execute, or ask follow-up questions to refine.${_.reset}`)}n&&(n.stop(),n=null),s(null)
|
|
542
|
-
${_.yellow}\u26A0 Max iterations reached.${_.reset}`),await Rc(" Continue for 20 more turns?")){ne=20;continue e}console.log(`${_.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${_.reset}`)}break e}}Lc.exports={processInput:Ch,clearConversation:
|
|
543
|
-
`),await t(c,i,d)}catch(u){if(s=u,
|
|
544
|
-
`);for(let y=0;y<h.length;y++){let $=Uc(h[y]);$>0&&(m+=Math.floor($/f))}let g=h.length-1+m;g>0&&(s._lastOutputRow=Math.min(s._lastOutputRow+g,s._scrollEnd))}return n(u,...d)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(u,...d){if(!s._active)return s._origStderrWrite(u,...d);if(typeof u=="string"&&u.includes("\r")){let f=Math.min(s._lastOutputRow+1,s._scrollEnd);s._origWrite(s._goto(f))}return s._origStderrWrite(u,...d)},this._origLog=console.log,this._origError=console.error;function o(...u){if(!s._active){s._origLog(...u);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origLog(...u),s.drawFooter()}function r(...u){if(!s._active){s._origError(...u);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origError(...u),s.drawFooter()}console.log=o,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(u){s._origSetPr(u),s._active&&s.drawFooter(u)},this._origPrompt=e.prompt.bind(e),e.prompt=function(u){if(!s._active)return s._origPrompt(u);e._prevPos=null,s._origWrite(s._goto(s._rowInput)),s._origPrompt(u),s._cursorOnInputRow=!0};let i=e.question.bind(e);e.question=function(u,d){if(!s._active)return i(u,d);s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),e._prevPos=null,s._cursorOnInputRow=!0,i(u,f=>{s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),s._cursorOnInputRow=!1,s.drawFooter(),d(f)})};let c=e._refreshLine?e._refreshLine.bind(e):null;this._origRefreshLine=c,c&&(e._refreshLine=function(){if(!s._active)return c();let u=s._cols,d=Uc(e._prompt||""),f=u-d-1;if(e.line.length<=f)return c();let m=e.line,h=e.cursor,p=Math.max(1,f-1),y=Math.max(0,h-p),$=(y>0?"\xAB":"")+m.slice(y,y+p+(y>0?0:1));e.line=$,e.cursor=$.length,c(),e.line=m,e.cursor=h}),e.on("line",u=>{s._active&&(s._cursorOnInputRow=!1,s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s.drawFooter())});let l=()=>{this._setScrollRegion(),this.drawFooter()};process.stdout.on("resize",l),this._offResize=()=>process.stdout.off("resize",l)}deactivate(){this._active&&(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine&&(this._rl._refreshLine=this._origRefreshLine,this._origRefreshLine=null)),this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null)}};Wc.exports={StickyFooter:
|
|
545
|
-
`);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 v=x;v<O;v++){let
|
|
544
|
+
`)}catch(de){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",de.message)}let c=[{role:"system",content:i},...ee],l=new Pt("Thinking...");l.start();let d=ee.length===1?Eh().catch(()=>null):Promise.resolve(null),f=Lt(),[{messages:m,compressed:h,compacted:p,tokensRemoved:g},y]=await Promise.all([Op(c,f),d]),$=Np(c,f);if(l.stop(),y&&console.log(`${_.dim}${y}${_.reset}`),p)console.log(`${_.dim} [context compacted \u2014 summary (~${g} tokens freed)]${_.reset}`);else if(h){let de=$.limit>0?Math.round(g/$.limit*100):0;console.log(`${_.dim} [context compressed \u2014 ~${g} tokens freed (${de}%)]${_.reset}`)}$.percentage>85&&console.log(`${_.yellow} \u26A0 Context ${Math.round($.percentage)}% full \u2014 consider /clear or /save + start fresh${_.reset}`);let x=m,O=0,k=0,v=0,T=0,S=0,C=new Map,F=new Set,I=new Set,V=Date.now(),D,ne=Ho,ie=0,ue=10;e:for(;;){for(D=0;D<ne&&!us()?.aborted;D++){let A=!0,L=null;if(n&&n.isActive())n._paused&&n.resume();else if(!n){let E=S>0?`Thinking... (step ${S+1})`:"Thinking...";L=new Pt(E),L.start()}let se=!0,z="",q=new Up,U,H=Date.now(),ae=!1,De=new AbortController,yt=setInterval(()=>{let E=Date.now()-H;if(E>=uh)q._clearCursorLine(),console.log(`${_.yellow} \u26A0 Stream stale for ${Math.round(E/1e3)}s \u2014 aborting and retrying${_.reset}`),De.abort();else if(E>=lh&&!ae){ae=!0,q._clearCursorLine();let j=ps.fast?.[pn()];console.log(`${_.yellow} \u26A0 No tokens received for ${Math.round(E/1e3)}s \u2014 waiting...${_.reset}`),j&&console.log(`${_.dim} \u{1F4A1} Ctrl+C \u2192 /model ${j} to switch to a faster model${_.reset}`)}},5e3),me="",ke=null;try{let E=Nc(Lt()),j=ms()?E.filter(pe=>Ac.has(pe.function.name)):E,wt=us(),W=new AbortController;wt&&wt.addEventListener("abort",()=>W.abort(),{once:!0}),De.signal.addEventListener("abort",()=>W.abort(),{once:!0}),U=await Tp(x,j,{signal:W.signal,onToken:pe=>{H=Date.now(),ae=!1,me+=pe,process.stdout.isTTY?ke||(ke=setTimeout(()=>{me&&q&&q.push(me),me="",ke=null},50)):(q.push(me),me=""),se&&(n&&!n._paused?n.pause():L&&L.stop(),A||(A=!0),q.startCursor(),se=!1),z+=pe}})}catch(E){if(clearInterval(yt),ke&&(clearTimeout(ke),ke=null),me&&q&&(q.push(me),me=""),n&&!n._paused&&n.pause(),L&&L.stop(),q.stopCursor(),De.signal.aborted&&!us()?.aborted){if(v++,v>Uo){if(T<1){T++,console.log(`${_.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${_.reset}`);let Ft=Lt(),{messages:Ut,tokensRemoved:bt}=Lo(x,Ft);x=Ut,console.log(`${_.dim} [force-compressed \u2014 ~${bt} tokens freed]${_.reset}`),v=0,D--;continue}n&&(n.stop(),n=null);let he=await Th();if(he.action==="quit"){s(null),$t(S,C,F,I,V),gt(ee);break}he.action==="switch"&&(Sc(`${he.provider}:${he.model}`),console.log(`${_.green} \u2713 Switched to ${he.provider}:${he.model}${_.reset}`)),v=0,T=0,D--;continue}let W=v===1?3e3:5e3;if(v>=2&&T<1){T++,console.log(`${_.yellow} \u26A0 Stale retry ${v}/${Uo} \u2014 force-compressing before retry...${_.reset}`);let he=Lt(),{messages:Ft,tokensRemoved:Ut}=Lo(x,he);if(x=Ft,console.log(`${_.dim} [force-compressed \u2014 ~${Ut} tokens freed]${_.reset}`),dh){let bt=ps.fast?.[pn()];bt&&bt!==Bo()&&(Sc(`${pn()}:${bt}`),console.log(`${_.cyan} \u26A1 Auto-switched to ${bt} to avoid further stale timeouts${_.reset}`),console.log(`${_.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${_.reset}`))}}else console.log(`${_.yellow} \u26A0 Stale retry ${v}/${Uo} \u2014 retrying in ${W/1e3}s...${_.reset}`);let pe=new Pt(`Waiting ${W/1e3}s before retry...`);pe.start(),await new Promise(he=>setTimeout(he,W)),pe.stop(),D--;continue}if(E.name==="AbortError"||E.name==="CanceledError"||E.message?.includes("canceled")||E.message?.includes("aborted")){n&&(n.stop(),n=null),s(null),$t(S,C,F,I,V),gt(ee);break}let j=E.message;if(E.code==="ECONNREFUSED"||E.message.includes("ECONNREFUSED"))j="Connection refused \u2014 please check your internet connection or API endpoint";else if(E.code==="ENOTFOUND"||E.message.includes("ENOTFOUND"))j="Network error \u2014 could not reach the API server. Please check your connection";else if(E.code==="ETIMEDOUT"||E.message.includes("timeout"))j="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"))j="Authentication failed \u2014 please check your API key in the .env file";else if(E.message.includes("403")||E.message.includes("Forbidden"))j="Access denied \u2014 your API key may not have permission for this model";else if(E.message.includes("400")){let W=(E.message||"").toLowerCase(),pe=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(pe&&T<1){T++,console.log(`${_.yellow} \u26A0 Context too long \u2014 force-compressing and retrying...${_.reset}`);let he=Lt(),{messages:Ft,tokensRemoved:Ut}=Lo(x,he);x=Ft,console.log(`${_.dim} [force-compressed \u2014 ~${Ut} tokens freed]${_.reset}`),D--;continue}pe?j="Context too long \u2014 force compression exhausted. Use /clear to start fresh":j="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")?j="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(E.message.includes("fetch failed")||E.message.includes("fetch"))&&(j="Network request failed \u2014 please check your internet connection");if(console.log(`${_.red} \u2717 ${j}${_.reset}`),E.message.includes("429")){if(O++,O>Do){console.log(`${_.red} Rate limit: max retries (${Do}) exceeded. Try again later or use /budget to check your limits.${_.reset}`),n&&(n.stop(),n=null),s(null),$t(S,C,F,I,V),gt(ee);break}let W=Math.min(1e4*Math.pow(2,O-1),12e4),pe=new Pt(`Rate limit \u2014 waiting ${Math.round(W/1e3)}s (retry ${O}/${Do})`);pe.start(),await new Promise(he=>setTimeout(he,W)),pe.stop();continue}if(E.message.includes("socket disconnected")||E.message.includes("TLS")||E.message.includes("ECONNRESET")||E.message.includes("ECONNABORTED")||E.message.includes("ETIMEDOUT")||E.code==="ECONNRESET"||E.code==="ECONNABORTED"){if(k++,k>Fo){console.log(`${_.red} Network error: max retries (${Fo}) exceeded. Check your connection and try again.${_.reset}`),n&&(n.stop(),n=null),s(null),$t(S,C,F,I,V),gt(ee);break}let W=Math.min(2e3*Math.pow(2,k-1),3e4),pe=new Pt(`Network error \u2014 retrying in ${Math.round(W/1e3)}s (${k}/${Fo})`);pe.start(),await new Promise(he=>setTimeout(he,W)),pe.stop(),D--;continue}n&&(n.stop(),n=null),s(null),$t(S,C,F,I,V),gt(ee);break}clearInterval(yt),O=0,k=0,se&&(n&&!n._paused&&n.pause(),L&&L.stop()),ke&&(clearTimeout(ke),ke=null),me&&q&&(q.push(me),me=""),z&&q.flush(),k=0,v=0,U&&U.usage&&(Kp(pn(),Bo(),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:ws,tool_calls:st}=U,bs={role:"assistant",content:ws||""};if(st&&st.length>0&&(bs.tool_calls=st),ee.push(bs),x.push(bs),!st||st.length===0){let E=(ws||"").trim().length>0||z.trim().length>0;if(!E&&S>0&&D<Ho-1){let j={role:"user",content:"[SYSTEM] You ran tools but produced no visible output. The user CANNOT see tool results \u2014 only your text. Please summarize your findings now."};x.push(j),ee.push(j);continue}if(ms()&&E){let j=(ws||z||"").trim();Fp(j),fh(j),console.log(`
|
|
545
|
+
${_.cyan}${_.bold}Plan ready.${_.reset} ${_.dim}Type ${_.reset}${_.cyan}/plan approve${_.reset}${_.dim} to execute, or ask follow-up questions to refine.${_.reset}`)}n&&(n.stop(),n=null),s(null),$t(S,C,F,I,V),gt(ee);return}S++,S>1&&(A=!1);for(let E of st){let j=E.function.name;C.set(j,(C.get(j)||0)+1)}let wn=await Promise.all(st.map(E=>mh(E))),xs=n?{skipSpinner:!0,skipSummaries:!0}:{},mr=!xs.skipSummaries&&!A;mr&&(A=!0),n&&n._paused&&n.resume();let{results:pr,summaries:bn}=await gh(wn,!0,{...xs,skipSummaries:!0});if(!xs.skipSummaries)if(mr){let E=Ep(wn,S);if(bn.length===1)console.log(E+bn[0]);else{console.log(E);for(let j of bn)console.log(j)}}else for(let E of bn)console.log(E);for(let E=0;E<wn.length;E++){let j=wn[E];if(!j.canExecute)continue;let wt=pr[E].content,W=!wt.startsWith("ERROR")&&!wt.includes("CANCELLED");W&&["write_file","edit_file","patch_file"].includes(j.fnName)&&j.args&&j.args.path&&F.add(j.args.path),W&&j.fnName==="read_file"&&j.args&&j.args.path&&I.add(j.args.path)}for(let E of pr)ee.push(E),x.push(E);let hr=yh();if(hr){let E={role:"user",content:`[User note mid-run]: ${hr}`};ee.push(E),x.push(E),console.log(`${_.cyan} \u270E Kontext hinzugef\xFCgt${_.reset}`)}}if(D>=ne){n&&(n.stop(),n=null),s(null),$t(S,C,F,I,V),gt(ee);let{getActiveProviderName:de}=ge();if(de()==="ollama"&&ie<ue){ie++,ne=20,console.log(`${_.dim} \u2500\u2500 auto-extending (+20 turns, ext ${ie}/${ue}) \u2500\u2500${_.reset}`);continue e}if(console.log(`
|
|
546
|
+
${_.yellow}\u26A0 Max iterations reached.${_.reset}`),await Rc(" Continue for 20 more turns?")){ne=20;continue e}console.log(`${_.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${_.reset}`)}break e}}Lc.exports={processInput:Ch,clearConversation:xh,getConversationLength:kh,getConversationMessages:vh,setConversationMessages:Sh,setAbortSignalGetter:eh,setMaxIterations:Zp,invalidateSystemPromptCache:ah,clearToolFilterCache:ih,getCachedFilteredTools:Nc,buildSystemPrompt:Pc,getProjectContextHash:Mc,buildUserContent:Oc,injectMidRunNote:$h}});var ge=M((L$,Fc)=>{var{OllamaProvider:Rh}=Nr(),{OpenAIProvider:Ah}=Yr(),{AnthropicProvider:Oh}=Zr(),{GeminiProvider:Nh}=si(),{LocalProvider:Mh}=ii(),{checkBudget:Ph}=vt(),Jo={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"}},Ic={};for(let[t,e]of Object.entries(Jo))for(let s of Object.values(e))Ic[s]=t;function qc(t,e){let s=Ic[t];return s&&Jo[s][e]||t}var fe={},_e=null,le=null,gn=[];function Ce(){if(Object.keys(fe).length>0)return;qt("ollama",new Rh),qt("openai",new Ah),qt("anthropic",new Oh),qt("gemini",new Nh),qt("local",new Mh);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;fe[t]?(_e=t,le=e||fe[t].defaultModel):(_e="ollama",le="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(gn=s.split(",").map(n=>n.trim()).filter(Boolean))}function qt(t,e){fe[t]=e}function Lh(t){return Ce(),fe[t]||null}function Yo(){return Ce(),fe[_e]||null}function Ih(){return Ce(),_e}function qh(){return Ce(),le}function jh(){Ce();let t=Yo();if(!t)return{id:le,name:le,provider:_e};let e=t.getModel(le);return e?{...e,provider:_e}:{id:le,name:le,provider:_e}}function jc(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if(fe[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function Dh(t){Ce();let{provider:e,model:s}=jc(t);if(e){let o=fe[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(_e=e,le=s,hs(),!0):!1}let n=Yo();if(n&&n.getModel(s))return le=s,hs(),!0;for(let[o,r]of Object.entries(fe))if(r.getModel(s))return _e=o,le=s,hs(),!0;return!1}function hs(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=ce();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Re();t()}catch{}}function Fh(){Ce();let t=new Set;for(let e of Object.values(fe))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function Uh(){return Ce(),Object.entries(fe).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===_e&&s.id===le}))}))}function Wh(){Ce();let t=[];for(let[e,s]of Object.entries(fe)){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 Bh(t){gn=Array.isArray(t)?t:[]}function Hh(){return[...gn]}function Gh(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 Dc(t){let e=[_e,...gn.filter(r=>r!==_e)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],c=fe[i];if(!c||!c.isConfigured())continue;o++;let l=Ph(i);if(!l.allowed){n++,s=new Error(`Budget limit reached for ${i}: $${l.spent.toFixed(2)} / $${l.limit.toFixed(2)}`);continue}try{let u=r>0,d=u?qc(le,i):le;return u&&d!==le&&process.stderr.write(` [fallback: ${i}:${d}]
|
|
547
|
+
`),await t(c,i,d)}catch(u){if(s=u,Gh(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 zh(t,e,s={}){return Ce(),Dc((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function Kh(t,e,s={}){if(Ce(),s.provider){let n=fe[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||le,...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 Dc(async(n,o,r)=>{try{return await n.chat(t,e,{model:r,...s})}catch(i){if(typeof n.stream=="function")try{return await n.stream(t,e,{model:r,...s,onToken:()=>{}})}catch{}throw i}})}function Jh(){Ce();let t=[];for(let[e,s]of Object.entries(fe))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function Yh(){for(let t of Object.keys(fe))delete fe[t];_e=null,le=null,gn=[]}Fc.exports={registerProvider:qt,getProvider:Lh,getActiveProvider:Yo,getActiveProviderName:Ih,getActiveModelId:qh,getActiveModel:jh,setActiveModel:Dh,getModelNames:Fh,parseModelSpec:jc,listProviders:Uh,listAllModels:Wh,callStream:zh,callChat:Kh,getConfiguredProviders:Jh,setFallbackChain:Bh,getFallbackChain:Hh,resolveModelForProvider:qc,MODEL_EQUIVALENTS:Jo,_reset:Yh}});var Bc=M((I$,Wc)=>{"use strict";var Xh="\x1B[2m",Vh="\x1B[0m";function Uc(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Xo=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 Xh+"\u2500".repeat(this._cols)+Vh}drawFooter(e){!this._origWrite||this._drawing||(this._drawing=!0,this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K"+this._statusLine(e)+"\x1B8"),this._drawing=!1)}_setScrollRegion(){let e=Math.max(1,this._scrollEnd);this._origWrite(`\x1B[1;${e}r`)}_clearScrollRegion(){this._origWrite&&this._origWrite("\x1B[r")}_eraseStatus(){this._origWrite&&this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K\x1B8")}activate(e){if(!process.stdout.isTTY)return;this._rl=e,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let s=this,n=process.stdout.write.bind(process.stdout);this._origWrite=n,process.stdout.write=function(u,...d){if(s._active&&typeof u=="string"){if(s._cursorOnInputRow){let y=u.replace(/\n/g,"");return y?n(y,...d):!0}let f=s._cols||80,m=0,h=u.split(`
|
|
548
|
+
`);for(let y=0;y<h.length;y++){let $=Uc(h[y]);$>0&&(m+=Math.floor($/f))}let g=h.length-1+m;g>0&&(s._lastOutputRow=Math.min(s._lastOutputRow+g,s._scrollEnd))}return n(u,...d)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(u,...d){if(!s._active)return s._origStderrWrite(u,...d);if(typeof u=="string"&&u.includes("\r")){let f=Math.min(s._lastOutputRow+1,s._scrollEnd);s._origWrite(s._goto(f))}return s._origStderrWrite(u,...d)},this._origLog=console.log,this._origError=console.error;function o(...u){if(!s._active){s._origLog(...u);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origLog(...u),s.drawFooter()}function r(...u){if(!s._active){s._origError(...u);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origError(...u),s.drawFooter()}console.log=o,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(u){s._origSetPr(u),s._active&&s.drawFooter(u)},this._origPrompt=e.prompt.bind(e),e.prompt=function(u){if(!s._active)return s._origPrompt(u);e._prevPos=null,s._origWrite(s._goto(s._rowInput)),s._origPrompt(u),s._cursorOnInputRow=!0};let i=e.question.bind(e);e.question=function(u,d){if(!s._active)return i(u,d);s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),e._prevPos=null,s._cursorOnInputRow=!0,i(u,f=>{s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),s._cursorOnInputRow=!1,s.drawFooter(),d(f)})};let c=e._refreshLine?e._refreshLine.bind(e):null;this._origRefreshLine=c,c&&(e._refreshLine=function(){if(!s._active)return c();let u=s._cols,d=Uc(e._prompt||""),f=u-d-1;if(e.line.length<=f)return c();let m=e.line,h=e.cursor,p=Math.max(1,f-1),y=Math.max(0,h-p),$=(y>0?"\xAB":"")+m.slice(y,y+p+(y>0?0:1));e.line=$,e.cursor=$.length,c(),e.line=m,e.cursor=h}),e.on("line",u=>{s._active&&(s._cursorOnInputRow=!1,s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s.drawFooter())});let l=()=>{this._setScrollRegion(),this.drawFooter()};process.stdout.on("resize",l),this._offResize=()=>process.stdout.off("resize",l)}deactivate(){this._active&&(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine&&(this._rl._refreshLine=this._origRefreshLine,this._origRefreshLine=null)),this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null)}};Wc.exports={StickyFooter:Xo}});var zc=M((q$,Gc)=>{var{C:J}=oe(),{listProviders:Qh,getActiveProviderName:Zh,getActiveModelId:eg,setActiveModel:tg}=ge();function Hc(t,e,s={}){let{title:n="Select",hint:o="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=s;return new Promise(r=>{let i=e.map(($,x)=>$.isHeader?-1:x).filter($=>$>=0);if(i.length===0){r(null);return}let c=e.findIndex($=>$.isCurrent),l=c>=0?i.indexOf(c):0;l<0&&(l=0);let u=process.stdout.rows?Math.max(process.stdout.rows-6,5):20,d=0;function f(){let $=i[l];return $<d?d=$:$>=d+u&&(d=$-u+1),{start:d,end:Math.min(e.length,d+u)}}let m=0;function h(){if(m>0){process.stdout.write(`\x1B[${m}A`);for(let v=0;v<m;v++)process.stdout.write(`\x1B[2K
|
|
549
|
+
`);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 v=x;v<O;v++){let T=e[v];if(T.isHeader){$.push(` ${J.bold}${J.dim}${T.label}${J.reset}`);continue}let S=i[l]===v,C=S?`${J.cyan}> `:" ",F=T.isCurrent?` ${J.yellow}<current>${J.reset}`:"";S?$.push(`${C}${J.bold}${T.label}${J.reset}${F}`):$.push(`${C}${J.dim}${T.label}${J.reset}${F}`)}O<e.length&&$.push(` ${J.dim}\u2193 more${J.reset}`);let k=$.join(`
|
|
546
550
|
`);process.stdout.write(k+`
|
|
547
|
-
`),m=$.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function y($,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<i.length-1&&(l++,h());return}if(x.name==="return"){let O=e[i[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",y),h()})}async function
|
|
551
|
+
`),m=$.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function y($,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<i.length-1&&(l++,h());return}if(x.name==="return"){let O=e[i[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",y),h()})}async function ng(t){let e=Qh(),s=Zh(),n=eg(),o=[];for(let i of e)if(i.models.length!==0){o.push({label:i.provider,value:null,isHeader:!0});for(let c of i.models){let l=i.provider===s&&c.id===n;o.push({label:` ${c.name} (${i.provider}:${c.id})`,value:`${i.provider}:${c.id}`,isCurrent:l})}}let r=await Hc(t,o,{title:"Select Model"});return r?(tg(r),console.log(`${J.green}Switched to ${r}${J.reset}`),!0):(console.log(`${J.dim}Cancelled${J.reset}`),!1)}Gc.exports={pickFromList:Hc,showModelPicker:ng}});var Zo=M((D$,Zc)=>{var Vo=require("fs"),sg=require("path"),{callChat:Kc}=ge(),{remember:og,listMemories:j$,recall:rg}=Ze(),Qo=4,ig=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
548
552
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
549
553
|
|
|
550
554
|
Return ONLY valid JSON in this exact format:
|
|
@@ -572,13 +576,13 @@ Rules:
|
|
|
572
576
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
573
577
|
- Return ONLY the JSON, no markdown, no explanation`;function Jc(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(`
|
|
574
578
|
|
|
575
|
-
`)}async function Yc(t){if(t.filter(o=>o.role==="user").length<
|
|
579
|
+
`)}async function Yc(t){if(t.filter(o=>o.role==="user").length<Qo)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=Jc(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=[{role:"system",content:ig},{role:"user",content:`Conversation to analyze:
|
|
576
580
|
|
|
577
|
-
${s}`}];try{let i=((await Kc(n,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let c=JSON.parse(i[0]);return{memories:Array.isArray(c.memories)?c.memories:[],nex_additions:Array.isArray(c.nex_additions)?c.nex_additions:[],summary:typeof c.summary=="string"?c.summary:null}}catch(o){return{memories:[],nex_additions:[],summary:null,error:o.message}}}function Xc(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 i=
|
|
581
|
+
${s}`}];try{let i=((await Kc(n,[],{temperature:0,maxTokens:800})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{memories:[],nex_additions:[],summary:null,error:"No JSON in response"};let c=JSON.parse(i[0]);return{memories:Array.isArray(c.memories)?c.memories:[],nex_additions:Array.isArray(c.nex_additions)?c.nex_additions:[],summary:typeof c.summary=="string"?c.summary:null}}catch(o){return{memories:[],nex_additions:[],summary:null,error:o.message}}}function Xc(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 i=rg(o);i!==r&&(og(o,r),e.push({key:o,value:r,action:i?"updated":"added"}))}return e}function Vc(t){if(!t||t.length===0)return[];let e=sg.join(process.cwd(),"NEX.md"),s="";try{Vo.existsSync(e)&&(s=Vo.readFileSync(e,"utf-8"))}catch{}let n=[],o=s;for(let r of t){if(!r||typeof r!="string")continue;let i=r.trim();if(!i)continue;let c=i.substring(0,35).toLowerCase();s.toLowerCase().includes(c)||(n.push(i),o=o?o.endsWith(`
|
|
578
582
|
`)?o+i:o+`
|
|
579
583
|
`+i:i)}return n.length>0&&(o.endsWith(`
|
|
580
584
|
`)||(o+=`
|
|
581
|
-
`),
|
|
585
|
+
`),Vo.writeFileSync(e,o,"utf-8")),n}async function ag(t){let e=await Yc(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=Xc(e.memories),n=Vc(e.nex_additions);return{applied:s,nexAdded:n,summary:e.summary}}var cg=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
582
586
|
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
583
587
|
|
|
584
588
|
Return ONLY valid JSON in this exact format:
|
|
@@ -612,37 +616,37 @@ Rules:
|
|
|
612
616
|
---
|
|
613
617
|
- Maximum 3 documents per session. Quality over quantity.
|
|
614
618
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
615
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function Qc(t){if(t.filter(o=>o.role==="user").length<
|
|
619
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function Qc(t){if(t.filter(o=>o.role==="user").length<Qo)return{documents:[],skip_reason:"Session too short"};let s=Jc(t);if(!s.trim())return{documents:[],skip_reason:"No usable content"};let n=[{role:"system",content:cg},{role:"user",content:`Conversation to analyze:
|
|
616
620
|
|
|
617
|
-
${s}`}];try{let i=((await Kc(n,[],{temperature:0,maxTokens:2e3})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{documents:[],error:"No JSON in response"};let c=JSON.parse(i[0]);return{documents:Array.isArray(c.documents)?c.documents:[],skip_reason:c.skip_reason}}catch(o){return{documents:[],error:o.message}}}async function
|
|
621
|
+
${s}`}];try{let i=((await Kc(n,[],{temperature:0,maxTokens:2e3})).content||"").trim().match(/\{[\s\S]*\}/);if(!i)return{documents:[],error:"No JSON in response"};let c=JSON.parse(i[0]);return{documents:Array.isArray(c.documents)?c.documents:[],skip_reason:c.skip_reason}}catch(o){return{documents:[],error:o.message}}}async function lg(t){let e=await Qc(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}=rn(),o=[],r=[];for(let i of e.documents){if(!i.name||!i.content)continue;let c=i.name.trim().replace(/\.md$/,"").replace(/[^a-z0-9-]/g,"-").substring(0,60);if(!c)continue;let l=n(c);if(l.content){let d=`
|
|
618
622
|
|
|
619
623
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
620
624
|
|
|
621
|
-
${i.content}`;s(c,l.content+d),o.push({name:c,reason:i.reason||"",action:"updated"})}else s(c,i.content),o.push({name:c,reason:i.reason||"",action:"created"})}return{written:o,skipped:r}}Zc.exports={learnFromSession:
|
|
625
|
+
${i.content}`;s(c,l.content+d),o.push({name:c,reason:i.reason||"",action:"updated"})}else s(c,i.content),o.push({name:c,reason:i.reason||"",action:"created"})}return{written:o,skipped:r}}Zc.exports={learnFromSession:ag,learnBrainFromSession:lg,reflectOnSession:Yc,reflectBrain:Qc,applyMemories:Xc,applyNexAdditions:Vc,LEARN_MIN_MESSAGES:Qo}});var ol=M((U$,sl)=>{var ye=require("fs"),Dt=require("path"),F$=require("os"),ug=require("readline"),{C:R}=oe(),el=".nex",er=null;function dg(t){er=t}function Se(t,e=""){let s=e?` ${R.dim}[${e}]${R.reset}`:"",n=` ${R.cyan}${t}${s}${R.reset}: `;return new Promise(o=>{let r=i=>{let c=i.trim()||e;o(c)};if(er)er.question(n,r);else{let i=ug.createInterface({input:process.stdin,output:process.stdout});i.question(n,c=>{i.close(),r(c)})}})}function jt(t,e=!0){return Se(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(n=>n.toLowerCase()!=="n"&&n.toLowerCase()!=="no")}async function tl(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 Se("Enter number",String(o)),i=parseInt(r,10)-1;return e[Math.max(0,Math.min(i,e.length-1))]}async function fg(){let t=Dt.join(process.cwd(),el),e=Dt.join(t,"servers.json"),s={};if(ye.existsSync(e))try{s=JSON.parse(ye.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
622
626
|
${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}
|
|
623
|
-
`);let n=Object.keys(s);if(n.length>0&&(console.log(`${R.dim}Existing profiles: ${n.join(", ")}${R.reset}`),!await
|
|
627
|
+
`);let n=Object.keys(s);if(n.length>0&&(console.log(`${R.dim}Existing profiles: ${n.join(", ")}${R.reset}`),!await jt("Add or update a server profile?",!0))){console.log(`${R.dim}No changes made.${R.reset}
|
|
624
628
|
`);return}let o={...s},r=!0;for(;r;){console.log(`
|
|
625
|
-
${R.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${R.reset}`);let l=await Se("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${R.red} Name is required.${R.reset}`);continue}let u=await Se("Host / IP address");if(!u){console.log(`${R.red} Host is required.${R.reset}`);continue}let d=await Se("SSH user","root"),f=await Se("SSH port","22"),m=parseInt(f,10)||22,h=await Se("SSH key path (leave empty for SSH agent)",""),p=await tl("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await
|
|
626
|
-
${R.green}\u2713${R.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${p!=="other"?` [${p}]`:""}`),r=await
|
|
629
|
+
${R.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${R.reset}`);let l=await Se("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${R.red} Name is required.${R.reset}`);continue}let u=await Se("Host / IP address");if(!u){console.log(`${R.red} Host is required.${R.reset}`);continue}let d=await Se("SSH user","root"),f=await Se("SSH port","22"),m=parseInt(f,10)||22,h=await Se("SSH key path (leave empty for SSH agent)",""),p=await tl("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await jt("Allow sudo commands?",!0),y={host:u,user:d};m!==22&&(y.port=m),h&&(y.key=h),p!=="other"&&(y.os=p),g&&(y.sudo=!0),o[l]=y,console.log(`
|
|
630
|
+
${R.green}\u2713${R.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${p!=="other"?` [${p}]`:""}`),r=await jt(`
|
|
627
631
|
Add another server?`,!1)}ye.existsSync(t)||ye.mkdirSync(t,{recursive:!0}),ye.writeFileSync(e,JSON.stringify(o,null,2)+`
|
|
628
632
|
`,"utf-8"),console.log(`
|
|
629
|
-
${R.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${R.reset}`);let i=
|
|
633
|
+
${R.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${R.reset}`);let i=Dt.join(process.cwd(),".gitignore");ye.existsSync(i)&&(ye.readFileSync(i,"utf-8").includes(".nex/")||await jt("Add .nex/ to .gitignore?",!0)&&(ye.appendFileSync(i,`
|
|
630
634
|
# nex-code server profiles
|
|
631
635
|
.nex/
|
|
632
|
-
`),console.log(`${R.green}\u2713 Added .nex/ to .gitignore${R.reset}`))),await
|
|
636
|
+
`),console.log(`${R.green}\u2713 Added .nex/ to .gitignore${R.reset}`))),await jt(`
|
|
633
637
|
Set up deploy configs (.nex/deploy.json)?`,!1)&&await nl(o,t),console.log(`
|
|
634
638
|
${R.dim}Use /servers to list profiles, /servers ping to check connectivity.${R.reset}
|
|
635
|
-
`)}async function nl(t,e){let s=e||
|
|
639
|
+
`)}async function nl(t,e){let s=e||Dt.join(process.cwd(),el),n=Dt.join(s,"deploy.json"),o={};if(ye.existsSync(n))try{o=JSON.parse(ye.readFileSync(n,"utf-8"))}catch{}if(!t){let u=Dt.join(s,"servers.json");if(ye.existsSync(u))try{t=JSON.parse(ye.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
636
640
|
${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}
|
|
637
641
|
`);let i=Object.keys(o);i.length>0&&console.log(`${R.dim}Existing deploy configs: ${i.join(", ")}${R.reset}`);let c={...o},l=!0;for(;l;){console.log(`
|
|
638
642
|
${R.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${R.reset}`);let u=await Se("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 tl("Target server",r,r[0]):d=await Se("Target server (profile name or user@host)");let f=await Se("Local path to sync (e.g. dist/ or ./build)","dist/"),m=await Se("Remote destination path (e.g. /var/www/app)");if(!m){console.log(`${R.red} Remote path is required.${R.reset}`);continue}let h=await Se("Deploy script to run after sync (leave empty to skip)",""),p=await Se("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env"),g=p?p.split(",").map(x=>x.trim()).filter(Boolean):[],y={server:d,local_path:f,remote_path:m};h&&(y.deploy_script=h),g.length>0&&(y.exclude=g),c[u]=y;let $=f.endsWith("/")?f:`${f}/`;console.log(`
|
|
639
|
-
${R.green}\u2713${R.reset} Deploy config "${u}": ${$} \u2192 ${d}:${m}`),h&&console.log(` ${R.dim} Then: ${h}${R.reset}`),l=await
|
|
643
|
+
${R.green}\u2713${R.reset} Deploy config "${u}": ${$} \u2192 ${d}:${m}`),h&&console.log(` ${R.dim} Then: ${h}${R.reset}`),l=await jt(`
|
|
640
644
|
Add another deploy config?`,!1)}ye.existsSync(s)||ye.mkdirSync(s,{recursive:!0}),ye.writeFileSync(n,JSON.stringify(c,null,2)+`
|
|
641
645
|
`,"utf-8"),console.log(`
|
|
642
646
|
${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}
|
|
643
|
-
`)}sl.exports={runServerWizard:
|
|
647
|
+
`)}sl.exports={runServerWizard:fg,runDeployWizard:nl,setWizardRL:dg}});var al=M((W$,il)=>{var mg=require("axios"),$n=require("fs"),rl=require("path"),pg="nex-code",tr=rl.join(process.cwd(),".nex"),nr=rl.join(tr,"last-version-check");$n.existsSync(tr)||$n.mkdirSync(tr,{recursive:!0});async function hg(){try{let t=$g(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};yg(e);let s=gg(),o=(await mg.get(`https://registry.npmjs.org/${pg}/latest`,{timeout:5e3})).data.version,r=wg(o,s);return{hasNewVersion:r,latestVersion:r?o:void 0,currentVersion:r?s:void 0}}catch{return{hasNewVersion:!1}}}function gg(){return xn().version}function $g(){try{if($n.existsSync(nr)){let t=$n.readFileSync(nr,"utf8");return parseInt(t,10)}}catch{}return null}function yg(t){try{$n.writeFileSync(nr,t.toString())}catch{}}function wg(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}}il.exports={checkForNewVersion:hg}});var _l=M((H$,xl)=>{var bg=require("readline"),nt=require("fs"),je=require("path"),{C:a,banner:xg,cleanupTerminal:cl}=oe(),{listProviders:or,getActiveProviderName:et,listAllModels:B$,setFallbackChain:_g,getFallbackChain:kg,getProvider:vg}=ge(),{flushAutoSave:ll}=dt(),{getActiveModel:tt,setActiveModel:ul}=Nn(),{printContext:dl}=xo(),{loadAllSkills:Sg,getSkillCommands:rr,handleSkillCommand:Eg}=Kt(),{setReadlineInterface:Tg,setAutoConfirm:Cg,getAutoConfirm:fl}=Me(),{StickyFooter:Rg}=Bc(),$s=process.cwd(),Je=null;function ml(){return Je?.signal??null}var ys=[{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 pl(){let t=rr(),e=[...ys,...t],s=Math.max(...e.map(n=>n.cmd.length));console.log("");for(let{cmd:n,desc:o}of ys)console.log(` ${a.cyan}${n.padEnd(s+2)}${a.reset}${a.dim}${o}${a.reset}`);for(let{cmd:n,desc:o}of t)console.log(` ${a.cyan}${n.padEnd(s+2)}${a.reset}${a.dim}${o} ${a.yellow}[skill]${a.reset}`);console.log(`
|
|
644
648
|
${a.dim}Type /help for detailed usage${a.reset}
|
|
645
|
-
`)}function hl(t){try{let e,s;t.endsWith("/")||t.endsWith(
|
|
649
|
+
`)}function hl(t){try{let e,s;t.endsWith("/")||t.endsWith(je.sep)?(e=t,s=""):(e=je.dirname(t),s=je.basename(t)),e.startsWith("~")&&(e=je.join(require("os").homedir(),e.slice(1)));let n=je.isAbsolute(e)?e:je.resolve($s,e);if(!nt.existsSync(n)||!nt.statSync(n).isDirectory())return[];let o=nt.readdirSync(n,{withFileTypes:!0}),r=[];for(let i of o){if(i.name.startsWith(".")||i.name==="node_modules"||s&&!i.name.startsWith(s))continue;let c=t.endsWith("/")||t.endsWith(je.sep)?t:je.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?i.name:c+i.name;r.push(i.isDirectory()?l+"/":l)}return r}catch{return[]}}function gl(t){if(t.startsWith("/")){let n=[...ys,...rr()],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("~"))?[hl(s),s]:[[],t]}function $l(){console.log(`
|
|
646
650
|
${a.bold}${a.cyan}Commands:${a.reset}
|
|
647
651
|
${a.cyan}/help${a.reset} ${a.dim}Show this help${a.reset}
|
|
648
652
|
${a.cyan}/model [spec]${a.reset} ${a.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${a.reset}
|
|
@@ -703,18 +707,18 @@ ${a.bold}${a.cyan}Undo / Redo:${a.reset}
|
|
|
703
707
|
${a.cyan}/history${a.reset} ${a.dim}Show file change history${a.reset}
|
|
704
708
|
|
|
705
709
|
${a.cyan}/exit${a.reset} ${a.dim}Quit${a.reset}
|
|
706
|
-
`)}function yl(t){let s=Math.round(t/100*30),n=30-s;return` ${t>80?a.red:t>50?a.yellow:a.green}${"\u2588".repeat(s)}${a.dim}${"\u2591".repeat(n)}${a.reset} ${t}%`}function
|
|
707
|
-
${a.bold}${a.cyan}Providers:${a.reset}`);for(let n of t){let o=n.provider===e,r=n.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,i=o?` ${a.cyan}(active)${a.reset}`:"";console.log(` ${r} ${a.bold}${n.provider}${a.reset}${i}`);for(let c of n.models){let l=c.id===s.id&&o?` ${a.yellow}\u25C4${a.reset}`:"";console.log(` ${a.dim}${c.id}${a.reset} \u2014 ${c.name}${l}`)}}console.log()}async function wl(t,e){let[s,...n]=t.split(/\s+/);switch(s){case"/help":return $l(),!0;case"/model":{let o=n.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=zc();await r(e)}else{let r=
|
|
710
|
+
`)}function yl(t){let s=Math.round(t/100*30),n=30-s;return` ${t>80?a.red:t>50?a.yellow:a.green}${"\u2588".repeat(s)}${a.dim}${"\u2591".repeat(n)}${a.reset} ${t}%`}function sr(){let t=or(),e=et(),s=tt();console.log(`
|
|
711
|
+
${a.bold}${a.cyan}Providers:${a.reset}`);for(let n of t){let o=n.provider===e,r=n.configured?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,i=o?` ${a.cyan}(active)${a.reset}`:"";console.log(` ${r} ${a.bold}${n.provider}${a.reset}${i}`);for(let c of n.models){let l=c.id===s.id&&o?` ${a.yellow}\u25C4${a.reset}`:"";console.log(` ${a.dim}${c.id}${a.reset} \u2014 ${c.name}${l}`)}}console.log()}async function wl(t,e){let[s,...n]=t.split(/\s+/);switch(s){case"/help":return $l(),!0;case"/model":{let o=n.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=zc();await r(e)}else{let r=tt(),i=et();console.log(`${a.bold}${a.cyan}Active model:${a.reset} ${a.dim}${i}:${r.id} (${r.name})${a.reset}`),console.log(`${a.gray}Use /model <provider:model> to switch. /providers to see all.${a.reset}`)}return!0}if(o==="list")return sr(),!0;if(ul(o)){let r=tt(),i=et();console.log(`${a.green}Switched to ${i}:${r.id} (${r.name})${a.reset}`)}else console.log(`${a.red}Unknown model: ${o}${a.reset}`),console.log(`${a.gray}Use /providers to see available models${a.reset}`);return!0}case"/providers":return sr(),!0;case"/fallback":{let o=n.join(" ").trim();if(!o){let i=kg();return i.length===0?(console.log(`${a.dim}No fallback chain configured${a.reset}`),console.log(`${a.dim}Use /fallback anthropic,openai,local to set${a.reset}`)):console.log(`${a.bold}${a.cyan}Fallback chain:${a.reset} ${i.join(" \u2192 ")}`),!0}let r=o.split(",").map(i=>i.trim()).filter(Boolean);return _g(r),console.log(`${a.green}Fallback chain: ${r.join(" \u2192 ")}${a.reset}`),!0}case"/tokens":{let{getConversationMessages:o}=ce(),{getUsage:r}=Re(),{TOOL_DEFINITIONS:i}=We(),c=o(),l=r(c,i),u=tt(),d=et();console.log(`
|
|
708
712
|
${a.bold}${a.cyan}Token Usage:${a.reset}`),console.log(` ${a.dim}Model:${a.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${a.dim}Used:${a.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f=yl(l.percentage);return console.log(` ${f}`),console.log(`
|
|
709
|
-
${a.dim}Breakdown:${a.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:r}=
|
|
713
|
+
${a.dim}Breakdown:${a.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:r}=vt();return n.join(" ").trim()==="reset"?(r(),console.log(`${a.green}Cost tracking reset${a.reset}`),!0):(console.log(`
|
|
710
714
|
${o()}
|
|
711
|
-
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=
|
|
712
|
-
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let y of p){let $=r(y.provider),x=h[y.provider];if(x!==void 0){g=!0;let O=Math.min(100,Math.round($/x*100)),k=10,v=Math.round(O/100*k),
|
|
715
|
+
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=vt(),d=n[0];if(!d){let h=o(),p=or();console.log(`
|
|
716
|
+
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let y of p){let $=r(y.provider),x=h[y.provider];if(x!==void 0){g=!0;let O=Math.min(100,Math.round($/x*100)),k=10,v=Math.round(O/100*k),T=k-v,C=`${O>=100?a.red:O>=80?a.yellow:a.green}${"\u2588".repeat(v)}${a.dim}${"\u2591".repeat(T)}${a.reset}`;console.log(` ${a.bold}${y.provider}:${a.reset} $${$.toFixed(2)} / $${x.toFixed(2)} (${O}%) ${C}`)}else y.provider==="ollama"||y.provider==="local"?console.log(` ${a.bold}${y.provider}:${a.reset} ${a.dim}free (no limit)${a.reset}`):$>0&&console.log(` ${a.bold}${y.provider}:${a.reset} $${$.toFixed(2)} ${a.dim}(no limit)${a.reset}`)}return g||console.log(` ${a.dim}No limits set. Use /budget <provider> <amount> to set one.${a.reset}`),console.log(),!0}let f=n[1];if(!f){let h=i(d);return h.limit!==null?console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} ${a.dim}(no limit)${a.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return c(d),l(),console.log(`${a.green}Removed cost limit for ${d}${a.reset}`),!0;let m=parseFloat(f);return isNaN(m)||m<=0?(console.log(`${a.red}Invalid amount: ${f}. Use a positive number or 'off'.${a.reset}`),!0):(u(d,m),l(),console.log(`${a.green}Set ${d} budget limit: $${m.toFixed(2)}${a.reset}`),!0)}case"/clear":{let{clearConversation:o,getConversationMessages:r}=ce(),{clearHistory:i}=Et(),c=r();if(c.filter(u=>u.role==="user").length>=4){process.stdout.write(`${a.dim}Reflecting on session...${a.reset} `);let{learnFromSession:u}=Zo();u(c).then(d=>{if(!d.skipped&&!d.error&&(d.applied.length>0||d.nexAdded.length>0)){let f=d.applied.length+d.nexAdded.length;process.stdout.write(`${a.green}${f} learning(s) saved${a.reset}
|
|
713
717
|
`)}else process.stdout.write(`${a.dim}nothing new${a.reset}
|
|
714
718
|
`)}).catch(()=>process.stdout.write(`
|
|
715
|
-
`))}return o(),i(),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/context":return await dl(
|
|
716
|
-
${a.bold}${a.cyan}Sessions:${a.reset}`);for(let i of r){let c=i.updatedAt?new Date(i.updatedAt).toLocaleString():"?",l=i.name==="_autosave"?` ${a.dim}(auto)${a.reset}`:"";console.log(` ${a.cyan}${i.name}${a.reset}${l} \u2014 ${i.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=
|
|
717
|
-
${a.bold}${a.cyan}Memory:${a.reset}`);for(let i of r)console.log(` ${a.cyan}${i.key}${a.reset} = ${i.value}`);return console.log(),!0}case"/brain":{let{listDocuments:o,readDocument:r,writeDocument:i,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=
|
|
719
|
+
`))}return o(),i(),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/context":return await dl($s),!0;case"/autoconfirm":{let o=!fl();return Cg(o),console.log(`${a.green}Auto-confirm: ${o?"ON":"OFF"}${a.reset}`),o&&console.log(`${a.yellow} \u26A0 File changes will be applied without confirmation${a.reset}`),!0}case"/save":{let{saveSession:o}=dt(),{getConversationMessages:r}=ce(),i=n.join(" ").trim()||`session-${Date.now()}`,c=r();if(c.length===0)return console.log(`${a.yellow}No conversation to save${a.reset}`),!0;let l=tt(),u=et();return o(i,c,{model:l.id,provider:u}),console.log(`${a.green}Session saved: ${i} (${c.length} messages)${a.reset}`),!0}case"/load":{let{loadSession:o}=dt(),{setConversationMessages:r}=ce(),i=n.join(" ").trim();if(!i)return console.log(`${a.red}Usage: /load <name>${a.reset}`),!0;let c=o(i);return c?(r(c.messages),console.log(`${a.green}Loaded session: ${c.name} (${c.messageCount} messages)${a.reset}`),!0):(console.log(`${a.red}Session not found: ${i}${a.reset}`),!0)}case"/sessions":{let{listSessions:o}=dt(),r=o();if(r.length===0)return console.log(`${a.dim}No saved sessions${a.reset}`),!0;console.log(`
|
|
720
|
+
${a.bold}${a.cyan}Sessions:${a.reset}`);for(let i of r){let c=i.updatedAt?new Date(i.updatedAt).toLocaleString():"?",l=i.name==="_autosave"?` ${a.dim}(auto)${a.reset}`:"";console.log(` ${a.cyan}${i.name}${a.reset}${l} \u2014 ${i.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=dt(),{setConversationMessages:r}=ce(),i=o();return i?(r(i.messages),console.log(`${a.green}Resumed: ${i.name} (${i.messageCount} messages)${a.reset}`),!0):(console.log(`${a.yellow}No session to resume${a.reset}`),!0)}case"/remember":{let{remember:o}=Ze(),r=n.join(" ").trim();if(!r)return console.log(`${a.red}Usage: /remember <key>=<value> or /remember <text>${a.reset}`),!0;let i=r.indexOf("="),c,l;return i>0?(c=r.substring(0,i).trim(),l=r.substring(i+1).trim()):(c=r.substring(0,40).replace(/\s+/g,"-"),l=r),o(c,l),console.log(`${a.green}Remembered: ${c}${a.reset}`),!0}case"/forget":{let{forget:o}=Ze(),r=n.join(" ").trim();return r?(o(r)?console.log(`${a.green}Forgotten: ${r}${a.reset}`):console.log(`${a.red}Memory not found: ${r}${a.reset}`),!0):(console.log(`${a.red}Usage: /forget <key>${a.reset}`),!0)}case"/memory":{let{listMemories:o}=Ze(),r=o();if(r.length===0)return console.log(`${a.dim}No memories saved${a.reset}`),!0;console.log(`
|
|
721
|
+
${a.bold}${a.cyan}Memory:${a.reset}`);for(let i of r)console.log(` ${a.cyan}${i.key}${a.reset} = ${i.value}`);return console.log(),!0}case"/brain":{let{listDocuments:o,readDocument:r,writeDocument:i,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=rn(),m=n[0],h=n.slice(1).join(" ").trim();switch(m){case"add":{if(!h)return console.log(`${a.red}Usage: /brain add <name> [content]${a.reset}`),console.log(`${a.dim} /brain add api-notes \u2014 creates empty file${a.reset}`),console.log(`${a.dim} /brain add api-notes This is content \u2014 writes directly${a.reset}`),!0;let p=h.indexOf(" ");if(p<0){i(h,`# ${h}
|
|
718
722
|
|
|
719
723
|
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${a.green}Created .nex/brain/${h}.md${a.reset}`),console.log(`${a.dim}Edit it directly at: ${g}${a.reset}`)}else{let g=h.substring(0,p),y=h.substring(p+1);i(g,y),console.log(`${a.green}Added to brain: ${g}${a.reset}`)}return!0}case"list":{let p=o();if(p.length===0)return console.log(`${a.dim}No brain documents yet. Use /brain add <name> to create one.${a.reset}`),!0;console.log(`
|
|
720
724
|
${a.bold}${a.cyan}Brain Documents:${a.reset}`);let g=Math.max(8,...p.map($=>$.name.length)),y=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd(y)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat(y)}${"-".repeat(7)} --------`);for(let $ of p){let{frontmatter:x}=r($.name),O=Array.isArray(x.tags)?x.tags.join(", "):"",k=$.size<1024?`${$.size}B`:`${($.size/1024).toFixed(1)}K`,v=$.modified.toLocaleDateString();console.log(` ${a.cyan}${$.name.padEnd(g+2)}${a.reset}${a.dim}${O.substring(0,y-1).padEnd(y)}${k.padStart(7)} ${v}${a.reset}`)}return console.log(),!0}case"search":{if(!h)return console.log(`${a.red}Usage: /brain search <query>${a.reset}`),!0;let p=await f(h,{topK:5});if(p.length===0)return console.log(`${a.dim}No matching brain documents for: ${h}${a.reset}`),!0;console.log(`
|
|
@@ -730,21 +734,21 @@ ${a.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \
|
|
|
730
734
|
`);else{console.log(`
|
|
731
735
|
${a.bold}${a.cyan}Brain: ${p.length} document(s)${a.reset}`);for(let g of p){let{frontmatter:y}=r(g.name),$=Array.isArray(y.tags)?` [${y.tags.join(", ")}]`:"";console.log(` ${a.cyan}${g.name}${a.reset}${a.dim}${$}${a.reset}`)}console.log(`
|
|
732
736
|
${a.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${a.reset}
|
|
733
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=
|
|
737
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=Zo(),{getConversationMessages:i}=ce(),c=i(),l=c.filter(u=>u.role==="user").length;if(l<4)return console.log(`${a.yellow}Session too short to learn from (need 4+ user messages, have ${l})${a.reset}`),!0;console.log(`${a.dim}Analyzing session for learnings...${a.reset}`);try{let[u,d]=await Promise.all([o(c),r(c)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${a.dim}Session too short${a.reset}`),!0;u.error&&console.log(`${a.red}Reflection error: ${u.error}${a.reset}`),console.log(""),u.summary&&(console.log(`${a.bold}Session:${a.reset} ${a.dim}${u.summary}${a.reset}`),console.log(""));let f=u.applied&&u.applied.length>0,m=u.nexAdded&&u.nexAdded.length>0,h=d.written&&d.written.length>0;if(!f&&!m&&!h)console.log(`${a.dim}No new learnings extracted from this session${a.reset}`);else{if(f){console.log(`${a.bold}${a.cyan}Memory updates:${a.reset}`);for(let{key:p,value:g,action:y}of u.applied){let $=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${$} ${a.bold}${p}${a.reset} = ${g}`)}}if(m){console.log(`${a.bold}${a.cyan}Added to NEX.md:${a.reset}`);for(let p of u.nexAdded)console.log(` ${a.green}+${a.reset} ${p}`)}if(h){console.log(`${a.bold}${a.cyan}Brain documents:${a.reset}`);for(let{name:p,reason:g,action:y}of d.written){let $=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${$} ${a.bold}${p}.md${a.reset}${g?a.dim+" \u2014 "+g+a.reset:""}`)}}}console.log("")}catch(u){console.log(`${a.red}Learn failed: ${u.message}${a.reset}`)}return!0}case"/optimize":{let{getConversationMessages:o}=ce(),{getUsage:r}=Re(),{TOOL_DEFINITIONS:i}=We(),{listMemories:c}=Ze(),l=o(),u=r(l,i),d=tt(),f=et(),m=c();console.log(`
|
|
734
738
|
${a.bold}${a.cyan}Optimization Report${a.reset}
|
|
735
739
|
`);let h=u.percentage>80?a.red:u.percentage>50?a.yellow:a.green;if(console.log(`${a.bold}Context Window:${a.reset} ${h}${u.percentage}%${a.reset} used (${u.used.toLocaleString()} / ${u.limit.toLocaleString()} tokens)`),u.percentage>75?console.log(` ${a.yellow}\u2192 Tip: Use /clear to free context (auto-learns first)${a.reset}`):u.percentage>50?console.log(` ${a.dim}\u2192 Context is filling up, consider /clear soon${a.reset}`):console.log(` ${a.green}\u2192 Context healthy${a.reset}`),console.log(`
|
|
736
|
-
${a.bold}Memory:${a.reset} ${m.length} entries`),m.length===0)console.log(` ${a.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${a.reset}`);else{let O=[...m].sort((
|
|
740
|
+
${a.bold}Memory:${a.reset} ${m.length} entries`),m.length===0)console.log(` ${a.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${a.reset}`);else{let O=[...m].sort((T,S)=>new Date(S.updatedAt)-new Date(T.updatedAt))[0],k=O?Math.round((Date.now()-new Date(O.updatedAt))/6e4):null,v=k!==null?k<60?`${k}m ago`:`${Math.round(k/60)}h ago`:"?";console.log(` ${a.dim}Latest update: ${v}${a.reset}`),m.length>30&&console.log(` ${a.yellow}\u2192 Many memories (${m.length}) \u2014 consider pruning with /forget${a.reset}`)}console.log(`
|
|
737
741
|
${a.bold}Active Model:${a.reset} ${f}:${d.id}`);let p=d.contextWindow||d.maxTokens||0;p>0&&p<32e3&&l.length>10?console.log(` ${a.yellow}\u2192 Small context window (${(p/1e3).toFixed(0)}k). Consider /model for larger context${a.reset}`):p>=128e3&&console.log(` ${a.green}\u2192 Large context window (${(p/1e3).toFixed(0)}k) \u2014 good for long sessions${a.reset}`);let g=l.filter(x=>x.role==="user").length;console.log(`
|
|
738
742
|
${a.bold}Session:${a.reset} ${g} turns, ${l.length} messages total`),g>=4&&g%10===0&&console.log(` ${a.cyan}\u2192 Good time to /learn and capture session insights${a.reset}`);let y=[],$=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync($)||y.push("Create NEX.md in project root to give nex-code project-specific instructions"),y.length>0){console.log(`
|
|
739
|
-
${a.bold}Quick Wins:${a.reset}`);for(let x of y)console.log(` ${a.cyan}\u2192${a.reset} ${x}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:r,startExecution:i,setPlanMode:c,getPlanContent:l,formatPlan:u}=
|
|
743
|
+
${a.bold}Quick Wins:${a.reset}`);for(let x of y)console.log(` ${a.cyan}\u2192${a.reset} ${x}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:r,startExecution:i,setPlanMode:c,getPlanContent:l,formatPlan:u}=Mt(),{invalidateSystemPromptCache:d}=ce(),f=n.join(" ").trim();if(f==="status"){let m=o();return console.log(u(m)),!0}if(f==="approve"){if(r()){i(),c(!1),d();let m=!!l();console.log(`${a.green}${a.bold}Plan approved!${a.reset} ${m?"Executing the planned steps...":"Starting execution..."}`),console.log(`${a.dim}Plan mode disabled \u2014 all tools now available.${a.reset}`)}else console.log(`${a.red}No plan to approve. Enter plan mode first with /plan${a.reset}`);return!0}return c(!0),d(),console.log(`
|
|
740
744
|
${a.cyan}${a.bold}\u250C\u2500 PLAN MODE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510${a.reset}
|
|
741
745
|
${a.cyan}${a.bold}\u2502${a.reset} Analysis only \u2014 no file changes until approved ${a.cyan}${a.bold}\u2502${a.reset}
|
|
742
746
|
${a.cyan}${a.bold}\u2502${a.reset} ${a.dim}Read-only tools only \xB7 /plan approve to execute${a.reset} ${a.cyan}${a.bold}\u2502${a.reset}
|
|
743
|
-
${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),f&&console.log(`${a.dim}Task: ${f}${a.reset}`),!0}case"/plans":{let{listPlans:o}=
|
|
744
|
-
${a.bold}${a.cyan}Plans:${a.reset}`);for(let i of r){let c=i.status==="completed"?`${a.green}\u2713`:i.status==="executing"?`${a.blue}\u2192`:`${a.dim}\u25CB`;console.log(` ${c} ${a.reset}${a.bold}${i.name}${a.reset} \u2014 ${i.task||"?"} (${i.steps} steps, ${i.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:o,setAutonomyLevel:r,AUTONOMY_LEVELS:i}=
|
|
747
|
+
${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),f&&console.log(`${a.dim}Task: ${f}${a.reset}`),!0}case"/plans":{let{listPlans:o}=Mt(),r=o();if(r.length===0)return console.log(`${a.dim}No saved plans${a.reset}`),!0;console.log(`
|
|
748
|
+
${a.bold}${a.cyan}Plans:${a.reset}`);for(let i of r){let c=i.status==="completed"?`${a.green}\u2713`:i.status==="executing"?`${a.blue}\u2192`:`${a.dim}\u25CB`;console.log(` ${c} ${a.reset}${a.bold}${i.name}${a.reset} \u2014 ${i.task||"?"} (${i.steps} steps, ${i.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:o,setAutonomyLevel:r,AUTONOMY_LEVELS:i}=Mt(),c=n.join(" ").trim();return c?(r(c)?console.log(`${a.green}Autonomy: ${c}${a.reset}`):console.log(`${a.red}Unknown level: ${c}. Use: ${i.join(", ")}${a.reset}`),!0):(console.log(`${a.bold}${a.cyan}Autonomy:${a.reset} ${o()}`),console.log(`${a.dim}Levels: ${i.join(", ")}${a.reset}`),!0)}case"/permissions":{let{listPermissions:o}=fn(),r=o();console.log(`
|
|
745
749
|
${a.bold}${a.cyan}Tool Permissions:${a.reset}`);for(let i of r){let c=i.mode==="allow"?`${a.green}\u2713`:i.mode==="deny"?`${a.red}\u2717`:`${a.yellow}?`;console.log(` ${c} ${a.reset}${a.bold}${i.tool}${a.reset} ${a.dim}(${i.mode})${a.reset}`)}return console.log(`
|
|
746
750
|
${a.dim}Use /allow <tool> or /deny <tool> to change${a.reset}
|
|
747
|
-
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=
|
|
751
|
+
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=fn(),i=n.join(" ").trim();return i?(o(i,"allow"),r(),console.log(`${a.green}${i}: allow${a.reset}`),!0):(console.log(`${a.red}Usage: /allow <tool>${a.reset}`),!0)}case"/deny":{let{setPermission:o,savePermissions:r}=fn(),i=n.join(" ").trim();return i?(o(i,"deny"),r(),console.log(`${a.red}${i}: deny${a.reset}`),!0):(console.log(`${a.red}Usage: /deny <tool>${a.reset}`),!0)}case"/commit":{let{isGitRepo:o,commit:r,analyzeDiff:i,formatDiffSummary:c}=ct(),{confirm:l}=Me();if(!o())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let u=n.join(" ").trim();if(u){let p=await r(u);return console.log(p?`${a.green}Committed: ${p} \u2014 ${u}${a.reset}`:`${a.red}Commit failed${a.reset}`),!0}if(!i())return console.log(`${a.yellow}No changes to commit${a.reset}`),!0;let f=await c();if(console.log(f),!await l(" Commit changes?"))return!0;let h=await r("nex-code update");return h&&console.log(`${a.green} \u2713 Committed: ${h}${a.reset}`),!0}case"/diff":{let{isGitRepo:o,formatDiffSummary:r}=ct();return o()?(console.log(r()),!0):(console.log(`${a.red}Not a git repository${a.reset}`),!0)}case"/review":{let{isGitRepo:o,getDiff:r}=ct(),{processInput:i}=ce(),c=n.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),f=`## Review Protocol
|
|
748
752
|
|
|
749
753
|
**Phase 1 \u2014 Broad Scan:** Read the target code and identify all issues at a high level.
|
|
750
754
|
|
|
@@ -787,16 +791,16 @@ ${f}
|
|
|
787
791
|
|
|
788
792
|
\`\`\`diff
|
|
789
793
|
${g.substring(0,2e4)}
|
|
790
|
-
\`\`\``}return await i(m),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:i}=
|
|
794
|
+
\`\`\``}return await i(m),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:i}=ct();if(!o())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let c=n.join(" ").trim();if(!c){let u=r();return console.log(`${a.bold}${a.cyan}Branch:${a.reset} ${u||"(detached)"}`),!0}let l=i(c);return console.log(l?`${a.green}Created and switched to: ${l}${a.reset}`:`${a.red}Failed to create branch${a.reset}`),!0}case"/mcp":{let{listServers:o,connectAll:r,disconnectAll:i}=qn(),c=n.join(" ").trim();if(c==="connect")return console.log(`${a.dim}Connecting MCP servers...${a.reset}`),r().then(u=>{for(let d of u)d.error?console.log(` ${a.red}\u2717${a.reset} ${d.name}: ${d.error}`):console.log(` ${a.green}\u2713${a.reset} ${d.name}: ${d.tools} tools`);u.length===0&&console.log(`${a.dim}No MCP servers configured in .nex/config.json${a.reset}`)}).catch(u=>{console.log(`${a.red}MCP connection error: ${u.message}${a.reset}`)}),!0;if(c==="disconnect")return i(),console.log(`${a.green}All MCP servers disconnected${a.reset}`),!0;let l=o();if(l.length===0)return console.log(`${a.dim}No MCP servers configured${a.reset}`),console.log(`${a.dim}Add servers to .nex/config.json under "mcpServers"${a.reset}`),!0;console.log(`
|
|
791
795
|
${a.bold}${a.cyan}MCP Servers:${a.reset}`);for(let u of l){let d=u.connected?`${a.green}\u2713 connected${a.reset}`:`${a.dim}\u25CB disconnected${a.reset}`;console.log(` ${d} ${a.bold}${u.name}${a.reset} (${u.command}) \u2014 ${u.toolCount} tools`)}return console.log(`
|
|
792
796
|
${a.dim}Use /mcp connect to connect all servers${a.reset}
|
|
793
|
-
`),!0}case"/hooks":{let{listHooks:o}=
|
|
794
|
-
${a.bold}${a.cyan}Hooks:${a.reset}`);for(let i of r){console.log(` ${a.cyan}${i.event}${a.reset}`);for(let c of i.commands)console.log(` ${a.dim}\u2192 ${c}${a.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:o,enableSkill:r,disableSkill:i}=
|
|
797
|
+
`),!0}case"/hooks":{let{listHooks:o}=Po(),r=o();if(r.length===0)return console.log(`${a.dim}No hooks configured${a.reset}`),console.log(`${a.dim}Add hooks to .nex/config.json or .nex/hooks/${a.reset}`),!0;console.log(`
|
|
798
|
+
${a.bold}${a.cyan}Hooks:${a.reset}`);for(let i of r){console.log(` ${a.cyan}${i.event}${a.reset}`);for(let c of i.commands)console.log(` ${a.dim}\u2192 ${c}${a.reset}`)}return console.log(),!0}case"/skills":{let{listSkills:o,enableSkill:r,disableSkill:i}=Kt(),c=n.join(" ").trim();if(c.startsWith("enable ")){let u=c.substring(7).trim();return r(u)?console.log(`${a.green}Skill enabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}if(c.startsWith("disable ")){let u=c.substring(8).trim();return i(u)?console.log(`${a.yellow}Skill disabled: ${u}${a.reset}`):console.log(`${a.red}Skill not found: ${u}${a.reset}`),!0}let l=o();if(l.length===0)return console.log(`${a.dim}No skills loaded${a.reset}`),console.log(`${a.dim}Add .md or .js files to .nex/skills/${a.reset}`),!0;console.log(`
|
|
795
799
|
${a.bold}${a.cyan}Skills:${a.reset}`);for(let u of l){let d=u.enabled?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,f=u.type==="prompt"?`${a.dim}(prompt)${a.reset}`:`${a.dim}(script)${a.reset}`,m=[];u.commands>0&&m.push(`${u.commands} cmd`),u.tools>0&&m.push(`${u.tools} tools`);let h=m.length>0?` \u2014 ${m.join(", ")}`:"";console.log(` ${d} ${a.bold}${u.name}${a.reset} ${f}${h}`)}return console.log(`
|
|
796
800
|
${a.dim}Use /skills enable <name> or /skills disable <name>${a.reset}
|
|
797
|
-
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=
|
|
801
|
+
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=Kn();return n.join(" ").trim()==="clear"?(r(),console.log(`${a.green}Tasks cleared${a.reset}`),!0):(console.log(`
|
|
798
802
|
`+o()+`
|
|
799
|
-
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=
|
|
803
|
+
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=Et(),i=o();if(!i)return console.log(`${a.yellow}Nothing to undo${a.reset}`),!0;i.wasCreated?console.log(`${a.green}Undone: deleted ${i.filePath} (was created by ${i.tool})${a.reset}`):console.log(`${a.green}Undone: restored ${i.filePath} (${i.tool})${a.reset}`);let c=r();return c>0&&console.log(`${a.dim}${c} more change(s) to undo${a.reset}`),!0}case"/redo":{let{redo:o,getRedoCount:r}=Et(),i=o();if(!i)return console.log(`${a.yellow}Nothing to redo${a.reset}`),!0;console.log(`${a.green}Redone: ${i.filePath} (${i.tool})${a.reset}`);let c=r();return c>0&&console.log(`${a.dim}${c} more change(s) to redo${a.reset}`),!0}case"/history":{let{getHistory:o,getUndoCount:r,getRedoCount:i}=Et(),c=o(20);if(c.length===0)return console.log(`${a.dim}No file changes in this session${a.reset}`),!0;console.log(`
|
|
800
804
|
${a.bold}File Change History${a.reset}
|
|
801
805
|
`);for(let l of c){let u=new Date(l.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${a.dim}${u}${a.reset} ${a.yellow}${l.tool}${a.reset} ${l.filePath}`)}return console.log(`
|
|
802
806
|
${a.dim}${r()} undo / ${i()} redo available${a.reset}
|
|
@@ -808,49 +812,45 @@ ${a.bold}${a.cyan}Kubernetes Overview${a.reset}${l?a.dim+" (remote: "+l+")"+a.re
|
|
|
808
812
|
`).filter(Boolean),h=m.filter($=>$.includes("Running")).length,p=m.filter($=>$.includes("Pending")).length,g=m.filter($=>$.includes("Failed")||$.includes("Error")||$.includes("CrashLoop")).length;console.log(`${a.bold}Pods: ${m.length} total ${a.green}${h} running${a.reset} ${a.yellow}${p} pending${a.reset} ${a.red}${g} unhealthy${a.reset}
|
|
809
813
|
`);let y=m.filter($=>!$.includes("Running")&&!$.includes("<none>"));if(y.length>0){console.log(`${a.bold}${a.red}Unhealthy Pods:${a.reset}`);for(let $ of y)console.log(` ${a.red}${$}${a.reset}`);console.log()}console.log(`${a.dim}Use k8s_pods / k8s_logs / k8s_exec tools for details${a.reset}`),console.log(`${a.dim}Or: /k8s user@host to query a remote cluster${a.reset}
|
|
810
814
|
`)}catch(f){console.log(`${a.dim}Could not list pods: ${f.message}${a.reset}
|
|
811
|
-
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:r,sshExec:i}=
|
|
815
|
+
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:r,sshExec:i}=Rt(),c=o(),l=Object.keys(c);if(l.length===0)return console.log(`
|
|
812
816
|
${a.dim}No servers configured. Create .nex/servers.json:${a.reset}`),console.log(`${a.dim} { "prod": { "host": "1.2.3.4", "user": "jarvis", "os": "almalinux9" } }${a.reset}
|
|
813
817
|
`),!0;if(n[0]==="ping"){let f=n[1]?[n[1]]:l;return console.log(`
|
|
814
|
-
${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(f.map(async m=>{if(!c[m]){console.log(` ${a.red}\u2717${a.reset} ${m} \u2014 unknown profile`);return}try{let h={...c[m],_name:m},{exitCode:p}=await i(h,"echo ok",{timeout:8e3});console.log(p===0?` ${a.green}\u2713${a.reset} ${m} (${h.user?h.user+"@":""}${h.host})`:` ${a.red}\u2717${a.reset} ${m} (${h.host}) \u2014 SSH failed (exit ${p})`)}catch(h){console.log(` ${a.red}\u2717${a.reset} ${m} \u2014 ${h.message}`)}})),console.log(""),!0}let{formatProfile:d}=
|
|
818
|
+
${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(f.map(async m=>{if(!c[m]){console.log(` ${a.red}\u2717${a.reset} ${m} \u2014 unknown profile`);return}try{let h={...c[m],_name:m},{exitCode:p}=await i(h,"echo ok",{timeout:8e3});console.log(p===0?` ${a.green}\u2713${a.reset} ${m} (${h.user?h.user+"@":""}${h.host})`:` ${a.red}\u2717${a.reset} ${m} (${h.host}) \u2014 SSH failed (exit ${p})`)}catch(h){console.log(` ${a.red}\u2717${a.reset} ${m} \u2014 ${h.message}`)}})),console.log(""),!0}let{formatProfile:d}=Rt();console.log(`
|
|
815
819
|
${a.bold}${a.cyan}Configured servers (${l.length}):${a.reset}`);for(let f of l)console.log(` ${a.green}${f}${a.reset} ${a.dim}${d(f,c[f])}${a.reset}`);return console.log(`
|
|
816
820
|
${a.dim}/servers ping \u2014 check SSH connectivity for all servers${a.reset}`),console.log(`${a.dim}/servers ping <name> \u2014 check a specific server${a.reset}
|
|
817
|
-
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=
|
|
821
|
+
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=Rt(),{exec:i}=require("child_process"),{promisify:c}=require("util"),l=c(i),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(`
|
|
818
822
|
${a.bold}${a.cyan}Docker Containers:${a.reset}`);for(let[m,h]of f){let p=m==="local"?`${a.dim}local${a.reset}`:`${a.cyan}${m}${a.reset}`;try{let g;if(m==="local"){let{stdout:y}=await l(u,{timeout:8e3});g=(y||"").trim()}else{let y=await r(h,u,{timeout:1e4});if(g=[y.stdout,y.stderr].filter(Boolean).join("").trim(),y.exitCode!==0){console.log(` ${p}: ${a.red}SSH error (${y.exitCode})${a.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${p}: ${a.dim}(no containers)${a.reset}`):(console.log(` ${p}:`),g.split(`
|
|
819
|
-
`).forEach(y=>console.log(` ${a.dim}${y}${a.reset}`)))}catch(g){console.log(` ${p}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=
|
|
823
|
+
`).forEach(y=>console.log(` ${a.dim}${y}${a.reset}`)))}catch(g){console.log(` ${p}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=eo(),r=o(),i=Object.keys(r),c=n[0];if(c&&i.includes(c)){let l=n.includes("--dry-run")||n.includes("-n"),u=r[c],{executeTool:d}=We();console.log(`
|
|
820
824
|
${a.bold}Running deploy: ${c}${l?" (dry run)":""}${a.reset}`);let f=await d("deploy",{...u,dry_run:l});return console.log(f),!0}if(i.length===0)return console.log(`
|
|
821
825
|
${a.dim}No deploy configs. Run /init to create .nex/deploy.json${a.reset}
|
|
822
826
|
`),!0;console.log(`
|
|
823
827
|
${a.bold}${a.cyan}Deploy configs (${i.length}):${a.reset}`);for(let[l,u]of Object.entries(r)){let d=u.local_path||"",f=`${u.server}:${u.remote_path}`,m=u.deploy_script?` ${a.dim}\u2192 ${u.deploy_script}${a.reset}`:"";console.log(` ${a.green}${l}${a.reset} ${a.dim}${d} \u2192 ${f}${a.reset}${m}`)}return console.log(`
|
|
824
828
|
${a.dim}/deploy <name> \u2014 run a named deploy${a.reset}`),console.log(`${a.dim}/deploy <name> --dry-run \u2014 preview without syncing${a.reset}
|
|
825
|
-
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:i}=ol();return i(e),n[0]==="deploy"?await r():await o(),!0}case"/exit":case"/quit":console.log(`
|
|
826
|
-
|
|
827
|
-
`).
|
|
828
|
-
`)}catch{}}function Ee(){let{isPlanMode:t,getAutonomyLevel:e}=Ot(),s=[];t()&&s.push("plan");let n=e();n!=="interactive"&&s.push(n);let o=Ze(),r=et(),i=o==="ollama"?r.id:`${o}:${r.id}`;return s.push(i),`${s.length>0?`${a.dim}[${s.join(" \xB7 ")}]${a.reset} `:""}${a.bold}${a.cyan}>${a.reset} `}var ar="\x1B[200~",cr="\x1B[201~";function Rg(t){return typeof t=="string"&&t.includes(ar)}function Ag(t){return typeof t=="string"&&t.includes(cr)}function gn(t){return typeof t!="string"?t:t.split(ar).join("").split(cr).join("")}async function Og(){if(!kg("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"),ul("local:llama3"),!0}catch{return!1}}async function Mg(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=ce();t(ml);let o=sr().some(A=>A.configured),r=(async()=>{vg();let A=et(),L=Ze();return{model:A,providerName:L}})(),i=(async()=>o?!0:await Og()?(console.log(`${a.green}\u2713 Local Ollama detected \u2014 using local models${a.reset}`),console.log(`${a.dim}Tip: Set API keys for cloud providers for more model options (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${a.reset}
|
|
829
|
+
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:i}=ol();return i(e),n[0]==="deploy"?await r():await o(),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:return Eg(t)||console.log(`${a.red}Unknown command: ${s}. Type /help${a.reset}`),!0}}var ir=1e3;function ar(){return je.join(process.cwd(),".nex","repl_history")}function bl(){try{let t=ar();if(nt.existsSync(t))return nt.readFileSync(t,"utf-8").split(`
|
|
830
|
+
`).filter(Boolean).slice(-ir)}catch{}return[]}function gs(t){try{let e=ar(),s=je.dirname(e);nt.existsSync(s)||nt.mkdirSync(s,{recursive:!0}),nt.appendFileSync(e,t+`
|
|
831
|
+
`)}catch{}}function Ee(){let{isPlanMode:t,getAutonomyLevel:e}=Mt(),s=[];t()&&s.push("plan");let n=e();n!=="interactive"&&s.push(n);let o=et(),r=tt(),i=o==="ollama"?r.id:`${o}:${r.id}`;return s.push(i),`${s.length>0?`${a.dim}[${s.join(" \xB7 ")}]${a.reset} `:""}${a.bold}${a.cyan}>${a.reset} `}var cr="\x1B[200~",lr="\x1B[201~";function Ag(t){return typeof t=="string"&&t.includes(cr)}function Og(t){return typeof t=="string"&&t.includes(lr)}function yn(t){return typeof t!="string"?t:t.split(cr).join("").split(lr).join("")}async function Ng(){if(!vg("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"),ul("local:llama3"),!0}catch{return!1}}async function Mg(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=ce();t(ml);let o=or().some(A=>A.configured),r=(async()=>{Sg();let A=tt(),L=et();return{model:A,providerName:L}})(),i=(async()=>o?!0:await Ng()?(console.log(`${a.green}\u2713 Local Ollama detected \u2014 using local models${a.reset}`),console.log(`${a.dim}Tip: Set API keys for cloud providers for more model options (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.)${a.reset}
|
|
829
832
|
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:A}=al();return await A()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,i,c]);!u&&!o&&(console.error(`
|
|
830
833
|
${a.red}\u2717 No provider configured and no local Ollama detected.${a.reset}
|
|
831
|
-
`),process.exit(1));let f=bl(),m=
|
|
832
|
-
`),await dl(
|
|
833
|
-
${a.dim}Bye!${a.reset}
|
|
834
|
-
`),process.exit(0)}process.on("SIGTERM",O),process.on("exit",()=>{ll()}),m.on("SIGINT",()=>{if(cl(),g){if(y++,y>=2){O();return}Ke&&Ke.abort();let{cancelPendingAskUser:A}=Ue();A(),console.log(`
|
|
834
|
+
`),process.exit(1));let f=bl(),m=bg.createInterface({input:process.stdin,output:process.stdout,prompt:Ee(),completer:gl,history:f,historySize:ir});Tg(m);let h=new Rg;h.activate(m);let p=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;xg(p,$s,{yolo:fl()}),d.hasNewVersion&&console.log(`${a.yellow}\u{1F4A1} New version available!${a.reset} Run ${a.cyan}npm update -g nex-code${a.reset} to upgrade from ${a.dim}${d.currentVersion}${a.reset} to ${a.green}${d.latestVersion}${a.reset}
|
|
835
|
+
`),await dl($s);let g=!1,y=0,$=!1,x=null;function O(){ll(),h.deactivate(),cl(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)}process.on("SIGTERM",O),process.on("exit",()=>{ll()}),m.on("SIGINT",()=>{if(cl(),g){if(y++,y>=2){O();return}Je&&Je.abort();let{cancelPendingAskUser:A}=We();A(),console.log(`
|
|
835
836
|
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),g=!1,m.setPrompt(Ee()),m.prompt();return}$?O():($=!0,process.stdout.write(`
|
|
836
837
|
${a.dim} (Press Ctrl+C again to exit)${a.reset}
|
|
837
|
-
`),m.setPrompt(Ee()),m.prompt(),x&&clearTimeout(x),x=setTimeout(()=>{$=!1,x=null},2e3))}),process.on("SIGINT",()=>{process.stdin.isTTY||O()});let k=!1,v=[],
|
|
838
|
-
`).replace(/\r/g,"").trim();if(v=[],k=!1,!A)return!0;C
|
|
839
|
-
`).length,z=se>1?`[Pasted content #${L} \u2014 ${se} lines]`:`[Pasted content #${L}]`,q=m.line||"",U=q&&!q.endsWith(" ")?" ":"",H=q+U+z;return m.setPrompt(Ee()),m.prompt(),m.line=H,m.cursor=H.length,m._refreshLine(),!0}function I(A){return A.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(L,se)=>S[Number(se)]||"")}function V(){
|
|
840
|
-
`)),F()}if(q){k=!0,v=[];let H=
|
|
841
|
-
`)),!0}if(U){let H=
|
|
842
|
-
`)),F()}if(k){let H=
|
|
843
|
-
`)),!0}return A.call(process.stdin,L,...se)}}let D=0;function ne(){if(D>0){let A="";for(let L=0;L<D;L++)A+="\x1B[1B\x1B[2K";A+=`\x1B[${D}A`,process.stdout.write(A),D=0}}function ie(A){let L=[...
|
|
844
|
-
\x1B[2K ${a.cyan}${
|
|
838
|
+
`),m.setPrompt(Ee()),m.prompt(),x&&clearTimeout(x),x=setTimeout(()=>{$=!1,x=null},2e3))}),process.on("SIGINT",()=>{process.stdin.isTTY||O()});let k=!1,v=[],T=0,S={},C=!1;function F(){let A=v.join(`
|
|
839
|
+
`).replace(/\r/g,"").trim();if(v=[],k=!1,!A)return!0;T++,C=!0;let L=T;S[L]=A;let se=A.split(`
|
|
840
|
+
`).length,z=se>1?`[Pasted content #${L} \u2014 ${se} lines]`:`[Pasted content #${L}]`,q=m.line||"",U=q&&!q.endsWith(" ")?" ":"",H=q+U+z;return m.setPrompt(Ee()),m.prompt(),m.line=H,m.cursor=H.length,m._refreshLine(),!0}function I(A){return A.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(L,se)=>S[Number(se)]||"")}function V(){T=0,S={},C=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let A=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(L,...se){if(L!=="data")return A.call(process.stdin,L,...se);let z=se[0];if(Buffer.isBuffer(z)&&(z=z.toString("utf8")),typeof z!="string")return A.call(process.stdin,L,...se);let q=z.includes(cr),U=z.includes(lr);if(q&&U){let H=yn(z);return H&&v.push(...H.split(`
|
|
841
|
+
`)),F()}if(q){k=!0,v=[];let H=yn(z);return H&&v.push(...H.split(`
|
|
842
|
+
`)),!0}if(U){let H=yn(z);return H&&v.push(...H.split(`
|
|
843
|
+
`)),F()}if(k){let H=yn(z);return H&&v.push(...H.split(`
|
|
844
|
+
`)),!0}return A.call(process.stdin,L,...se)}}let D=0;function ne(){if(D>0){let A="";for(let L=0;L<D;L++)A+="\x1B[1B\x1B[2K";A+=`\x1B[${D}A`,process.stdout.write(A),D=0}}function ie(A){let L=[...ys,...rr()].filter(ae=>ae.cmd.startsWith(A));if(!L.length||L.length===1&&L[0].cmd===A)return;let se=10,z=L.slice(0,se),q=Math.max(...z.map(ae=>ae.cmd.length)),U="";for(let{cmd:ae,desc:De}of z){let yt=ae.substring(0,A.length),me=ae.substring(A.length),ke=" ".repeat(Math.max(0,q-ae.length+2));U+=`
|
|
845
|
+
\x1B[2K ${a.cyan}${yt}${a.reset}${a.dim}${me}${ke}${De}${a.reset}`}D=z.length,L.length>se&&(U+=`
|
|
845
846
|
\x1B[2K ${a.dim}\u2026 +${L.length-se} more${a.reset}`,D++);let H=m._prompt.replace(/\x1b\[[0-9;]*m/g,"").length;U+=`\x1B[${D}A\x1B[${H+m.cursor+1}G`,process.stdout.write(U)}process.stdin.isTTY&&process.stdin.on("keypress",(A,L)=>{ne(),!(L&&(L.name==="tab"||L.name==="return"))&&setImmediate(()=>{m.line&&m.line.startsWith("/")&&ie(m.line)})});let ue=null,de=`${a.dim}...${a.reset} `;m.setPrompt(Ee()),m.prompt(),m.on("line",async A=>{if(ne(),Object.keys(S).length>0&&(A=I(A),V(),m.setPrompt(Ee())),g){let q=A.trim();if(q){let{injectMidRunNote:U}=ce();U(q),process.stdout.write(`${a.cyan} \u270E Wird im n\xE4chsten Schritt ber\xFCcksichtigt${a.reset}
|
|
846
847
|
`)}return}if(ue!==null){if(ue._mode==="triple"){if(A.trim()==='"""'){let q=ue.join(`
|
|
847
|
-
`).trim();if(ue=null,q){
|
|
848
|
+
`).trim();if(ue=null,q){gs(q.replace(/\n/g,"\\n")),g=!0,y=0,$=!1,x&&(clearTimeout(x),x=null),Je=new AbortController;try{await s(q)}catch(H){if(!Je?.signal?.aborted){let ae=H.message?.split(`
|
|
848
849
|
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${ae}${a.reset}`)}}g=!1;let U=se();U>0&&process.stdout.write(`${a.gray}[${U} messages] ${a.reset}`)}m.setPrompt(Ee()),m.prompt();return}ue.push(A),m.setPrompt(de),m.prompt();return}if(A.endsWith("\\"))ue.push(A.slice(0,-1));else{ue.push(A);let q=ue.join(`
|
|
849
|
-
`).trim();if(ue=null,q){
|
|
850
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${
|
|
851
|
-
`).forEach((ae,
|
|
852
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${U}${a.reset}`)}}g=!1;let{getConversationLength:se}=ce(),z=se();z>0&&process.stdout.write(`${a.gray}[${z} messages] ${a.reset}`),m.setPrompt(Ee()),m.prompt()}),m.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),console.log(`
|
|
853
|
-
${a.dim}Bye!${a.reset}`),process.exit(0)})}xl.exports={startREPL:Mg,getPrompt:Ee,loadHistory:bl,appendHistory:ps,getHistoryPath:ir,HISTORY_MAX:rr,showCommandList:pl,completer:gl,completeFilePath:hl,handleSlashCommand:wl,showProviders:nr,showHelp:$l,renderBar:yl,hasPasteStart:Rg,hasPasteEnd:Ag,stripPasteSequences:gn,getAbortSignal:ml}});var Sl=require("path");require("dotenv").config({path:Sl.join(__dirname,"..",".env")});require("dotenv").config();var te=process.argv.slice(2);(te.includes("--help")||te.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
850
|
+
`).trim();if(ue=null,q){gs(q.replace(/\n/g,"\\n")),g=!0,y=0,$=!1,x&&(clearTimeout(x),x=null),Je=new AbortController;try{await s(q)}catch(ae){if(!Je?.signal?.aborted){let De=ae.message?.split(`
|
|
851
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${De}${a.reset}`)}}let{getConversationLength:U}=ce();g=!1;let H=U();H>0&&process.stdout.write(`${a.gray}[${H} messages] ${a.reset}`)}m.setPrompt(Ee()),m.prompt();return}m.setPrompt(de),m.prompt();return}if(A.trim()==='"""'||A.trim().startsWith('"""')){let q=A.trim().substring(3);ue=q?[q]:[],ue._mode="triple",m.setPrompt(de),m.prompt();return}if(A.endsWith("\\")){ue=[A.slice(0,-1)],ue._mode="backslash",m.setPrompt(de),m.prompt();return}let L=A.trim();if(!L){m.setPrompt(Ee()),m.prompt();return}if(gs(L),L==="/"){pl(),m.setPrompt(Ee()),m.prompt();return}if(L.startsWith("/")){await wl(L,m),m.setPrompt(Ee()),m.prompt();return}{let q="\x1B[48;5;237m",U=process.stdout.columns||80;L.split(`
|
|
852
|
+
`).forEach((ae,De)=>{let yt=De===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",me=2+ae.length,ke=" ".repeat(Math.max(0,U-me));console.log(`${q}${yt} ${ae}${ke}\x1B[0m`)})}g=!0,y=0,$=!1,x&&(clearTimeout(x),x=null),Je=new AbortController;try{await s(L)}catch(q){if(!Je?.signal?.aborted){let U=q.message?.split(`
|
|
853
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${U}${a.reset}`)}}g=!1;let{getConversationLength:se}=ce(),z=se();z>0&&process.stdout.write(`${a.gray}[${z} messages] ${a.reset}`),m.setPrompt(Ee()),m.prompt()}),m.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}xl.exports={startREPL:Mg,getPrompt:Ee,loadHistory:bl,appendHistory:gs,getHistoryPath:ar,HISTORY_MAX:ir,showCommandList:pl,completer:gl,completeFilePath:hl,handleSlashCommand:wl,showProviders:sr,showHelp:$l,renderBar:yl,hasPasteStart:Ag,hasPasteEnd:Og,stripPasteSequences:yn,getAbortSignal:ml}});var Sl=require("path");require("dotenv").config({path:Sl.join(__dirname,"..",".env")});require("dotenv").config();var te=process.argv.slice(2);(te.includes("--help")||te.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
854
854
|
|
|
855
855
|
Options:
|
|
856
856
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -863,4 +863,4 @@ Options:
|
|
|
863
863
|
--json Output result as JSON (for CI parsing)
|
|
864
864
|
-h, --help Show this help
|
|
865
865
|
-v, --version Show version
|
|
866
|
-
`),process.exit(0));if(te.includes("-v")||te.includes("--version")){let t=
|
|
866
|
+
`),process.exit(0));if(te.includes("-v")||te.includes("--version")){let t=xn();console.log(t.version),process.exit(0)}var Pg=te.includes("--yolo")||te.includes("-yolo");if(Pg){let{setAutoConfirm:t}=Me();t(!0)}var ur=te.indexOf("--model");if(ur!==-1&&te[ur+1]){let{setActiveModel:t}=ge();t(te[ur+1])}var dr=te.indexOf("--max-turns");if(dr!==-1&&te[dr+1]){let t=parseInt(te[dr+1],10);if(t>0){let{setMaxIterations:e}=ce();e(t)}}else try{let t=require("fs"),e=Sl.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}=ce();o(n)}}}catch{}function fr(){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 kl(t){if(te.includes("--auto")){let{setAutoConfirm:o}=Me();o(!0)}if(!te.includes("--model")){let{setActiveModel:o}=ge(),r=process.env.HEADLESS_MODEL||"devstral-small-2:24b";o(r)}let{processInput:s,getConversationMessages:n}=ce();s(t).then(()=>{if(te.includes("--json")){let r=n().filter(i=>i.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 vl=te.indexOf("--prompt-file");if(vl!==-1){let t=te[vl+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{}fr(),kl(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)),fr(),kl(e)}else{fr();let{startREPL:e}=_l();e()}}
|