nex-code 0.3.29 → 0.3.31
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 +230 -230
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var N=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var
|
|
2
|
+
var N=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var wn=N((Lg,Sl)=>{Sl.exports={name:"nex-code",version:"0.3.31",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 wr=N((Ig,yr)=>{var M={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},hr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],gr=["\u273D","\u2726","\u2727","\u2726"],bs=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=hr[this.frame%hr.length],s="";if(this.startTime){let n=Math.floor((Date.now()-this.startTime)/1e3);if(n>=60){let o=Math.floor(n/60),r=n%60;s=` ${M.dim}${o}m ${String(r).padStart(2,"0")}s${M.reset}`}else n>=1&&(s=` ${M.dim}${n}s${M.reset}`)}process.stderr.write(`\x1B[2K\r${M.cyan}${e}${M.reset} ${M.dim}${this.text}${M.reset}${s}`),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),process.stderr.isTTY&&(process.stderr.write("\x1B[?25l"),this._render(),this.interval=setInterval(()=>this._render(),80))}update(e){this.text=e}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),process.stderr.isTTY&&process.stderr.write("\x1B[2K\r\x1B[?25h"),this.startTime=null}},$r=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],xs=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=$r[this.frame%$r.length],s=this._formatElapsed(),n=s?` ${M.dim}${s}${M.reset}`:"",o="";for(let r=0;r<this.labels.length;r++){let i,c;switch(this.statuses[r]){case"done":i=`${M.green}\u2713${M.reset}`,c=M.dim;break;case"error":i=`${M.red}\u2717${M.reset}`,c=M.dim;break;default:i=`${M.cyan}${e}${M.reset}`,c=""}let l=r===this.labels.length-1?n:"";o+=`\x1B[2K ${i} ${c}${this.labels[r]}${M.reset}${l}
|
|
3
3
|
`}this.lineCount>0&&(o+=`\x1B[${this.lineCount}A`),process.stderr.write(o),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
4
4
|
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${M.dim}${e}${M.reset}`:"",n="";for(let o=0;o<this.labels.length;o++){let r;switch(this.statuses[o]){case"done":r=`${M.green}\u2713${M.reset}`;break;case"error":r=`${M.red}\u2717${M.reset}`;break;default:r=`${M.yellow}\u25CB${M.reset}`}let i=o===this.labels.length-1?s:"";n+=`\x1B[2K ${r} ${M.dim}${this.labels[o]}${M.reset}${i}
|
|
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=
|
|
5
|
+
`}process.stderr.write(n)}},bn={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},xn={done:M.green,in_progress:M.cyan,pending:M.dim,failed:M.red},Je=null,_s=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=gr[this.frame%gr.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${M.dim}(${o})${M.reset}`:"",i=`\x1B[2K${M.cyan}${e}${M.reset} ${this.name}\u2026${r}
|
|
6
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=bn[l.status]||bn.pending,f=xn[l.status]||xn.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${M.dim}${u}${M.reset} ${f}${d}${M.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
8
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Je=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,Je===this&&(Je=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
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${M.green}\u2714${M.reset} ${this.name} ${M.dim}(${e} \xB7 ${r})${M.reset}
|
|
11
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=
|
|
12
|
-
`}process.stderr.write(i)}};function
|
|
11
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=bn[l.status]||bn.pending,f=xn[l.status]||xn.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${M.dim}${u}${M.reset} ${f}${d}${M.reset} ${M.dim}${m}${M.reset}
|
|
12
|
+
`}process.stderr.write(i)}};function El(t){Je=t}function Cl(){return Je}function Tl(){Je&&(Je.stop(),Je=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}yr.exports={C:M,Spinner:bs,MultiProgress:xs,TaskProgress:_s,setActiveTaskProgress:El,getActiveTaskProgress:Cl,cleanupTerminal:Tl}});var xr=N((qg,br)=>{var G={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},Rl={read_file:"Read file",write_file:"Write file",edit_file:"Edit file",patch_file:"Patch file",list_directory:"List directory",bash:"Run command",grep:"Search code",search_files:"Search files",glob:"Find files",web_fetch:"Fetch URL",web_search:"Web search",git_status:"Git status",git_diff:"Git diff",git_log:"Git log",git_commit:"Git commit",git_push:"Git push",git_pull:"Git pull",git_branch:"Git branch",git_stash:"Git stash",task_list:"Task list",spawn_agents:"Spawn agents",ask_user:"Ask user",switch_model:"Switch model",gh_run_list:"GH Actions",gh_run_view:"GH Actions",gh_workflow_trigger:"GH trigger",browser_open:"Browser open",browser_screenshot:"Screenshot",browser_click:"Browser click",browser_fill:"Browser fill",ssh_exec:"SSH exec",ssh_upload:"SSH upload",ssh_download:"SSH download",service_manage:"Service",service_logs:"Service logs",container_list:"Containers",container_logs:"Container logs",container_exec:"Container exec",brain_write:"Brain write",deploy:"Deploy"},Al={read_file:"Reading file",write_file:"Writing file",edit_file:"Editing file",patch_file:"Patching file",list_directory:"Listing directory",bash:"Running command",grep:"Searching code",search_files:"Searching files",glob:"Finding files",web_fetch:"Fetching content",web_search:"Searching the web",git_status:"Checking repository",git_diff:"Analyzing changes",git_log:"Reading git history",git_commit:"Creating commit",git_push:"Pushing changes",git_pull:"Pulling changes",git_branch:"Managing branches",git_stash:"Stashing changes",task_list:"Managing tasks",spawn_agents:"Delegating to agents",ask_user:"Awaiting input",switch_model:"Switching model",gh_run_list:"GitHub Actions",gh_run_view:"GitHub Actions",gh_workflow_trigger:"Triggering workflow",browser_open:"Opening browser",browser_screenshot:"Taking screenshot",browser_click:"Clicking element",browser_fill:"Filling form",ssh_exec:"Running on server",ssh_upload:"Uploading to server",ssh_download:"Downloading from server",service_manage:"Managing service",service_logs:"Reading service logs",container_list:"Listing containers",container_logs:"Reading container logs",container_exec:"Running in container",brain_write:"Saving to memory",deploy:"Deploying"};function Ol(t,e){let s=(t||[]).filter(r=>r&&r.canExecute!==!1);if(s.length===0)return`${G.cyan} \u25C6 Step ${e}${G.reset}`;let n=[...new Set(s.map(r=>Al[r.fnName]||r.fnName))],o;if(n.length===1&&s.length===1){o=n[0];let 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=Rl[t]||t.replace(/_/g," "),o=s?` ${G.dim}${s}${G.reset}`:"";return`${G.cyan} \u23FA${G.reset} ${G.bold}${n}${G.reset}${o}`}function Nl(t,e=8){let s=t.split(`
|
|
13
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
|
-
${G.gray} \u2026+${o} more lines${G.reset}`),c}function
|
|
15
|
+
${G.gray} \u2026+${o} more lines${G.reset}`),c}function Pl(t,e){switch(t){case"bash":case"ask_user":case"write_file":case"edit_file":case"patch_file":case"task_list":case"spawn_agents":return null;case"read_file":return`Reading: ${e.path||"file"}`;case"list_directory":return`Listing: ${e.path||"."}`;case"search_files":return`Searching: ${e.pattern||"..."}`;case"glob":return`Glob: ${e.pattern||"..."}`;case"grep":return`Grep: ${e.pattern||"..."}`;case"web_fetch":return`Fetching: ${(e.url||"").substring(0,60)}`;case"web_search":return`Searching web: ${(e.query||"").substring(0,50)}`;case"git_status":return"Git status...";case"git_diff":return`Git diff${e.file?`: ${e.file}`:""}...`;case"git_log":return`Git log${e.file?`: ${e.file}`:""}...`;case"gh_run_list":return`GitHub Actions: listing runs${e.workflow?` (${e.workflow})`:""}...`;case"gh_run_view":return`GitHub Actions: run ${e.run_id}...`;case"gh_workflow_trigger":return`GitHub Actions: trigger ${e.workflow}...`;case"browser_open":return`Browser: opening ${(e.url||"").substring(0,60)}...`;case"browser_screenshot":return`Browser: screenshot ${(e.url||"").substring(0,60)}...`;case"browser_click":return`Browser: clicking ${e.text||e.selector||"element"}...`;case"browser_fill":return`Browser: filling ${e.selector||"field"}...`;default:return`Running: ${t}`}}function Ll(t,e,s,n){let o=String(s||"");if(n){let i=o.split(`
|
|
16
16
|
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80),c=o.match(/\nHINT: (.+)/),l=c?`
|
|
17
17
|
${G.dim}${c[1].substring(0,100)}${G.reset}`:"";return` ${G.red}\u23BF ${i}${G.reset}${l}`}let r;switch(t){case"read_file":{let i=o.split(`
|
|
18
18
|
`).filter(Boolean),c=i.length,l=i[i.length-1],u=l?parseInt(l.match(/^(\d+):/)?.[1]||"0"):0;(e.line_start||e.line_end)&&u>c?r=`Read lines ${e.line_start||1}\u2013${u}`:r=`Read ${c} line${c!==1?"s":""}`;break}case"write_file":{let i=(e.content||"").split(`
|
|
@@ -25,110 +25,110 @@ ${G.gray} \u2026+${o} more lines${G.reset}`),c}function Nl(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}`}br.exports={C:G,formatToolCall:Ml,formatResult:Nl,getToolSpinnerText:Pl,formatToolSummary:Ll,formatSectionHeader:Ol}});var oe=N((jg,_r)=>{var wt={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"};function Il(t,e){return[...t].map(s=>s===" "?s:`\x1B[38;2;${e[0]};${e[1]};${e[2]}m${s}`).join("")+wt.reset}function ql(t,e){let s=(t.length-1)*e,n=Math.min(Math.floor(s),t.length-2),o=s-n;return[Math.round(t[n][0]+(t[n+1][0]-t[n][0])*o),Math.round(t[n][1]+(t[n+1][1]-t[n][1])*o),Math.round(t[n][2]+(t[n+1][2]-t[n][2])*o)]}function jl(t,e,s={}){let n=wt.bold,o=wt.dim,r=wt.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 Il(d,ql(c,m))}).join(`
|
|
29
|
+
`),u=s.yolo?` ${n}${wt.yellow}\u26A1 YOLO${r}`:"";console.log(`
|
|
30
30
|
${l}
|
|
31
|
-
${o}Agentic Coding CLI v${
|
|
31
|
+
${o}Agentic Coding CLI v${wn().version}${r}
|
|
32
32
|
${o}Model: ${t}${r} ${o}\xB7 /help${r}${u}
|
|
33
|
-
`)}var{Spinner:
|
|
34
|
-
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,c=await
|
|
35
|
-
`);
|
|
33
|
+
`)}var{Spinner:Dl,MultiProgress:Fl,TaskProgress:Ul,setActiveTaskProgress:Wl,getActiveTaskProgress:Bl,cleanupTerminal:Hl}=wr(),{formatToolCall:Gl,formatResult:zl,getToolSpinnerText:Kl,formatToolSummary:Jl,formatSectionHeader:Yl}=xr();_r.exports={C:wt,banner:jl,Spinner:Dl,MultiProgress:Fl,TaskProgress:Ul,setActiveTaskProgress:Wl,getActiveTaskProgress:Bl,cleanupTerminal:Hl,formatToolCall:Gl,formatResult:zl,getToolSpinnerText:Kl,formatToolSummary:Jl,formatSectionHeader:Yl}});var Me=N((Dg,Tr)=>{var Xl=require("readline"),{C:_n}=oe(),kr=[/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/],ks=[/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 vr(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)):ks.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:ks.some(c=>c.test(i))};return n.every(o)}var Ss=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],Sr=[/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/],Er=[...Ss,...Sr],Es=!1,vs=null;function Vl(t){Es=t}function Ql(){return Es}function Zl(t){vs=t}function eu(t){for(let e of kr)if(e.test(t))return e;return null}function tu(t){if(/ssh\s/.test(t)&&vr(t))return!1;for(let e of Er)if(e.test(t))return!0;return!1}function nu(t){for(let e of Ss)if(e.test(t))return!0;return!1}function su(t,e={}){if(Es)return Promise.resolve(!0);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?(Cr(e.toolName),n(!0)):n(i!=="n")};if(vs)vs.question(`${_n.yellow}${t} ${s}${_n.reset}`,o);else{let r=Xl.createInterface({input:process.stdin,output:process.stdout});r.question(`${_n.yellow}${t} ${s}${_n.reset}`,i=>{r.close(),o(i)})}})}var Cr=()=>{};function ou(t){Cr=t}Tr.exports={FORBIDDEN_PATTERNS:kr,SSH_SAFE_PATTERNS:ks,isSSHReadOnly:vr,DANGEROUS_BASH:Er,CRITICAL_BASH:Ss,NOTABLE_BASH:Sr,isForbidden:eu,isDangerous:tu,isCritical:nu,confirm:su,setAutoConfirm:Vl,getAutoConfirm:Ql,setReadlineInterface:Zl,setAllowAlwaysHandler:ou}});var bt=N((Fg,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 Mr=N((Ug,Or)=>{var kn=require("axios"),ru=require("http"),iu=require("https"),{BaseProvider:au}=bt(),vn=new ru.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Sn=new iu.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}},Ts=class extends au{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){kn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:vn,httpsAgent:Sn}).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 kn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:vn,httpsAgent:Sn})).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(`
|
|
34
|
+
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,c=await kn.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:vn,httpsAgent:Sn});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 kn.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:vn,httpsAgent:Sn})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.data?.error||u.message;throw new Error(`API Error: ${d}`)}return new Promise((u,d)=>{let f="",m=[],h="";n.signal&&n.signal.addEventListener("abort",()=>{l.data.destroy(),d(new DOMException("The operation was aborted","AbortError"))},{once:!0}),l.data.on("data",p=>{h+=p.toString();let g=h.split(`
|
|
35
|
+
`);h=g.pop()||"";for(let w of g){if(!w.trim())continue;let $;try{$=JSON.parse(w)}catch{continue}if($.message?.content&&(c($.message.content),f+=$.message.content),$.message?.tool_calls&&(m=m.concat($.message.tool_calls)),$.done){u({content:f,tool_calls:this._normalizeToolCalls(m)});return}}}),l.data.on("error",p=>{n.signal?.aborted||d(new Error(`Stream error: ${p.message}`))}),l.data.on("end",()=>{if(h.trim())try{let p=JSON.parse(h);p.message?.content&&(c(p.message.content),f+=p.message.content),p.message?.tool_calls&&(m=m.concat(p.message.tool_calls))}catch{}u({content:f,tool_calls:this._normalizeToolCalls(m)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`ollama-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};Or.exports={OllamaProvider:Ts,OLLAMA_MODELS:Ar}});var jr=N((Wg,qr)=>{var{callChat:cu}=ge(),{estimateTokens:Rs}=Re(),Nr=process.env.NEX_COMPACTION!=="false",Pr=6,Lr=500,lu=`Summarize this conversation history concisely. Focus on:
|
|
36
36
|
- What files were read, created, or modified
|
|
37
37
|
- Key decisions made and their rationale
|
|
38
38
|
- Current state of the task (what's done, what's pending)
|
|
39
39
|
- Any errors encountered and how they were resolved
|
|
40
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
41
|
-
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function
|
|
40
|
+
Be factual and brief. Use bullet points. Max 300 words.`;async function uu(t){if(!Nr||t.length<Pr)return null;let e=[{role:"system",content:lu},{role:"user",content:Ir(t)}];try{let n=((await cu(e,[],{temperature:0,maxTokens:Lr})).content||"").trim();if(!n)return null;let o=t.reduce((i,c)=>i+Rs(c.content||"")+(c.tool_calls?Rs(JSON.stringify(c.tool_calls)):0),0),r=Rs(n);return r>=o*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
41
|
+
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function 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
42
|
tools: ${o}`}return`[${s}] ${n}`}).join(`
|
|
43
43
|
|
|
44
|
-
`)}
|
|
45
|
-
`);if(o.length<=10){let
|
|
44
|
+
`)}qr.exports={compactMessages:uu,formatMessagesForSummary:Ir,COMPACTION_ENABLED:Nr,COMPACTION_MIN_MESSAGES:Pr,COMPACTION_SUMMARY_BUDGET:Lr}});var Re=N((Bg,Gr)=>{function Fr(){return ge().getActiveModel()}var du={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},Ft=new Map,Dr=1e3,As=new WeakMap,Ut=null;function fu(){if(Ut!==null)return Ut;try{let e=Fr()?.provider||"ollama";return Ut=du[e]||4,Ut}catch{return 4}}function mu(){Ut=null}function ot(t){if(!t)return 0;typeof t!="string"&&(t=JSON.stringify(t));let e=t.length<=80?t:`${t.length}:${t.substring(0,60)}:${t.substring(t.length-20)}`,s=Ft.get(e);if(s!==void 0)return s;let n=Math.ceil(t.length/fu());if(Ft.size>=Dr){let o=Dr>>1,r=Ft.keys();for(let i=0;i<o;i++)Ft.delete(r.next().value)}return Ft.set(e,n),n}function pu(t){if(As.has(t))return As.get(t);let e=JSON.stringify(t);return As.set(t,e),e}function xt(t){let s=4;if(t.content&&(s+=ot(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=ot(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=ot(o):o&&(s+=ot(JSON.stringify(o)))}return s}function Ae(t){let e=0;for(let s of t)e+=xt(s);return e}function hu(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+=xt(e[r]);return o}function En(t){return!t||t.length===0?0:ot(JSON.stringify(t))}function Cn(){return Fr()?.contextWindow||32768}function gu(t,e){let s=Ae(t),n=En(e),o=s+n,r=Cn(),i=r>0?o/r*100:0,c=0,l=0,u=0;for(let d of t){let f=xt(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,$u=200,yu=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
|
+
`);if(o.length<=10){let p=Math.floor(n*.6),g=Math.floor(n*.4),w=t.substring(0,p),$=t.substring(t.length-g);return w+`
|
|
46
46
|
...(${t.length} chars total)...
|
|
47
|
-
`+$}let r=Math.floor(o.length*.4),i=Math.floor(o.length*.4),c=[],l=0,u=Math.floor(n*.4);for(let
|
|
47
|
+
`+$}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
48
|
`)+`
|
|
49
|
-
...(${
|
|
49
|
+
...(${h} lines omitted, ${o.length} total)...
|
|
50
50
|
`+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
|
|
53
|
-
`),r=Math.floor(n*.6),i=Math.floor(n*.4),c="",l=0;for(let
|
|
54
|
-
`:"")+
|
|
55
|
-
`:"")+u;if(
|
|
51
|
+
`)}function Wt(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:yu,n=e==="aggressive"?50:e==="medium"?100:$u;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content: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)+`
|
|
52
|
+
...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(r=>({...r,function:{name:r.function.name,arguments:typeof r.function.arguments=="string"?r.function.arguments.substring(0,50):r.function.arguments}}))),o}return t}async function wu(t,e,s={}){let n=s.threshold??Ur,o=s.safetyMargin??Wr,r=s.keepRecent??Br,i=Cn(),c=En(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),w=t.slice(p,g),$=t.slice(g),x=w.filter(S=>!S._compacted);if(x.length>=6)try{let{compactMessages:S}=jr(),T=await S(x);if(T){let I=[...w.filter(ne=>ne._compacted),T.message],V=st(h,I,$),D=Ae(V);if(D+c<=l)return{messages:V,compressed:!0,compacted:!0,tokensRemoved:m-D};w=I}}catch(S){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",S.message)}let O=(f-l)/l,k=w.map(S=>Wt(S,"light")),v=st(h,k,$),C=Ae(v);if(C+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-C};if(k=w.map(S=>Wt(S,"medium")),v=st(h,k,$),C=Ae(v),C+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-C};if(k=w.map(S=>Wt(S,"aggressive")),v=st(h,k,$),C=Ae(v),C+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-C};for(;k.length>0&&C>u;){let S=k.shift();C-=xt(S)}return v=st(h,k,$),C=Ae(v),{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-C}}function st(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function bu(t,e){if(!t)return"";if(ot(t)<=e)return t;let n=e*4,o=t.split(`
|
|
53
|
+
`),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
|
+
`:"")+h,l++}let u="",d=0;for(let h=o.length-1;h>=l;h--){let p=o[h]+(u?`
|
|
55
|
+
`:"")+u;if(p.length>i)break;u=p,d++}let m=`
|
|
56
56
|
|
|
57
57
|
... (${o.length-l-d} lines omitted, ${o.length} total) ...
|
|
58
58
|
|
|
59
|
-
`;return c+m+u}var
|
|
60
|
-
`);g=$.pop()||"";for(let x of $){let O=x.trim();if(!O||!O.startsWith("data: "))continue;let k=O.slice(6);if(k==="[DONE]"){f({content:
|
|
61
|
-
|
|
62
|
-
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let 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
|
|
63
|
-
`);O=v.pop()||"";for(let C of v){let S=C.trim();if(S.startsWith("data: ")){let T=S.slice(6),F;try{F=JSON.parse(T)}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),w+=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":
|
|
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:
|
|
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=
|
|
67
|
-
`)}}function
|
|
68
|
-
`)}function
|
|
69
|
-
`),c}catch(c){throw o.stop(),c}}async function
|
|
59
|
+
`;return c+m+u}var xu=6;function _u(t,e){let s=Cn(),n=En(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-xu),u=t.slice(c,l),d=t.slice(l),f=u.map(p=>Wt(p,"aggressive")),m=st(i,f,d),h=Ae(m);for(;f.length>0&&h>o;){let p=f.shift();h-=xt(p)}return m=st(i,f,d),h=Ae(m),{messages:m,tokensRemoved:r-h}}Gr.exports={estimateTokens:ot,estimateMessageTokens:xt,estimateMessagesTokens:Ae,estimateDeltaTokens:hu,estimateToolsTokens:En,serializeMessage:pu,getContextWindow:Cn,getUsage:gu,compressMessage:Wt,compressToolResult:Hr,fitToContext:wu,forceCompress:_u,truncateFileContent:bu,invalidateTokenRatioCache:mu,COMPRESSION_THRESHOLD:Ur,SAFETY_MARGIN:Wr,KEEP_RECENT:Br}});var Yr=N((Gg,Jr)=>{var zr=require("axios"),{BaseProvider:ku}=bt(),{serializeMessage:Hg}=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}},Os=class extends ku{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",w=>{g+=w.toString();let $=g.split(`
|
|
60
|
+
`);g=$.pop()||"";for(let x of $){let O=x.trim();if(!O||!O.startsWith("data: "))continue;let 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 C=v.choices?.[0]?.delta;if(C&&(C.content&&(c(C.content),h+=C.content),C.tool_calls))for(let S of C.tool_calls){let T=S.index??0;p[T]||(p[T]={id:S.id||"",name:"",arguments:""}),S.id&&(p[T].id=S.id),S.function?.name&&(p[T].name+=S.function.name),S.function?.arguments&&(p[T].arguments+=S.function.arguments)}}}),d.data.on("error",w=>{n.signal?.aborted||m(new Error(`Stream error: ${w.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`openai-${Date.now()}`,function:{name:s.name,arguments:s.arguments}}))}};Jr.exports={OpenAIProvider:Os,OPENAI_MODELS:Kr}});var Zr=N((Kg,Qr)=>{var Xr=require("axios"),{BaseProvider:vu}=bt(),{serializeMessage:zg}=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}},Su="2023-06-01",Ms=class extends vu{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||Su}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s="",n=[];for(let o of e){if(o.role==="system"){s+=(s?`
|
|
61
|
+
|
|
62
|
+
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let r=this._formatSingleMessage(o,n);if(r){if(o.role!=="system"&&o.role!=="tool"&&this._messageStringCache.size<this._maxCacheSize){let 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 w="",$=[],x=-1,O="";n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",k=>{O+=k.toString();let v=O.split(`
|
|
63
|
+
`);O=v.pop()||"";for(let C of v){let S=C.trim();if(S.startsWith("data: ")){let T=S.slice(6),F;try{F=JSON.parse(T)}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),w+=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:w,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:w,tool_calls:this._buildToolCalls($)})})})}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}_buildToolCalls(e){return e.filter(s=>s.name).map(s=>{let n={};if(s.inputJson)try{n=JSON.parse(s.inputJson)}catch{n=s.inputJson}return{id:s.id||`anthropic-${Date.now()}`,function:{name:s.name,arguments:n}}})}};Qr.exports={AnthropicProvider:Ms,ANTHROPIC_MODELS:Vr}});var si=N((Yg,ni)=>{var ei=require("axios"),{BaseProvider:Eu}=bt(),{serializeMessage:Jg}=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}},Ns=class extends Eu{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",w=>{g+=w.toString();let $=g.split(`
|
|
64
|
+
`);g=$.pop()||"";for(let x of $){let O=x.trim();if(!O||!O.startsWith("data: "))continue;let 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 C=v.choices?.[0]?.delta;if(C&&(C.content&&(c(C.content),h+=C.content),C.tool_calls))for(let S of C.tool_calls){let T=S.index??0;p[T]||(p[T]={id:S.id||"",name:"",arguments:""}),S.id&&(p[T].id=S.id),S.function?.name&&(p[T].name+=S.function.name),S.function?.arguments&&(p[T].arguments+=S.function.arguments)}}}),d.data.on("error",w=>{n.signal?.aborted||m(new Error(`Stream error: ${w.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:s.name,arguments:s.arguments}}))}};ni.exports={GeminiProvider:Ns,GEMINI_MODELS:ti}});var ii=N((Xg,ri)=>{var Tn=require("axios"),{BaseProvider:Cu}=bt(),oi="http://localhost:11434",Ps=class extends Cu{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 Tn.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 Tn.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(`
|
|
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 Tn.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 Tn.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(`
|
|
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:Ps,DEFAULT_LOCAL_URL:oi}});var _t=N((Vg,mi)=>{var rt=require("fs"),Ls=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:{}},Rn=[],Ye={};function Tu(t,e,s,n){if(Rn.push({provider:t,model:e,input:s,output:n}),Ye[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
|
|
67
|
+
`)}}function Is(t,e){let s=ai[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function ci(t){let e=Is(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function li(){let t={};for(let r of Rn){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 Ru(){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(`
|
|
68
|
+
`)}function Au(t,e,s,n){let o=Is(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Ou(){Rn=[]}function Mu(t,e){Ye[t]=e}function Nu(t){delete Ye[t]}function Pu(){return{...Ye}}function ui(t){let e=0;for(let s of Rn)s.provider===t&&(e+=ci(s));return e}function di(t){let e=ui(t),s=Ye[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=Ls.join(process.cwd(),".nex","config.json");if(rt.existsSync(t))try{let e=JSON.parse(rt.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Ye={...e.costLimits})}catch{}}function Lu(){let t=Ls.join(process.cwd(),".nex"),e=Ls.join(t,"config.json"),s={};if(rt.existsSync(e))try{s=JSON.parse(rt.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Ye,rt.existsSync(t)||rt.mkdirSync(t,{recursive:!0}),rt.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function Iu(){Ye={}}fi();mi.exports={PRICING:ai,trackUsage:Tu,getSessionCosts:li,formatCosts:Ru,formatCostHint:Au,resetCosts:Ou,getPricing:Is,setCostLimit:Mu,removeCostLimit:Nu,getCostLimits:Pu,getProviderSpend:ui,checkBudget:di,loadCostLimits:fi,saveCostLimits:Lu,resetCostLimits:Iu}});var An=N((Qg,pi)=>{var Bt=ge(),qu={"kimi-k2.5":{id:"kimi-k2.5",name:"Kimi K2.5",max_tokens:16384},"qwen3-coder:480b":{id:"qwen3-coder:480b",name:"Qwen3 Coder 480B",max_tokens:16384}};function ju(){return Bt.getActiveModel()}function Du(t){return Bt.setActiveModel(t)}function Fu(){return Bt.getModelNames()}function Uu(t){if(!t)return null;if(typeof t=="object")return t;try{return JSON.parse(t)}catch{}try{let n=t.replace(/,\s*([}\]])/g,"$1").replace(/'/g,'"');return JSON.parse(n)}catch{}let e=t.match(/\{[\s\S]*\}/);if(e)try{return JSON.parse(e[0])}catch{}try{let n=t.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g,'$1"$2":');return JSON.parse(n)}catch{}let s=t.match(/```(?:json)?\s*([\s\S]*?)```/);if(s)try{return JSON.parse(s[1].trim())}catch{}return null}async function Wu(t,e){let{C:s}=oe(),{Spinner:n}=oe(),o=new n("Thinking...");o.start();let r=!0,i="";try{let c=await Bt.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}
|
|
69
|
+
`),c}catch(c){throw o.stop(),c}}async function Bu(t,e){return Bt.callChat(t,e)}pi.exports={MODELS:qu,getActiveModel:ju,setActiveModel:Du,getModelNames:Fu,callOllamaStream:Wu,callOllama:Bu,parseToolArgs:Uu}});var $i=N((Zg,gi)=>{var On=require("path"),{C:b}=oe(),{confirm:Hu,getAutoConfirm:Gu}=Me(),hi=2e3;function Ht(t,e){let s=t.split(`
|
|
70
70
|
`),n=e.split(`
|
|
71
|
-
`),o=[],r=s.length,i=n.length;if(r>
|
|
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=
|
|
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 zu(t,e,s,n=3){console.log(`
|
|
72
|
+
${b.bold}${b.cyan} Diff: ${t}${b.reset}`);let o=Ht(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 Ku(t,e,s){console.log(`
|
|
73
|
+
${b.bold}${b.cyan} File exists \u2014 showing changes: ${t}${b.reset}`);let n=Ht(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 Ju(t,e){console.log(`
|
|
74
74
|
${b.bold}${b.cyan} New file: ${t}${b.reset}`);let s=e.split(`
|
|
75
|
-
`),n=s.slice(0,20);for(let o of n)console.log(`${b.green} + ${o}${b.reset}`);s.length>20&&console.log(`${b.gray} ...+${s.length-20} more lines${b.reset}`),console.log()}async function
|
|
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
|
|
75
|
+
`),n=s.slice(0,20);for(let o of n)console.log(`${b.green} + ${o}${b.reset}`);s.length>20&&console.log(`${b.gray} ...+${s.length-20} more lines${b.reset}`),console.log()}async function Yu(t){return Gu()?!0:Hu(` ${t}?`)}function Xu(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
|
|
76
|
+
${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=Ht(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 w=0;w<g;w++)c.push({left:w<h.length?h[w]:"",right:w<p.length?p[w]:"",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)}`,w=p.right?`${b.green}${m(p.right,r)}${b.reset}`:`${m("",r)}`;console.log(` ${g}\u2502${w}`)}}f<c.length&&console.log(` ${b.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${b.reset}`),console.log(` ${b.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${b.reset}
|
|
77
|
+
`)}function Vu(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],c=On.isAbsolute(t)?On.relative(process.cwd(),t):t,l=Ht(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
78
|
${b.cyan}\u23FA${b.reset} ${b.bold}${o}(${c})${b.reset}`),f===0&&m===0){console.log(` ${b.dim}\u23BF (no changes)${b.reset}
|
|
79
|
-
`);return}let
|
|
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(T=>T.severity==="error").length,v=i.filter(T=>T.severity==="warn").length,C=i.filter(T=>T.severity==="info").length,S=[];k>0&&S.push(`${b.red}${k} error${k!==1?"s":""}${b.dim}`),v>0&&S.push(`${b.yellow}${v} warning${v!==1?"s":""}${b.dim}`),C>0&&S.push(`${b.cyan}${C} info${C!==1?"s":""}${b.dim}`),h.push(`found ${S.join(", ")}`)}console.log(` ${b.dim}\u23BF ${h.join(", ")}${b.reset}`);let g=[];l.forEach((k,v)=>{k.type!=="same"&&g.push(v)});let w=[],$=null,x=null;for(let k of g){let v=Math.max(0,k-r),C=Math.min(l.length-1,k+r);$===null?($=v,x=C):(v<=x+1||(w.push([$,x]),$=v),x=C)}$!==null&&w.push([$,x]);let O=" ";for(let k=0;k<w.length;k++){k>0&&console.log(`${O}${b.dim}\xB7\xB7\xB7${b.reset}`);let[v,C]=w[k];for(let S=v;S<=C;S++){let T=l[S],F=T.newLine!=null?T.newLine:T.oldLine,I=String(F).padStart(4),V=T.type!=="remove"?i.filter(D=>D.line===T.newLine):[];T.type==="remove"?console.log(`${O}${b.red}${I} -${T.line}${b.reset}`):T.type==="add"?console.log(`${O}${b.green}${I} +${T.line}${b.reset}`):console.log(`${O}${b.dim}${I}${b.reset} ${T.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 Qu(t,e,s={}){let n=On.isAbsolute(t)?On.relative(process.cwd(),t):t,o=e.split(`
|
|
80
80
|
`),r=s.annotations||[];console.log(`
|
|
81
|
-
${b.cyan}\u23FA${b.reset} ${b.bold}Create(${n})${b.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(
|
|
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
|
|
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,w="\u2139";p.severity==="error"?(g=b.red,w="\u2716"):p.severity==="warn"&&(g=b.yellow,w="\u26A0"),console.log(`${l} ${g}${w} ${p.message}${b.reset}`)}}o.length>20&&console.log(`${l}${b.dim} ...+${o.length-20} more lines${b.reset}`),console.log()}gi.exports={diffLines:Ht,showEditDiff:zu,showWriteDiff:Ku,showNewFilePreview:Ju,confirmFileChange:Yu,showSideBySideDiff:Xu,showClaudeDiff:Vu,showClaudeNewFile:Qu}});var it=N((e$,bi)=>{var yi=require("util").promisify(require("child_process").exec),Zu=require("util").promisify(require("child_process").execFile),{C:Q}=oe();async function qs(t){try{let{stdout:e}=await yi(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Mn(...t){try{let{stdout:e}=await Zu("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function ed(){return await qs("git rev-parse --is-inside-work-tree")==="true"}async function td(){return await qs("git branch --show-current")}async function js(){try{let{stdout:t}=await yi("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
82
|
+
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function Nn(t=!1){return await qs(`git diff ${t?"--cached":""}`)||""}async function Ds(){return(await js()).map(e=>e.file)}async function wi(){let t=await Ds();if(t.length===0)return null;let e=await Nn(),n=await Nn(!0)||e,o=0,r=0;if(n){let d=n.split(`
|
|
83
|
+
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&r++}else o=t.length;let 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 nd(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Mn("checkout","-b",s)!==null?s:null}async function sd(t){return await Mn("add","-A"),await Mn("commit","-m",t)?await Mn("rev-parse","--short","HEAD"):null}async function od(){let t=await wi();if(!t)return`${Q.dim}No changes${Q.reset}`;let e=[];e.push(`
|
|
84
84
|
${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
85
|
${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
86
|
${Q.bold}${Q.cyan}Suggested message:${Q.reset}`),e.push(` ${Q.cyan}${t.summary}${Q.reset}
|
|
87
87
|
`),e.join(`
|
|
88
|
-
`)}async function
|
|
88
|
+
`)}async function rd(){return(await js()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function id(){let t=await Ds();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 Nn();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
|
|
89
89
|
...(truncated)`:s;e.push(`
|
|
90
90
|
DIFF:
|
|
91
91
|
${n}`)}return e.join(`
|
|
92
|
-
`)}
|
|
92
|
+
`)}bi.exports={isGitRepo:ed,getCurrentBranch:td,getStatus:js,getDiff:Nn,getChangedFiles:Ds,analyzeDiff:wi,createBranch:nd,commit:sd,formatDiffSummary:od,getDiffContext:id,getMergeConflicts:rd}});var vt=N((t$,xi)=>{var Fs=require("fs").promises,ad=50,De=[],kt=[];function cd(t,e,s,n){for(De.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});De.length>ad;)De.shift();kt.length=0}async function ld(){if(De.length===0)return null;let t=De.pop();if(t.oldContent===null)try{await Fs.unlink(t.filePath)}catch{}else await Fs.writeFile(t.filePath,t.oldContent,"utf-8");return kt.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function ud(){if(kt.length===0)return null;let t=kt.pop();return await Fs.writeFile(t.filePath,t.newContent,"utf-8"),De.push(t),{tool:t.tool,filePath:t.filePath}}function dd(t=10){return De.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function fd(){return De.length}function md(){return kt.length}function pd(){De.length=0,kt.length=0}xi.exports={recordChange:cd,undo:ld,redo:ud,getHistory:dd,getUndoCount:fd,getRedoCount:md,clearHistory:pd}});var Gt=N((n$,Ci)=>{var ve=require("fs"),St=require("path"),we=[];function Us(){return St.join(process.cwd(),".nex","skills")}function _i(){return St.join(process.cwd(),".nex","config.json")}function hd(){let t=Us();return ve.existsSync(t)||ve.mkdirSync(t,{recursive:!0}),t}function Ws(){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=St.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:St.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||St.basename(t,".js"),type:"script",filePath:t,description:e.description||"",instructions:e.instructions||"",commands:(e.commands||[]).map(r=>({cmd:r.cmd.startsWith("/")?r.cmd:`/${r.cmd}`,desc:r.desc||r.description||"",handler:r.handler||null})),tools:(e.tools||[]).map(r=>({type:r.type||"function",function:{name:r.function.name,description:r.function.description||"",parameters:r.function.parameters||{type:"object",properties:{}}},execute:r.execute||null}))}:(console.error(`Skill validation failed: ${t}
|
|
93
93
|
${n.join(`
|
|
94
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
94
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function gd(){we=[];let t=Us();if(!ve.existsSync(t))return we;let e=Ws(),s;try{s=ve.readdirSync(t)}catch{return we}for(let n of s){let o=St.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 $d(){let t=[];for(let e of we)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
95
95
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
96
96
|
${t.join(`
|
|
97
97
|
|
|
98
|
-
`)}`}function
|
|
99
|
-
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},n);function d(m){l+=m.toString();let
|
|
100
|
-
`);for(let
|
|
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=
|
|
98
|
+
`)}`}function yd(){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 wd(){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 bd(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 xd(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 _d(){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 kd(t){let e=we.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Ws().filter(n=>n!==t);return ki(s),!0}function vd(t){let e=we.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Ws();return s.includes(t)||(s.push(t),ki(s)),!0}function Sd(){return we}Ci.exports={initSkillsDir:hd,loadAllSkills:gd,getSkillInstructions:$d,getSkillCommands:yd,getSkillToolDefinitions:wd,routeSkillCall:bd,handleSkillCommand:xd,listSkills:_d,enableSkill:kd,disableSkill:vd,getLoadedSkills:Sd,_getSkillsDir:Us,_validateScriptSkill:vi,_loadMarkdownSkill:Si,_loadScriptSkill:Ei}});var Ln=N((s$,Ni)=>{var{spawn:Ed}=require("child_process"),Cd=require("path"),Ti=require("fs"),Fe=new Map;function Td(){return Cd.join(process.cwd(),".nex","config.json")}function Bs(){let t=Td();if(!Ti.existsSync(t))return{};try{return JSON.parse(Ti.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function Pn(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
|
+
`,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(Fe.has(t))return Fe.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=Ed(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await Pn(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await Pn(o,"tools/list",{});return r.tools=i&&i.tools||[],Fe.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Ai(t){let e=Fe.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Fe.delete(t),!0}function Rd(){for(let[t]of Fe)Ai(t)}async function Oi(t,e,s={}){let n=Fe.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await Pn(n.proc,"tools/call",{name:e,arguments:s});return o&&Array.isArray(o.content)?o.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
101
|
+
`):JSON.stringify(o)}function Mi(){let t=[];for(let[e,s]of Fe)for(let n of s.tools)t.push({server:e,name:n.name,description:n.description||"",inputSchema:n.inputSchema||{type:"object",properties:{}}});return t}function Ad(){return Mi().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Od(t,e){if(!t.startsWith("mcp_"))return null;let s=t.substring(4).split("_");if(s.length<2)return null;let n=s[0],o=s.slice(1).join("_");return Oi(n,o,e)}function Md(){let t=Bs();return Object.entries(t).map(([e,s])=>{let n=Fe.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function Nd(){let t=Bs(),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}Ni.exports={loadMCPConfig:Bs,sendRequest:Pn,connectServer:Ri,disconnectServer:Ai,disconnectAll:Rd,callTool:Oi,getAllTools:Mi,getMCPToolDefinitions:Ad,routeMCPCall:Od,listServers:Md,connectAll:Nd}});var Hs=N((o$,qi)=>{var{getSkillToolDefinitions:Pd}=Gt(),{getMCPToolDefinitions:Ld}=Ln(),In=new Map;function Pi(){let{TOOL_DEFINITIONS:t}=Ue();return[...t,...Pd(),...Ld()]}function Li(t){if(In.has(t))return In.get(t);let s=Pi().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return In.set(t,n),n}function Id(){In.clear()}function qn(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 qd(t,e){let s=Li(t);if(s===null){let d=Pi().map(m=>m.function.name),f=qn(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
102
|
+
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),r=Object.keys(e),i=[],c={...e},l=!1;for(let u of n)if(!(u in e)||e[u]===void 0||e[u]===null){let d=qn(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=qn(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
103
|
`+i.map(u=>` - ${u}`).join(`
|
|
104
104
|
`)+`
|
|
105
105
|
|
|
106
|
-
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}
|
|
106
|
+
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}qi.exports={validateToolArgs:qd,closestMatch:qn,levenshtein:Ii,getCachedSchema:Li,clearSchemaCache:Id}});var Ui=N((r$,Fi)=>{var{levenshtein:jn}=Hs(),jd=200,Dd=.3,Fd=2;function Gs(t){return t.replace(/\r\n/g,`
|
|
107
107
|
`).replace(/\r/g,`
|
|
108
|
-
`).replace(/\t/g," ".repeat(
|
|
108
|
+
`).replace(/\t/g," ".repeat(Fd)).split(`
|
|
109
109
|
`).map(e=>{let s=e.replace(/\s+$/,""),n=s.match(/^(\s*)(.*)/);if(!n)return s;let[,o,r]=n;return o+r.replace(/ {2,}/g," ")}).join(`
|
|
110
|
-
`)}function
|
|
110
|
+
`)}function Ud(t,e){if(t.includes(e))return e;let s=Gs(t),n=Gs(e);if(!s.includes(n))return null;let o=t.split(`
|
|
111
111
|
`),r=s.split(`
|
|
112
112
|
`),i=n.split(`
|
|
113
113
|
`),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
|
|
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 Wd(t,e){if(!t||!e)return null;let s=t.split(`
|
|
115
115
|
`),o=e.split(`
|
|
116
|
-
`).length;return s.length===0||o===0?null:o===1?
|
|
117
|
-
`),u=
|
|
118
|
-
`),
|
|
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),
|
|
116
|
+
`).length;return s.length===0||o===0?null:o===1?Bd(s,e):Gd(s,e,o)}function ji(t){return Math.max(1,Math.floor(t/jd))}function Di(t,e){return t<=Math.ceil(e*Dd)}function Bd(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=jn(c.trim(),s);l<r&&(r=l,o={text:c,distance:l,line:i+1})}return o&&n>1&&(o=Hd(t,s,o,n)||o,r=o.distance),Di(r,e.length)?o:null}function Hd(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=jn(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function Gd(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=ji(n),r=null,i=1/0;for(let c=0;c<n;c+=o){let l=t.slice(c,c+s).join(`
|
|
117
|
+
`),u=jn(l,e);u<i&&(i=u,r={text:l,distance:u,line:c+1})}return r&&o>1&&(r=zd(t,e,r,o,s,n)||r,i=r.distance),Di(i,e.length)?r:null}function zd(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(`
|
|
118
|
+
`),h=jn(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}Fi.exports={normalizeWhitespace:Gs,fuzzyFindText:Ud,findMostSimilar:Wd}});var Bi=N((a$,Wi)=>{var{C:i$}=oe(),Kd=[{name:"OpenAI API Key",regex:/sk-[a-zA-Z0-9]{20,}/i},{name:"Anthropic API Key",regex:/sk-ant-api03-[a-zA-Z0-9-]{90,}/i},{name:"Google Gemini API Key",regex:/AIzaSy[a-zA-Z0-9_-]{30,45}/i},{name:"Slack Token",regex:/xox[bpors]-[a-zA-Z0-9-]+/i},{name:"AWS Access Key",regex:/AKIA[A-Z0-9]{16}/i},{name:"GitHub Token",regex:/ghp_[a-zA-Z0-9]{36}/i},{name:"Private Key",regex:/BEGIN (RSA|EC|DSA|OPENSSH|PGP) PRIVATE KEY/i},{name:"Database URL",regex:/\b(postgres|mongodb|mysql|redis):\/\/[^"'\s]+/i},{name:"Hardcoded Secret",regex:/(password|secret|token|api_key|apikey|api_secret|access_token|auth_token|credentials)\s*[:=]\s*['"'][^'"']{8,}/i}],Jd=[{name:"TODO",regex:/\bTODO\b/i,severity:"warn"},{name:"FIXME",regex:/\bFIXME\b/i,severity:"warn"},{name:"Debugger",regex:/\bdebugger\b/,severity:"error",ext:[".js",".ts",".jsx",".tsx"]},{name:"eval()",regex:/\beval\s*\(/,severity:"warn",ext:[".js",".ts",".jsx",".tsx"]},{name:"Console Log",regex:/\bconsole\.log\(/,severity:"info",ext:[".js",".ts",".jsx",".tsx"]},{name:"ANSI Code",regex:/\\x1b\[[0-9;]*m/,severity:"warn",message:"Avoid hardcoded ANSI codes; use cli/ui.js instead."}];function Yd(t,e){let s=e.split(`
|
|
119
|
+
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],c=r+1;for(let l of Kd)l.regex.test(i)&&n.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of Jd)l.ext&&!l.ext.includes(o)||l.regex.test(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:Yd}});var Js=N((c$,zi)=>{var Xd=require("fs").promises,Hi=require("path"),{exec:Vd}=require("util").promisify(require("child_process").exec),Et=[],Ks=null,Dn=!1,zs=0,Qd=6e4;function Gi(t){return!(Et.length===0||Ks!==t||Date.now()-zs>Qd)}async function Zd(t){if(!Dn&&!Gi(t)){Dn=!0,Ks=t;try{try{let{stdout:n}=await Vd("rg --files",{cwd:t,timeout:5e3});Et=n.split(`
|
|
120
|
+
`).filter(Boolean),zs=Date.now(),Dn=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await Xd.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,""),Et=e,zs=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Dn=!1}}}function ef(){return Et}function tf(){return Ks}function nf(t){return Et.filter(e=>Hi.basename(e)===t)}function sf(t){let e=t.toLowerCase();return Et.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}zi.exports={refreshIndex:Zd,getFileIndex:ef,getIndexedCwd:tf,findFileInIndex:nf,searchIndex:sf,isIndexValid:Gi}});var Ct=N((l$,Xi)=>{var Fn=require("fs"),Wn=require("path"),Ys=require("os"),{execFile:of}=require("child_process"),{promisify:rf}=require("util"),Xs=rf(of),af=Wn.join(".nex","servers.json"),Un=Wn.join(Ys.tmpdir(),"nex-ssh-sockets");function cf(){return Wn.join(process.cwd(),af)}function Ki(){let t=cf();if(!Fn.existsSync(t))return{};try{return JSON.parse(Fn.readFileSync(t,"utf-8"))}catch{return{}}}function lf(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 uf(){Fn.existsSync(Un)||Fn.mkdirSync(Un,{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(/^~/,Ys.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),uf();let s=t.user?`${t.user}@${t.host}`:t.host,n=Wn.join(Un,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(/^~/,Ys.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function df(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=Ji(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:c}=await Xs("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:Bn(l,t)}}}async function ff(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 Xs("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(Bn(c,t)||c)}}async function mf(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 Xs("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(Bn(c,t)||c)}}function Bn(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
|
|
121
121
|
HINT: Connection refused on ${e.host}:${s}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${s} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let s=e.key?`key: ${e.key}`:"SSH agent";return`${t}
|
|
122
122
|
HINT: Auth failed using ${s} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
|
|
123
123
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
124
124
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
125
125
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
126
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function
|
|
127
|
-
`,"utf-8")}
|
|
126
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function pf(t,e){let s=e.user?`${e.user}@${e.host}`:e.host,n=e.port&&Number(e.port)!==22?`:${e.port}`:"",o=e.os?` [${e.os}]`:"",r=e.key?` key:${e.key}`:"",i=e.sudo?" sudo:yes":"";return`${t}: ${s}${n}${o}${r}${i}`}Xi.exports={loadServerProfiles:Ki,resolveProfile:lf,buildSSHArgs:Ji,sshExec:df,scpUpload:ff,scpDownload:mf,enrichSSHError:Bn,formatProfile:pf,SSH_SOCKET_DIR:Un}});var Zs=N((u$,Qi)=>{var zt=require("fs"),Vs=require("path"),hf=Vs.join(".nex","deploy.json");function Qs(){return Vs.join(process.cwd(),hf)}function Vi(){let t=Qs();if(!zt.existsSync(t))return{};try{return JSON.parse(zt.readFileSync(t,"utf-8"))}catch{return{}}}function gf(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 $f(t){let e=Vs.join(process.cwd(),".nex");zt.existsSync(e)||zt.mkdirSync(e,{recursive:!0}),zt.writeFileSync(Qs(),JSON.stringify(t,null,2)+`
|
|
127
|
+
`,"utf-8")}Qi.exports={loadDeployConfigs:Vi,resolveDeployConfig:gf,saveDeployConfigs:$f,getDeployConfigPath:Qs}});var Jt=N((d$,ta)=>{var eo=null,We=null,Kt=null,Zi=`Playwright is not installed. Install with:
|
|
128
128
|
npm install playwright && npx playwright install chromium
|
|
129
|
-
Then restart nex-code.`;function
|
|
130
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function
|
|
131
|
-
`)}function
|
|
129
|
+
Then restart nex-code.`;function ea(){if(Kt!==null)return Kt;try{require("playwright"),Kt=!0}catch{Kt=!1}return Kt}async function Hn(){if(!ea())throw new Error(Zi);return eo||(eo=require("playwright")),(!We||!We.isConnected())&&(We=await eo.chromium.launch({headless:!0})),We}async function yf(){if(We){try{await We.close()}catch{}We=null}}process.on("exit",()=>{if(We)try{We.close()}catch{}});async function wf(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await Hn()).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?`
|
|
130
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function bf(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await Hn()).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 xf(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await Hn()).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 _f(t,{selector:e,value:s,submit:n=!1,timeout:o=3e4}={}){if(!e||s===void 0)throw new Error("selector and value are required");let i=await(await Hn()).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:wf,browserScreenshot:bf,browserClick:xf,browserFill:_f,closeBrowser:yf,INSTALL_MSG:Zi}});var Gn=N((f$,na)=>{var{C:K}=oe(),Xt="",$e=[],Yt=0,at=null;function kf(t){at=t}function vf(t,e){Xt=t,$e=[],Yt=0;for(let n of e){Yt++;let o=`t${Yt}`;$e.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${Yt}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=$e.map(n=>({...n}));return at&&at("create",{name:t,tasks:s}),s}function Sf(t,e,s){let n=$e.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),at&&at("update",{id:t,status:e,result:s}),{...n}):null}function Ef(){return{name:Xt,tasks:$e.map(t=>({...t}))}}function Cf(){Xt="",$e=[],Yt=0,at&&at("clear",{})}function Tf(){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 Rf(){if($e.length===0)return`${K.dim}No active tasks${K.reset}`;let t=[];Xt&&(t.push(` ${K.bold}${K.cyan}Tasks: ${Xt}${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(`
|
|
131
|
+
`)}function Af(){return $e.length>0&&$e.some(t=>t.status==="pending"||t.status==="in_progress")}na.exports={createTasks:vf,updateTask:Sf,getTaskList:Ef,clearTasks:Cf,getReadyTasks:Tf,renderTaskList:Rf,setOnChange:kf,hasActiveTasks:Af}});var no=N((m$,oa)=>{var{getActiveModel:Of,getActiveProviderName:Mf}=ge(),Vt={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},Qt={"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"},Zt={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Ne={};function sa(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Ne=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Ne={}}}sa();function to(){let e=Of()?.id,s=Mf();return e&&Ne[e]?Ne[e]:s&&Ne[`${s}:*`]?Ne[`${s}:*`]:e&&Qt[e]?Qt[e]:s&&Zt[s]?Zt[s]:"full"}function Nf(t,e){return t&&Ne[t]?Ne[t]:e&&Ne[`${e}:*`]?Ne[`${e}:*`]:t&&Qt[t]?Qt[t]:e&&Zt[e]?Zt[e]:"full"}function Pf(t,e){let s=e||to();if(s==="full"||!Vt[s])return t;let n=new Set(Vt[s]);return t.filter(o=>n.has(o.function.name))}function Lf(){let t=to(),e=Vt[t]?Vt[t].length:"all";return{tier:t,toolCount:e}}oa.exports={filterToolsForModel:Pf,getActiveTier:to,getModelTier:Nf,getTierInfo:Lf,TIERS:Vt,MODEL_TIERS:Qt,PROVIDER_DEFAULT_TIER:Zt,loadConfigOverrides:sa}});var ga=N((h$,ha)=>{var{callStream:If,getActiveProviderName:Kn,getActiveModelId:qf,getConfiguredProviders:jf,getProvider:ra,getActiveProvider:ia,parseModelSpec:aa}=ge(),{parseToolArgs:Df}=An(),{filterToolsForModel:Ff,getModelTier:zn}=no(),{trackUsage:Uf}=_t(),{MultiProgress:Wf,C:p$}=oe(),Bf=15,ca=5,la=3,Jn=new Map;function Hf(t,e){let s=Jn.get(t);return s&&s!==e?!1:(Jn.set(t,e),!0)}function en(t){Jn.delete(t)}function so(){Jn.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 If(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 Gf=new Set(["ask_user","task_list","spawn_agents"]),zf=new Set(["write_file","edit_file","patch_file"]),Kf=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Jf=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function fa(t){return Jf.test(t)?"full":Kf.test(t)?"essential":"standard"}function ma(t){let e=jf(),s=Kn(),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(zn(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Yf={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function oo(t){if(t.model){let{provider:o,model:r}=aa(t.model),i=o?ra(o):ia(),c=o||Kn();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=zn(r,c);return{provider:c,model:r,tier:l}}}let e=fa(t.task),s=Yf[e];if(s){let{provider:o,model:r}=aa(s),i=o?ra(o):ia(),c=o||Kn();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=zn(r,c);return{provider:c,model:r,tier:l}}}let n=ma(e);if(n){let o=zn(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function pa(t,e={}){let s=Math.min(t.max_iterations||10,Bf),n=`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,o=[],r={input:0,output:0},i=new Set,l=[{role:"system",content:`You are a focused sub-agent. Complete this specific task efficiently.
|
|
132
132
|
|
|
133
133
|
TASK: ${t.task}
|
|
134
134
|
${t.context?`
|
|
@@ -150,150 +150,150 @@ TOOL STRATEGY:
|
|
|
150
150
|
ERROR RECOVERY:
|
|
151
151
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
152
152
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
153
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=
|
|
154
|
-
`)}let w={};d&&(w.provider=d),f&&(w.model=f);try{for(let $=0;$<s;$++){let x=await
|
|
155
|
-
...(truncated)`: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
|
|
158
|
-
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of
|
|
153
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=oo(t),d=u.provider,f=u.model,m=u.tier,{TOOL_DEFINITIONS:h,executeTool:p}=Ue(),g=Ff(h.filter($=>!Gf.has($.function.name)),m);if(f&&!t._skipLog){let $=m?` (${m})`:"";process.stderr.write(` [sub-agent: ${d}:${f}${$}]
|
|
154
|
+
`)}let w={};d&&(w.provider=d),f&&(w.model=f);try{for(let $=0;$<s;$++){let x=await da(l,g,w);if(!x||typeof x!="object")throw new Error("Empty or invalid response from provider");if(x.usage){let T=x.usage.prompt_tokens||0,F=x.usage.completion_tokens||0;r.input+=T,r.output+=F;let I=d||Kn(),V=f||qf();Uf(I,V,T,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 T of i)en(T);return{task:t.task,status:"done",result:O||"(no response)",toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}let C=k.map(T=>{let F=T.function.name,I=Df(T.function.arguments),V=T.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(zf.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)||!Hf(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&&(en(D),i.delete(D));let ie=String(ne??"");return{role:"tool",content:ie.length>2e4?ie.substring(0,2e4)+`
|
|
155
|
+
...(truncated)`:ie,tool_call_id:V}}).catch(ne=>(D&&(en(D),i.delete(D)),{role:"tool",content:`ERROR: ${ne.message}`,tool_call_id:V}))}),S=await Promise.all(C);l.push(...S),e.onUpdate&&e.onUpdate(`step ${$+1}/${s}`)}for(let $ of i)en($);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)en(x);return{task:t.task,status:"failed",result:`Error: ${$.message}`,toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}}async function Xf(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>ca)return`ERROR: Max ${ca} parallel agents allowed, got ${e.length}`;let s=e.map(r=>oo(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 Wf(n);o.start();try{let r=e.map((d,f)=>{let m=s[f],h=m.model?{...d,model:`${m.provider}:${m.model}`,_skipLog:!0}:{...d,_skipLog:!0};return 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(),so();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(`
|
|
156
|
+
`)}catch(r){return o.stop(),so(),`ERROR: Sub-agent execution failed: ${r.message}`}}ha.exports={runSubAgent:pa,executeSpawnAgents:Xf,clearAllLocks:so,classifyTask:fa,pickModelForTier:ma,resolveSubAgentModel:oo,isRetryableError:ua,callWithRetry:da}});var sn=N((g$,Ra)=>{var Y=require("fs"),Be=require("path"),Vf=new Set(["the","a","an","is","are","and","or","but","in","on","at","to","for","of","with","this","that","it","as","be","by","from","was","were","has","have","had","not","do","does","did","so","if","its","my","me","we","you","he","she","they","our","your","their","can","will","would","could","should","may","might","then","than","also","which","when","where","how","what","who","all","any","each","more","most","use","used","using","get","set","new","add","make","der","die","das","den","dem","des","ein","eine","einen","einem","eines","und","oder","aber","von","zu","mit","auf","bei","nach","aus","vor","ist","sind","war","hat","haben","wird","kann","soll","muss","nicht","auch","als","durch"]);function Tt(){let t=Be.join(process.cwd(),".nex","brain");return Y.existsSync(t)||Y.mkdirSync(t,{recursive:!0}),t}function $a(){return Be.join(Tt(),".brain-index.json")}function ao(){return Be.join(Tt(),".embeddings.json")}function tn(){let t=Be.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=Be.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 nn(t){let e={},s=t,n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(n){let o=n[1].split(`
|
|
157
|
+
`);for(let r of o){let 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=Be.join(Tt(),`${t}.md`);if(!Y.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=Y.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=nn(s);return{name:t,content:s,body:o,frontmatter:n}}function Qf(t,e){let s=Be.join(Tt(),`${t}.md`);Y.writeFileSync(s,e,"utf-8"),tm(t,e),Zf()}function Zf(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=ao();Y.existsSync(t)&&setImmediate(async()=>{try{await Sa()}catch{}})}function em(t){let e=Be.join(Tt(),`${t}.md`);return Y.existsSync(e)?(Y.unlinkSync(e),nm(t),!0):!1}function Yn(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!Vf.has(e))}function co(t){let e={},{frontmatter:s,body:n}=nn(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(`
|
|
158
|
+
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of Yn(c))e[l]=(e[l]||0)+3}for(let i of Yn(n||t))e[i]=(e[i]||0)+1;return e}function lo(){let t=$a();if(!Y.existsSync(t))return{documents:{}};try{return JSON.parse(Y.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function uo(t){Y.writeFileSync($a(),JSON.stringify(t,null,2),"utf-8")}function tm(t,e){let s=lo(),{frontmatter:n}=nn(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:co(e),tags:o,modified:new Date().toISOString()},uo(s)}function nm(t){let e=lo();delete e.documents[t],uo(e)}function io(){let t=tn(),e={documents:{}};for(let s of t){let n=Y.readFileSync(s.path,"utf-8"),{frontmatter:o}=nn(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:co(n),tags:r,modified:s.modified.toISOString()}}return uo(e),e}function wa(){let t=lo(),e=tn();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return io()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return io();return t}function ba(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=Yn(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",ro=400,sm=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 fo(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+ro).join(" ");if(s.push({text:o,offset:n}),n+ro>=e.length)break;n+=ro-sm}return s}async function Sa(){let t=tn(),e={documents:{}},s=ao();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 fo(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=ao();if(!Y.existsSync(o))return[];let r;try{r=JSON.parse(Y.readFileSync(o,"utf-8"))}catch{return[]}let i=await fo(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 Ca(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 Ta(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=Ca(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 om(t){if(!t||!t.trim())return"";let e=Be.join(process.cwd(),".nex","brain");if(!Y.existsSync(e)||tn().length===0)return"";let n;try{n=await Ta(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
159
|
...(truncated)`}let f=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(i.push(`--- ${l.name} (relevance: ${f}) ---
|
|
160
160
|
${u}`),c+=o(u),c>=r)break}return i.length===0?"":`KNOWLEDGE BASE (auto-selected):
|
|
161
161
|
|
|
162
162
|
${i.join(`
|
|
163
163
|
|
|
164
|
-
`)}`}
|
|
164
|
+
`)}`}Ra.exports={getBrainDir:Tt,listDocuments:tn,readDocument:ya,writeDocument:Qf,removeDocument:em,buildIndex:io,getIndex:wa,query:Ta,getBrainContext:om,isEmbeddingAvailable:_a,generateEmbedding:fo,buildEmbeddingIndex:Sa,semanticQuery:Ea,cosineSimilarity:ka,_keywordQuery:ba,_extractKeywords:co,_chunkText:va,parseFrontmatter:nn,tokenize:Yn,_fuseResults:Ca}});var Ue=N((b$,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:rm}=require("child_process"),mo=require("axios"),{isForbidden:im,isDangerous:am,isCritical:Ma,confirm:Pe}=Me(),{showClaudeDiff:Xn,showClaudeNewFile:cm,showEditDiff:$$,confirmFileChange:on}=$i(),{C:P,Spinner:qa,getToolSpinnerText:lm}=oe(),{isGitRepo:po,getCurrentBranch:Na,getStatus:um,getDiff:dm}=it(),{recordChange:Vn}=vt(),{fuzzyFindText:Pa,findMostSimilar:go}=Ui(),{runDiagnostics:rn}=Bi(),{findFileInIndex:fm,getFileIndex:y$}=Js(),{resolveProfile:Le,sshExec:Xe,scpUpload:mm,scpDownload:pm}=Ct(),{resolveDeployConfig:hm,loadDeployConfigs:w$}=Zs(),gm=/^(vim?|nano|emacs|pico|less|more|top|htop|iftop|iotop|glances|telnet\s|screen|tmux|fzf|gum|dialog|whiptail|man\s|node\s*$|python3?\s*$|irb\s*$|rails\s*c|psql\s|mysql\s|redis-cli|mongosh?|sqlite3)\b/,$m=/^ssh\s/,ym=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function Qn(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=fm(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
165
|
${i.map(l=>xe.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
166
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
166
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function wm(t){return/\bprintenv\b/.test(t)?"printenv exposes all secrets. Use `echo $VAR_NAME` for a single variable, or `env | grep PATTERN` for filtered output.":/cat\s+.*\.env\b/.test(t)?'Reading .env directly is blocked. Use `grep -v "KEY=" .env` to inspect non-secret entries, or ask the user to share specific values.':/cat\s+.*credentials/i.test(t)?"Credentials files are blocked. Reference the variable name from the application config instead.":/python3?\s+-c\s/.test(t)?"Inline python -c is blocked. Write a temporary script file and run it with `python3 script.py` instead.":/node\s+-e\s/.test(t)?"Inline node -e is blocked. Write a temporary script file and run it with `node script.js` instead.":/curl.*-X\s*POST|curl.*--data/.test(t)?"curl POST is blocked to prevent data exfiltration. Use the application's own API client or ask the user to run the request.":/base64.*\|.*bash/.test(t)?"Piping base64-decoded content to bash is blocked. Decode the content first, inspect it, then run explicitly.":/\beval\s*\(/.test(t)?"eval is blocked. Execute the command directly without eval.":/(?:^|[;&|]\s*)history(?:\s|$)/.test(t)?"Shell history is blocked. Look at git log or project files for context instead.":""}function 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
167
|
|
|
168
168
|
`+s.join(`
|
|
169
|
-
`)}function qa(t,e,s){let n=mo(t,e);if(!n)return null;let o=Math.max(3,Math.ceil(e.length*.05));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var Na=!1,an=null;function wm(){an&&(an(),an=null)}async function fo(){if(!Na){Na=!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 bm=[/\.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 bm)if(s.test(e))return null;return e}var xm=[{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 rn(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 Pa(t,e,s={}){switch(t){case"bash":{let n=e.command,o=rm(n);if(o){let u=ym(n);return`BLOCKED: Command matches forbidden pattern: ${o}${u?`
|
|
170
|
-
HINT: ${u}`:""}`}if(s.autoConfirm?
|
|
171
|
-
${P.yellow}${u}: ${n}${P.reset}`),!await Pe(" Execute?"))return"CANCELLED: User declined to execute this command."}let i=process.cwd();try{
|
|
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
|
-
`+m.message:""}`}let r=Buffer.alloc(8192),i=await
|
|
174
|
-
`),d=(e.line_start||1)-1,f=e.line_end||u.length;return u.slice(d,f).map((m,
|
|
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=
|
|
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 bm(){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 xm=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function be(t){let e=xe.isAbsolute(t)?xe.resolve(t):xe.resolve(process.cwd(),t);for(let s of xm)if(s.test(e))return null;return e}var _m=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Use this to find where functions/variables/classes are defined or used. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when requirements are ambiguous, you need to choose between approaches, or a decision has significant impact. Do not ask unnecessary questions \u2014 proceed if the intent is clear.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"deploy",description:'Deploy files to a remote server via rsync + optional remote script. Can use a named config from .nex/deploy.json (e.g. deploy("prod")) or explicit params. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},local_path:{type:"string",description:'Local directory or file to sync (e.g. "dist/", "./build"). Required if no config.'},remote_path:{type:"string",description:'Remote destination path (e.g. "/var/www/app"). Required if no config.'},deploy_script:{type:"string",description:"Shell command to run on the remote after sync. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from sync. Optional."},dry_run:{type:"boolean",description:"Show what would be synced without actually syncing. Default: false."}},required:[]}}}];function 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=im(n);if(o){let u=wm(n);return`BLOCKED: Command matches forbidden pattern: ${o}${u?`
|
|
170
|
+
HINT: ${u}`:""}`}if(s.autoConfirm?Ma(n):am(n)){let u=Ma(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
|
|
171
|
+
${P.yellow}${u}: ${n}${P.reset}`),!await Pe(" 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=$m.test(n.trim())&&!ym.test(n.trim());if(gm.test(n.trim())||c){s.silent||console.log(`${P.dim} \u25B6 interactive: ${n}${P.reset}`);let u=rm("sh",["-c",n],{stdio:"inherit",cwd: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}
|
|
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 Qn(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
|
+
`+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
|
+
`),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 ho();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 rn(n,e.content);if(Xn(n,r,e.content,{annotations:l}),!await on("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let l=await rn(n,e.content);if(cm(n,e.content,{annotations:l}),!await on("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"),Vn("write_file",n,r,e.content),`Written: ${n} (${e.content.length} chars)`}case"edit_file":{await ho();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 Qn(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?`
|
|
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 rn(n,f.content);if(Xn(n,r,f.content,{annotations:p}),!await on(`Apply (auto-fix, line ${f.line}, distance ${f.distance})`))return"CANCELLED: User declined to apply edit."}await X.writeFile(n,f.content,"utf-8"),Vn("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=go(r,e.old_text);return m?`ERROR: old_text not found in ${n}
|
|
177
177
|
Most similar text (line ${m.line}, distance ${m.distance}):
|
|
178
|
-
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=r.split(i).join(e.new_text),f=await
|
|
179
|
-
`)||"(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
|
|
178
|
+
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=r.split(i).join(e.new_text),f=await rn(n,d);if(Xn(n,r,d,{annotations:f}),!await on(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"),Vn("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
|
+
`)||"(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
180
|
`).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:
|
|
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}=Js(),g=f(),w=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
182
|
`);return x?`${O}
|
|
183
183
|
|
|
184
|
-
\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
|
|
184
|
+
\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
185
|
`).slice(0,100).join(`
|
|
186
|
-
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await
|
|
187
|
-
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await X.readFile(n,"utf-8"),c=[],l=!1,u=!1;for(let m=0;m<r.length;m++){let{old_text:
|
|
186
|
+
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await ho();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 Qn(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?`
|
|
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 w=go(i,h);if(w){let $=Math.max(3,Math.ceil(h.length*.05));if(w.distance<=$)c.push({old_text:w.text,new_text:p}),u=!0;else return`ERROR: Patch ${m+1} old_text not found in ${n}
|
|
188
188
|
Most similar text (line ${w.line}, distance ${w.distance}):
|
|
189
|
-
${w.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${n}`}}}let d=i;for(let{old_text:m,new_text:
|
|
189
|
+
${w.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 rn(n,d);if(Xn(n,i,d,{annotations:m}),!await on(l?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await X.writeFile(n,d,"utf-8"),Vn("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 mo.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 mo.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
190
|
|
|
191
191
|
${r}`;return i.length>0&&(c+=`
|
|
192
192
|
|
|
193
193
|
Sources:
|
|
194
194
|
`+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
|
|
195
|
+
`)),c}catch(o){console.error(`${P.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${P.reset}`)}try{let r=(await mo.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
196
|
${u.url}`).join(`
|
|
197
197
|
|
|
198
|
-
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=
|
|
198
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=Jt();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
|
|
199
199
|
|
|
200
200
|
Links:
|
|
201
201
|
`+o.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
|
|
202
202
|
`):"";return`Title: ${o.title}
|
|
203
203
|
URL: ${o.url}
|
|
204
204
|
|
|
205
|
-
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=
|
|
205
|
+
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=Jt();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
|
|
206
206
|
Title: ${o.title}
|
|
207
207
|
URL: ${o.url}
|
|
208
208
|
|
|
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=>{
|
|
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}=Jt();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=Jt();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});cn=()=>{r.close(),o("CANCELLED")},console.log(`
|
|
210
|
+
${P.cyan}${P.bold} ? ${n}${P.reset}`),r.question(`${P.cyan} > ${P.reset}`,i=>{cn=null,r.close(),o(i.trim()||"(no response)")})})}case"git_status":{if(!await po())return"ERROR: Not a git repository";let n=await Na()||"(detached)",o=await um();if(o.length===0)return`Branch: ${n}
|
|
211
211
|
Clean working tree (no changes)`;let r=[`Branch: ${n}`,`Changed files (${o.length}):`];for(let 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
|
|
212
|
+
`)}case"git_diff":{if(!await po())return"ERROR: Not a git repository";let n;if(e.file){let o=["diff"];e.staged&&o.push("--cached"),o.push("--",e.file);try{n=execFileSync("git",o,{cwd:process.cwd(),encoding:"utf-8",timeout:15e3,stdio:"pipe"}).trim()}catch{n=""}}else n=await dm(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await po())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}=Gn(),{getActiveTaskProgress:l}=oe(),u=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let d=n(e.name,e.tasks);return u||console.log(`
|
|
213
213
|
`+i()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
214
214
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
215
215
|
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":o(e.task_id,e.status,e.result)?(u||console.log(`
|
|
216
216
|
`+i()),`Updated ${e.task_id}: ${e.status}${e.result?" \u2014 "+e.result:""}`):`ERROR: Task not found: ${e.task_id}`;case"get":{let d=r();return d.tasks.length===0?"No active tasks":(u||console.log(`
|
|
217
|
-
`+i()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=
|
|
217
|
+
`+i()),JSON.stringify(d,null,2))}default:return`ERROR: Unknown task_list action: ${e.action}. Use: create, update, get`}}case"spawn_agents":{let{executeSpawnAgents:n}=ga();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=ge();return n(e.model)?`Switched to ${o()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let n=Math.min(e.limit||10,30),o=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:r}=await Z(`gh ${o.join(" ")}`,{cwd:process.cwd(),timeout:3e4}),i=JSON.parse(r||"[]");return i.length===0?"No workflow runs found.":i.map(l=>{let u=l.conclusion||l.status||"unknown",d=u==="success"?"\u2713":u==="failure"?"\u2717":u==="in_progress"?"\u283F":"\u25CB",f=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${d} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${u} \xB7 ${f}`}).join(`
|
|
218
218
|
`)}catch(r){let i=(r.stderr||r.message||"").toString();return i.includes("not found")||i.includes("not logged")?"ERROR: gh CLI not found or not authenticated. Run: gh auth login":`ERROR: ${i.split(`
|
|
219
219
|
`)[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
220
|
...(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
221
|
`)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
|
|
222
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Me(),o=e.branch||await
|
|
222
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Me(),o=e.branch||await Na()||"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
223
|
${P.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${P.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await 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=
|
|
224
|
+
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=an(`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(`
|
|
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=an(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
226
|
...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
227
227
|
`)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let n=e.namespace||"default";if(console.log(`
|
|
228
|
-
${P.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${P.reset}`),console.log(`${P.dim} Command: ${e.command}${P.reset}`),!await Pe(" 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=
|
|
228
|
+
${P.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${P.reset}`),console.log(`${P.dim} Command: ${e.command}${P.reset}`),!await Pe(" 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=an(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
229
|
`)[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 Pe(" 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=
|
|
230
|
+
${P.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${P.reset}`),!await Pe(" 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=an(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
231
|
`)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let n=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let c=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
|
|
232
|
-
${P.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${n})${P.reset}`),!await Pe(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=
|
|
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}=
|
|
232
|
+
${P.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${n})${P.reset}`),!await Pe(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=an(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(`
|
|
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}=sn(),{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
234
|
|
|
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=Le(e.server)}catch(
|
|
236
|
-
${P.yellow} \u26A0 Remote command on ${
|
|
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=Le(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(`
|
|
236
|
+
${P.yellow} \u26A0 Remote command on ${h}: ${o}${P.reset}`),!await Pe(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:f}=await Xe(n,o,{timeout:i,sudo:r}),m=[l,u].filter(Boolean).join(`
|
|
237
237
|
`).trim();return d!==0?`EXIT ${d}
|
|
238
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=Le(e.server)}catch(i){return`ERROR: ${i.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
239
|
-
${P.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${P.reset}`),!await Pe(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await
|
|
239
|
+
${P.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${P.reset}`),!await Pe(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await mm(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=Le(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await pm(n,e.remote_path,e.local_path)}catch(o){return`ERROR: ${o.message}`}}case"service_manage":{if(!e.service)return"ERROR: service is required";if(!e.action)return"ERROR: action is required";let n=["status","start","stop","restart","reload","enable","disable"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost",r=e.action==="status",i=null;if(!o)try{i=Le(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(`
|
|
240
240
|
${P.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${P.reset}`),!await Pe(" 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}
|
|
241
241
|
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await Xe(i,c,{timeout:15e3,sudo:!0}),m=[l,u].filter(Boolean).join(`
|
|
242
242
|
`).trim();return d!==0?/not found|loaded.*not-found/i.test(m)?`ERROR: Service "${e.service}" not found on ${i.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${d}
|
|
243
|
-
${f||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${o} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:
|
|
244
|
-
${(
|
|
243
|
+
${f||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",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=Le(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await Xe(l,c,{timeout:2e4}),h=[u,d].filter(Boolean).join(`
|
|
245
245
|
`).trim();return f!==0?`EXIT ${f}
|
|
246
|
-
${m||
|
|
246
|
+
${m||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",r=`docker ps ${e.all?"-a":""} --format "table {{.ID}}\\t{{.Names}}\\t{{.Image}}\\t{{.Status}}\\t{{.Ports}}"`.trim().replace(/\s+/g," ");if(n)try{let{stdout:m,stderr:h}=await Z(r,{timeout:1e4});return(m||h||"(no containers)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
247
247
|
${(m.stderr||m.message||"").toString().trim()}`}let i;try{i=Le(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await Xe(i,r,{timeout:15e3}),f=[c,l].filter(Boolean).join(`
|
|
248
248
|
`).trim();return u!==0?`EXIT ${u}
|
|
249
|
-
${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=`docker logs --tail ${o} ${r} ${e.container} 2>&1`.trim().replace(/\s+/g," ");if(n)try{let{stdout:
|
|
250
|
-
${(
|
|
249
|
+
${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",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=Le(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Xe(c,i,{timeout:2e4}),m=[l,u].filter(Boolean).join(`
|
|
251
251
|
`).trim();return d!==0?`EXIT ${d}
|
|
252
|
-
${f||m}`:m||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!o.test(e.command.trim())){let
|
|
253
|
-
${P.yellow} \u26A0 docker exec in ${e.container} on ${
|
|
254
|
-
${(
|
|
252
|
+
${f||m}`:m||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!o.test(e.command.trim())){let h=n?"local":e.server;if(console.log(`
|
|
253
|
+
${P.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${P.reset}`),!await Pe(" 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}
|
|
254
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=Le(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:f}=await Xe(c,i,{timeout:35e3}),m=[l,u].filter(Boolean).join(`
|
|
255
255
|
`).trim();return d!==0?`EXIT ${d}
|
|
256
|
-
${f||m}`:m||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let
|
|
257
|
-
${P.yellow} \u26A0 docker ${e.action} ${e.container} on ${
|
|
258
|
-
${(
|
|
256
|
+
${f||m}`:m||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let p=o?"local":e.server;if(console.log(`
|
|
257
|
+
${P.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${P.reset}`),!await Pe(" 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}
|
|
258
|
+
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=Le(e.server)}catch(p){return`ERROR: ${p.message}`}let{stdout:u,stderr:d,exitCode:f,error:m}=await Xe(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
|
|
259
259
|
`).trim();return f!==0?`EXIT ${f}
|
|
260
|
-
${m||
|
|
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 Pe(" Proceed with deployment?")))return"CANCELLED: User declined.";let m="";try{let{stdout:
|
|
262
|
-
${m||"(nothing to sync)"}`;let
|
|
260
|
+
${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...hm(e.config),...e},delete e.config,delete e._name}catch(p){return`ERROR: ${p.message}`}if(!e.server)return'ERROR: server is required (or use config: "<name>")';if(!e.local_path)return"ERROR: local_path is required";if(!e.remote_path)return"ERROR: remote_path is required";let n;try{n=Le(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(`
|
|
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 Pe(" 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:
|
|
262
|
+
${m||"(nothing to sync)"}`;let h="";if(e.deploy_script){let{stdout:p,stderr:g,exitCode:w,error:$}=await Xe(n,e.deploy_script,{timeout:6e4}),x=[p,g].filter(Boolean).join(`
|
|
263
263
|
`).trim();if(w!==0)return`rsync OK
|
|
264
264
|
|
|
265
265
|
ERROR (deploy_script, exit ${w}):
|
|
266
|
-
${$||x}`;
|
|
266
|
+
${$||x}`;h=`
|
|
267
267
|
|
|
268
268
|
Remote script output:
|
|
269
269
|
${x||"(no output)"}`}return`Deployed ${d} \u2192 ${o}:${e.remote_path}
|
|
270
|
-
${m}${
|
|
271
|
-
`)}function
|
|
270
|
+
${m}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function km(t,e,s={}){let n=s.silent?null:lm(t,e);if(!n)return 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:_m,executeTool:km,resolvePath:be,autoFixPath:Qn,autoFixEdit:Da,enrichBashError:ja,cancelPendingAskUser:bm}});var Wa=N((x$,Ua)=>{var{loadServerProfiles:yo}=Ct(),$o={almalinux9:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all. Open port: firewall-cmd --permanent --add-port=PORT/tcp && firewall-cmd --reload.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent | audit2why. Fix context: restorecon -Rv /path.","Nginx config: /etc/nginx/. Test: nginx -t. Reload: systemctl reload nginx.","Process list: ps aux. Ports: ss -tuln.","Python: python3. Pip: pip3. Virtualenv: python3 -m venv."],almalinux8:["Package manager: dnf (NOT apt). Install: dnf install <pkg>. Update: dnf update.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: firewalld. Check: firewall-cmd --list-all.","SELinux is active by default. Check: getenforce. Diagnose: ausearch -m avc -ts recent."],ubuntu:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw. Status: ufw status. Allow port: ufw allow PORT/tcp.","SELinux NOT active by default (AppArmor instead). Check: aa-status."],debian:["Package manager: apt. Install: apt install <pkg>. Update: apt update && apt upgrade.","Service manager: systemctl. Logs: journalctl -u <service> -n 50.","Firewall: ufw or iptables."],macos:["Package manager: Homebrew (brew). Install: brew install <pkg>. Update: brew update && brew upgrade.","Service manager: launchctl (NOT systemctl). Start: brew services start <name>. List: brew services list.",`No systemd. No journalctl. Use: log show --predicate 'process == "nginx"' --last 1h instead.`,"Firewall: macOS built-in (pfctl or System Settings). Check: pfctl -s rules.","Process list: ps aux. Ports: lsof -i -n -P | grep LISTEN."]};function vm(){let t=yo();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&&$o[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 $o[o])s.push(`- ${i}`)}}return s.join(`
|
|
271
|
+
`)}function Sm(t){let e=yo();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function Em(){return Object.keys(yo())}Ua.exports={getServerContext:vm,hasServerOS:Sm,getProfileNames:Em,OS_HINTS:$o}});var bo=N((_$,Ha)=>{var Oe=require("fs").promises,Ce=require("path"),Zn=require("util").promisify(require("child_process").exec),{C:Ie}=oe(),{getMergeConflicts:Ba}=it(),{getServerContext:Cm}=Wa(),wo=new Map,Rt=new Map,es=null,Tm=3e4;async function Ve(t){try{return await t()}catch{return null}}async function Rm(){if(!es||Date.now()>es)return!1;let t=[Ce.join(process.cwd(),"package.json"),Ce.join(process.cwd(),"README.md"),Ce.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await Oe.stat(e),n=Rt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(Rt.has(e))return!1}try{let e=Ce.join(process.cwd(),".git","HEAD"),s=await Oe.stat(e),n=Rt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function Am(){let t=[Ce.join(process.cwd(),"package.json"),Ce.join(process.cwd(),"README.md"),Ce.join(process.cwd(),".gitignore"),Ce.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await Oe.stat(e);Rt.set(e,s.mtimeMs)}catch{Rt.delete(e)}}async function Om(t){let e="fileContext",s=wo.get(e),n=!1;if(s&&await Rm()&&(n=!0),!n){let u=[],d=Ce.join(t,"package.json");if(await Ve(()=>Oe.access(d).then(()=>!0).catch(()=>!1)))try{let w=await Oe.readFile(d,"utf-8"),$=JSON.parse(w),x={name:$.name,version:$.version};$.scripts&&(x.scripts=Object.keys($.scripts).slice(0,15)),$.dependencies&&(x.deps=Object.keys($.dependencies).length),$.devDependencies&&(x.devDeps=Object.keys($.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(x)}`)}catch{}let m=Ce.join(t,"README.md");if(await Ve(()=>Oe.access(m).then(()=>!0).catch(()=>!1))){let $=(await Oe.readFile(m,"utf-8")).split(`
|
|
272
272
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
273
273
|
${$.join(`
|
|
274
|
-
`)}`)}let
|
|
274
|
+
`)}`)}let p=Ce.join(t,".gitignore");if(await Ve(()=>Oe.access(p).then(()=>!0).catch(()=>!1))){let w=await Oe.readFile(p,"utf-8");u.push(`GITIGNORE:
|
|
275
275
|
${w.trim()}`)}s=u.join(`
|
|
276
276
|
|
|
277
|
-
`),
|
|
277
|
+
`),wo.set(e,s),es=Date.now()+Tm,await Am()}let o=[s],[r,i,c,l]=await Promise.all([Ve(async()=>{let{stdout:u}=await Zn("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Ve(async()=>{let{stdout:u}=await Zn("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Ve(async()=>{let{stdout:u}=await Zn("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
278
|
${i}`),c&&o.push(`RECENT COMMITS:
|
|
279
279
|
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
280
280
|
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
281
|
-
${u}`)}try{let u=
|
|
281
|
+
${u}`)}try{let u=Cm();u&&o.push(u)}catch{}return o.join(`
|
|
282
282
|
|
|
283
|
-
`)}async function
|
|
284
|
-
${e}`);let s=
|
|
285
|
-
${s}`);let n=
|
|
283
|
+
`)}async function Mm(t){let e=Ce.join(t,"package.json"),s="";if(await Ve(()=>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([Ve(async()=>{let{stdout:i}=await Zn("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),Ba()]);if(s&&console.log(`${Ie.dim} project: ${s}${Ie.reset}`),o&&console.log(`${Ie.dim} branch: ${o}${Ie.reset}`),r&&r.length>0){console.log(`${Ie.red} \u26A0 ${r.length} unresolved merge conflict(s):${Ie.reset}`);for(let i of r)console.log(`${Ie.red} ${i.file}${Ie.reset}`);console.log(`${Ie.yellow} \u2192 Resolve conflicts before starting tasks${Ie.reset}`)}console.log()}Ha.exports={gatherProjectContext:Om,printContext:Mm,_clearContextCache:()=>{wo.clear(),Rt.clear(),es=null}}});var lt=N((k$,Ja)=>{var Ge=require("fs"),xo=require("path");function ts(){return xo.join(process.cwd(),".nex","sessions")}function Ga(){let t=ts();Ge.existsSync(t)||Ge.mkdirSync(t,{recursive:!0})}function _o(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return xo.join(ts(),`${e}.json`)}function ko(t,e,s={}){Ga();let n=_o(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 Ge.writeFileSync(n,JSON.stringify(o,null,2),"utf-8"),{path:n,name:t}}function za(t){let e=_o(t);if(!Ge.existsSync(e))return null;try{return JSON.parse(Ge.readFileSync(e,"utf-8"))}catch{return null}}function Ka(){Ga();let t=ts(),e=Ge.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Ge.readFileSync(xo.join(t,n),"utf-8"));s.push({name:o.name||n.replace(".json",""),createdAt:o.createdAt,updatedAt:o.updatedAt,messageCount:o.messageCount||0,model:o.model,provider:o.provider})}catch{}return s.sort((n,o)=>(o.updatedAt||"").localeCompare(n.updatedAt||""))}function Nm(t){let e=_o(t);return Ge.existsSync(e)?(Ge.unlinkSync(e),!0):!1}function Pm(){let t=Ka();return t.length===0?null:za(t[0].name)}var ct=null,He=null,ln=null;function Lm(t,e={}){t.length!==0&&(ct&&clearTimeout(ct),He=t,ln=e||{},ct=setTimeout(()=>{He&&He.length>0&&ko("_autosave",He,ln),ct=null,He=null,ln=null},5e3))}function Im(){ct&&(clearTimeout(ct),ct=null),He&&He.length>0&&(ko("_autosave",He,ln),He=null,ln=null)}Ja.exports={saveSession:ko,loadSession:za,listSessions:Ka,deleteSession:Nm,getLastSession:Pm,autoSave:Lm,flushAutoSave:Im,_getSessionsDir:ts}});var Qe=N((v$,ec)=>{var ze=require("fs"),ns=require("path"),qm=require("os");function vo(){return ns.join(process.cwd(),".nex","memory")}function So(){return ns.join(vo(),"memory.json")}function jm(){return ns.join(process.cwd(),"NEX.md")}function Ya(){return ns.join(qm.homedir(),".nex","NEX.md")}function Dm(){let t=vo();ze.existsSync(t)||ze.mkdirSync(t,{recursive:!0})}function ss(){let t=So();if(!ze.existsSync(t))return{};try{return JSON.parse(ze.readFileSync(t,"utf-8"))}catch{return{}}}function Xa(t){Dm(),ze.writeFileSync(So(),JSON.stringify(t,null,2),"utf-8")}function Fm(t,e){let s=ss();s[t]={value:e,updatedAt:new Date().toISOString()},Xa(s)}function Um(t){let e=ss();return e[t]?e[t].value:null}function Wm(t){let e=ss();return t in e?(delete e[t],Xa(e),!0):!1}function Va(){let t=ss();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Qa(){let t=Ya();if(!ze.existsSync(t))return"";try{return ze.readFileSync(t,"utf-8").trim()}catch{return""}}function Za(){let t=jm();if(!ze.existsSync(t))return"";try{return ze.readFileSync(t,"utf-8").trim()}catch{return""}}function Bm(){let t=[],e=Qa();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
284
|
+
${e}`);let s=Za();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
285
|
+
${s}`);let n=Va();if(n.length>0){let o=n.map(r=>` ${r.key}: ${r.value}`).join(`
|
|
286
286
|
`);t.push(`PROJECT MEMORY:
|
|
287
287
|
${o}`)}return t.join(`
|
|
288
288
|
|
|
289
|
-
`)}
|
|
289
|
+
`)}ec.exports={remember:Fm,recall:Um,forget:Wm,listMemories:Va,loadGlobalInstructions:Qa,loadProjectInstructions:Za,getMemoryContext:Bm,_getMemoryDir:vo,_getMemoryFile:So,_getGlobalNexMdPath:Ya}});var un=N((E$,sc)=>{var ut=require("fs"),Eo=require("path"),{C:S$}=oe(),os={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"},At={...os};function tc(){let t=Eo.join(process.cwd(),".nex","config.json");if(ut.existsSync(t))try{let e=JSON.parse(ut.readFileSync(t,"utf-8"));e.permissions&&(At={...os,...e.permissions})}catch{}}function Hm(){let t=Eo.join(process.cwd(),".nex"),e=Eo.join(t,"config.json"),s={};if(ut.existsSync(e))try{s=JSON.parse(ut.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=At,ut.existsSync(t)||ut.mkdirSync(t,{recursive:!0}),ut.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function nc(t){return At[t]||"ask"}function Gm(t,e){return["allow","ask","deny"].includes(e)?(At[t]=e,!0):!1}function zm(t){return nc(t)}function Km(){return Object.entries(At).map(([t,e])=>({tool:t,mode:e}))}function Jm(){At={...os}}tc();sc.exports={getPermission:nc,setPermission:Gm,checkPermission:zm,listPermissions:Km,loadPermissions:tc,savePermissions:Hm,resetPermissions:Jm,DEFAULT_PERMISSIONS:os}});var Ot=N((T$,cc)=>{var dt=require("fs"),rs=require("path"),C$=require("readline"),{C:B}=oe(),re=null,Co=!1,To=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 is(){return rs.join(process.cwd(),".nex","plans")}function rc(){let t=is();dt.existsSync(t)||dt.mkdirSync(t,{recursive:!0})}function Ym(t,e=[]){return re={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(s=>({description:s.description||s,files:s.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},re}function Xm(){return re}function Vm(t){Co=t}function Qm(){return Co}function Zm(){return!re||re.status!=="draft"?!1:(re.status="approved",re.updatedAt=new Date().toISOString(),!0)}function ep(){return!re||re.status!=="approved"?!1:(re.status="executing",!0)}function tp(t,e){return!re||t<0||t>=re.steps.length?!1:(re.steps[t].status=e,re.updatedAt=new Date().toISOString(),re.steps.every(s=>s.status==="done"||s.status==="skipped")&&(re.status="completed"),!0)}function np(t){if(!t)return`${B.dim}No active plan${B.reset}`;let e={draft:`${B.yellow}DRAFT${B.reset}`,approved:`${B.green}APPROVED${B.reset}`,executing:`${B.blue}EXECUTING${B.reset}`,completed:`${B.green}COMPLETED${B.reset}`},s=[];s.push(`
|
|
290
290
|
${B.bold}${B.cyan}Plan: ${t.task}${B.reset}`),s.push(`${B.dim}Status: ${e[t.status]||t.status}${B.reset}
|
|
291
291
|
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${B.green}\u2713${B.reset}`;break;case"in_progress":r=`${B.blue}\u2192${B.reset}`;break;case"skipped":r=`${B.dim}\u25CB${B.reset}`;break;default:r=`${B.dim} ${B.reset}`}s.push(` ${r} ${B.bold}Step ${n+1}:${B.reset} ${o.description}`),o.files.length>0&&s.push(` ${B.dim}Files: ${o.files.join(", ")}${B.reset}`)}return s.push(""),s.join(`
|
|
292
|
-
`)}function
|
|
292
|
+
`)}function sp(t){if(t||(t=re),!t)return null;rc();let e=rs.join(is(),`${t.name}.json`);return dt.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function op(t){let e=rs.join(is(),`${t}.json`);if(!dt.existsSync(e))return null;try{let s=JSON.parse(dt.readFileSync(e,"utf-8"));return re=s,s}catch{return null}}function rp(){rc();let t=is(),e=dt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(dt.readFileSync(rs.join(t,n),"utf-8"));s.push({name:o.name,task:o.task,status:o.status,steps:o.steps?o.steps.length:0,createdAt:o.createdAt})}catch{}return s.sort((n,o)=>(o.createdAt||"").localeCompare(n.createdAt||""))}function ip(t){To=t}function ap(){return To}function cp(){re=null,Co=!1,To=null}function lp(){return`
|
|
293
293
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
294
294
|
|
|
295
295
|
# Allowed Tools (read-only)
|
|
296
|
-
You may ONLY use these tools: ${[...
|
|
296
|
+
You may ONLY use these tools: ${[...oc].join(", ")}
|
|
297
297
|
Any other tool call will be blocked and returned with an error.
|
|
298
298
|
|
|
299
299
|
# Analysis Phase
|
|
@@ -324,42 +324,42 @@ Bullet list of potential issues and mitigations.
|
|
|
324
324
|
# Important
|
|
325
325
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
326
326
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
327
|
-
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var
|
|
328
|
-
`),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${y.dim}${"\u2500".repeat(40)}${y.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let i=o?` ${o} `:"";s.push(`${y.dim}${"\u2500".repeat(3)}${i}${"\u2500".repeat(Math.max(0,37-i.length))}${y.reset}`)}continue}if(n){s.push(` ${
|
|
329
|
-
`)}function ft(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function mt(t){return t?t.replace(/`([^`]+)`/g,`${y.cyan}$1${y.reset}`).replace(/\*\*([^*]+)\*\*/g,`${y.bold}$1${y.reset}`).replace(/\*([^*]+)\*/g,`${y.dim}$1${y.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${y.cyan}$1${y.reset} ${y.dim}($2)${y.reset}`):""}function
|
|
330
|
-
`)}function
|
|
327
|
+
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var ic=["interactive","semi-auto","autonomous"],ac="interactive";function up(t){return ic.includes(t)?(ac=t,!0):!1}function dp(){return ac}cc.exports={createPlan:Ym,getActivePlan:Xm,setPlanMode:Vm,isPlanMode:Qm,approvePlan:Zm,startExecution:ep,updateStep:tp,formatPlan:np,savePlan:sp,loadPlan:op,listPlans:rp,clearPlan:cp,getPlanModePrompt:lp,setPlanContent:ip,getPlanContent:ap,PLAN_MODE_ALLOWED_TOOLS:oc,setAutonomyLevel:up,getAutonomyLevel:dp,AUTONOMY_LEVELS:ic}});var yc=N((R$,$c)=>{var{C:y}=oe();function fp(t){if(!t)return"";let e=t.split(`
|
|
328
|
+
`),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${y.dim}${"\u2500".repeat(40)}${y.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let i=o?` ${o} `:"";s.push(`${y.dim}${"\u2500".repeat(3)}${i}${"\u2500".repeat(Math.max(0,37-i.length))}${y.reset}`)}continue}if(n){s.push(` ${Ao(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${y.bold}${y.cyan} ${ft(r.substring(4))}${y.reset}`);continue}if(r.startsWith("## ")){s.push(`${y.bold}${y.cyan} ${ft(r.substring(3))}${y.reset}`);continue}if(r.startsWith("# ")){s.push(`${y.bold}${y.cyan}${ft(r.substring(2))}${y.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let i=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,"");s.push(`${i}${y.cyan}\u2022${y.reset} ${mt(c)}`);continue}if(/^\s*\d+\.\s/.test(r)){let i=r.match(/^(\s*)(\d+)\.\s(.*)/);if(i){s.push(`${i[1]}${y.cyan}${i[2]}.${y.reset} ${mt(i[3])}`);continue}}s.push(mt(r))}return s.join(`
|
|
329
|
+
`)}function ft(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function mt(t){return t?t.replace(/`([^`]+)`/g,`${y.cyan}$1${y.reset}`).replace(/\*\*([^*]+)\*\*/g,`${y.bold}$1${y.reset}`).replace(/\*([^*]+)\*/g,`${y.dim}$1${y.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${y.cyan}$1${y.reset} ${y.dim}($2)${y.reset}`):""}function Ao(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,`${y.yellow}$1${y.reset}`),r=r.replace(e,`${y.magenta}$1${y.reset}`),r=r.replace(s,`${y.green}$&${y.reset}`),r=r.replace(n,`${y.dim}$1${y.reset}`),r}function uc(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${y.cyan}$1${y.reset}`),r=r.replace(e,`$1${y.green}$2${y.reset}`),r=r.replace(n,`${y.yellow}$&${y.reset}`),r=r.replace(o,`${y.dim}$1${y.reset}`),r}function 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,`${y.cyan}$1${y.reset}:`),r=r.replace(s,`: ${y.green}$1${y.reset}`),r=r.replace(n,`: ${y.yellow}$1${y.reset}`),r=r.replace(o,`: ${y.magenta}$1${y.reset}`),r}function 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,`${y.yellow}$1${y.reset}`),i=i.replace(e,`${y.magenta}$1${y.reset}`),i=i.replace(r,`${y.cyan}$1${y.reset}`),i=i.replace(s,`${y.green}$&${y.reset}`),i=i.replace(n,`${y.dim}$1${y.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,`${y.yellow}$1${y.reset}`),i=i.replace(s,`${y.cyan}$1${y.reset}`),i=i.replace(e,`${y.magenta}$1${y.reset}`),i=i.replace(n,`${y.green}$&${y.reset}`),i=i.replace(o,`${y.dim}$1${y.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,`${y.yellow}$1${y.reset}`),c=c.replace(s,`${y.cyan}$1${y.reset}`),c=c.replace(e,`${y.magenta}$1${y.reset}`),c=c.replace(i,`${y.yellow}$1${y.reset}`),c=c.replace(n,`${y.green}$&${y.reset}`),c=c.replace(o,`${y.dim}$1${y.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,`${y.yellow}$1${y.reset}`),c=c.replace(o,`${y.yellow}$1${y.reset}`),c=c.replace(e,`$1${y.cyan}$2${y.reset}:`),c=c.replace(n,`$1${y.magenta}$&${y.reset}`),c=c.replace(r,`${y.dim}$1${y.reset}`),c}function 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,`${y.dim}$1${y.reset}`),i=i.replace(n,`${y.green}$&${y.reset}`),i=i.replace(e,`<${y.magenta}$1${y.reset}`),i=i.replace(s,` ${y.cyan}$1${y.reset}=`),i=i.replace(r,`${y.yellow}$1${y.reset}`),i}function mp(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)=>` ${y.bold}${i.padEnd(s[c])}${y.reset} `).join("\u2502"),r=[];r.push(`${y.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${y.reset}`),r.push(`${y.dim}\u2502${y.reset}${o}${y.dim}\u2502${y.reset}`),r.push(`${y.dim}\u251C${n}\u2524${y.reset}`);for(let i of e){let c=t.map((l,u)=>` ${(i[u]||"").padEnd(s[u])} `).join(`${y.dim}\u2502${y.reset}`);r.push(`${y.dim}\u2502${y.reset}${c}${y.dim}\u2502${y.reset}`)}return r.push(`${y.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${y.reset}`),r.join(`
|
|
330
|
+
`)}function pp(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),i=n-r,c=o>=100?y.green:o>50?y.yellow:y.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${y.dim}${"\u2591".repeat(i)}${y.reset} ${o}% (${e}/${s})`}var Ro=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{process.stdout.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}_cursorWrite(e){try{process.stderr.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),80))}_renderCursor(){let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],s=e[this._cursorFrame%e.length];this._cursorWrite(`\x1B[2K\r\x1B[36m${s}\x1B[0m`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let s;for(;(s=this.buffer.indexOf(`
|
|
331
331
|
`))!==-1;){let n=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(n)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),120))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${y.dim}${"\u2500".repeat(40)}${y.reset}
|
|
332
332
|
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${y.dim}${"\u2500".repeat(40)}${y.reset}
|
|
333
333
|
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${y.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${y.reset}
|
|
334
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
334
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${Ao(e,this.codeBlockLang)}
|
|
335
335
|
`);return}if(e.startsWith("### ")){this._safeWrite(`${y.bold}${y.cyan} ${ft(e.substring(4))}${y.reset}
|
|
336
336
|
`);return}if(e.startsWith("## ")){this._safeWrite(`${y.bold}${y.cyan} ${ft(e.substring(3))}${y.reset}
|
|
337
337
|
`);return}if(e.startsWith("# ")){this._safeWrite(`${y.bold}${y.cyan}${ft(e.substring(2))}${y.reset}
|
|
338
338
|
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${y.cyan}\u2022${y.reset} ${mt(n)}
|
|
339
339
|
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${y.cyan}${s[2]}.${y.reset} ${mt(s[3])}
|
|
340
340
|
`);return}}this._safeWrite(`${mt(e)}
|
|
341
|
-
`)}}
|
|
341
|
+
`)}};$c.exports={renderMarkdown:fp,renderInline:mt,stripHeadingMarkers:ft,highlightCode:Ao,highlightJS:lc,highlightBash:uc,highlightJSON:dc,highlightPython:fc,highlightGo:mc,highlightRust:pc,highlightCSS:hc,highlightHTML:gc,renderTable:mp,renderProgress:pp,StreamRenderer:Ro}});var No=N((A$,_c)=>{var{execSync:hp}=require("child_process"),Oo=require("path"),dn=require("fs"),Mo=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function wc(){return Oo.join(process.cwd(),".nex","hooks")}function gp(){return Oo.join(process.cwd(),".nex","config.json")}function bc(){let t=gp();if(!dn.existsSync(t))return{};try{return JSON.parse(dn.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function as(t){if(!Mo.includes(t))return[];let e=[],s=wc(),n=Oo.join(s,t);dn.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:hp(t,{cwd:process.cwd(),encoding:"utf-8",timeout:s,env:{...process.env,...e},stdio:["pipe","pipe","pipe"]}).trim()}}catch(n){return{success:!1,error:n.stderr?n.stderr.trim():n.message}}}function $p(t,e={}){let s=as(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 yp(t){return as(t).length>0}function wp(){let t=[];for(let e of Mo){let s=as(e);s.length>0&&t.push({event:e,commands:s})}return t}function bp(){let t=wc();return dn.existsSync(t)||dn.mkdirSync(t,{recursive:!0}),t}_c.exports={HOOK_EVENTS:Mo,loadHookConfig:bc,getHooksForEvent:as,executeHook:xc,runHooks:$p,hasHooks:yp,listHooks:wp,initHooksDir:bp}});var ce=N((N$,Lc)=>{var{C:_,Spinner:Mt,TaskProgress:xp,formatToolCall:_p,formatResult:kp,formatToolSummary:Tc,formatSectionHeader:vp,setActiveTaskProgress:O$}=oe(),{callStream:Sp}=ge(),{parseToolArgs:Ep}=An(),{executeTool:Cp}=Ue(),{gatherProjectContext:Tp}=bo(),{fitToContext:Rp,forceCompress:Po,getUsage:Ap,estimateTokens:Op}=Re(),{autoSave:pt}=lt(),{getMemoryContext:Mp}=Qe(),{checkPermission:Np,setPermission:Pp,savePermissions:Lp}=un(),{confirm:Rc,setAllowAlwaysHandler:Ip}=Me(),{isPlanMode:ds,getPlanModePrompt:qp,PLAN_MODE_ALLOWED_TOOLS:Ac,setPlanContent:jp}=Ot(),{StreamRenderer:Dp}=yc(),{runHooks:kc}=No(),{routeMCPCall:Fp,getMCPToolDefinitions:Up}=Ln(),{getSkillInstructions:Wp,getSkillToolDefinitions:Bp,routeSkillCall:Hp}=Gt(),{trackUsage:Gp}=_t(),{validateToolArgs:zp}=Hs(),{filterToolsForModel:vc,getModelTier:Kp,PROVIDER_DEFAULT_TIER:M$}=no(),{getConfiguredProviders:Jp,getActiveProviderName:fn,getActiveModelId:Wo,setActiveModel:Sc,MODEL_EQUIVALENTS:fs}=ge(),Go=require("fs"),zo=require("path"),Ec=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function Yp(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||""):zo.resolve(n);Go.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Xp(t){let e=Go.readFileSync(t),s=zo.extname(t).toLowerCase().replace(".",""),n=s==="jpg"||s==="jpeg"?"image/jpeg":s==="png"?"image/png":s==="gif"?"image/gif":s==="webp"?"image/webp":"image/png";return{data:e.toString("base64"),media_type:n}}function Oc(t){let e=Yp(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}=Xp(n.abs);s.push({type:"image",media_type:r,data:o})}catch{}return s.length>1?s:t}var Lo=null,Io=null,qo=null;function Nt(){if(Lo===null){let{TOOL_DEFINITIONS:t}=Ue();Lo=t}return Io===null&&(Io=Bp()),qo===null&&(qo=Up()),[...Lo,...Io,...qo]}var Bo=50;function Vp(t){Number.isFinite(t)&&t>0&&(Bo=t)}var cs=()=>null;function Qp(t){cs=t}var mn=null,Ho=null,Pt=null,ls=new Map,Zp=1e4,eh=6e3,th=/\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 nh(t){return!t||typeof t!="string"?t:t.replace(th,(e,s)=>`${s}=***REDACTED***`)}function sh(t){let e=nh(t);if(Op(e)>Zp)try{let{compressToolResult:n}=Re();return n(e,eh)}catch{return e}return e}function Mc(t){try{let{getActiveModel:e}=ge(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(ls.has(n))return ls.get(n);let o=vc(t);return ls.set(n,o),o}catch{return vc(t)}}function oh(){ls.clear()}async function Nc(){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}=Qe(),i=r();i&&o.push(`memory:${i}`)}catch{}try{let r=e.join(process.cwd(),".nex","brain");if(Go.existsSync(r)){let i=await t.stat(r);o.push(`brain:${i.mtimeMs}`)}}catch{}return o.join("|")}catch{return`fallback:${Date.now()}`}}function rh(){mn=null,Ho=null,Pt=null}var ih=new Set(["spawn_agents"]),jo=5,Do=3,Fo=2,ah=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),ch=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10),lh=process.env.NEX_STALE_AUTO_SWITCH!=="0";function uh(t){try{let e=require("fs"),s=require("path"),n=s.join(process.cwd(),".nex","plans");e.existsSync(n)||e.mkdirSync(n,{recursive:!0});let o=s.join(n,"current-plan.md");e.writeFileSync(o,t,"utf-8")}catch{}}Ip(t=>{Pp(t,"allow"),Lp(),console.log(`${_.green} \u2713 ${t}: always allow${_.reset}`)});async function dh(t){let e=t.function.name,s=Ep(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let l=Nt().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
342
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
343
343
|
|
|
344
344
|
Expected JSON schema for "${e}":
|
|
345
345
|
${u}
|
|
346
346
|
|
|
347
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=
|
|
348
|
-
`)[0]}${_.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(
|
|
347
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=zp(e,s);if(!o.valid)return console.log(`${_.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
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(ds()&&!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=Np(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 fh(t,e,s={}){let n=await Hp(t,e);if(n!==null)return n;let o=await Fp(t,e);return o!==null?o:Cp(t,e,s)}function mh(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 Uo(t,e=!1){e||console.log(_p(t.fnName,t.args)),kc("pre-tool",{tool_name:t.fnName});let s=await fh(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(s??""),o=n.length>5e4?n.substring(0,5e4)+`
|
|
349
349
|
...(truncated ${n.length-5e4} chars)`:n,r=o.split(`
|
|
350
|
-
`)[0],i=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),c=
|
|
351
|
-
`)}function
|
|
350
|
+
`)[0],i=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),c=Tc(t.fnName,t.args,o,i);return e||(console.log(kp(o)),console.log(c)),kc("post-tool",{tool_name:t.fnName}),{msg:{role:"tool",content:sh(o),tool_call_id:t.callId},summary:c}}async function ph(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=mh(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 Mt(u),i.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await Uo(t[l],e);n[l]=u,o.push(d)}else{let l=r.map(d=>Uo(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(Tc(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(ih.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await Uo(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=[],Cc=300,us=[];function hh(t){us.push(t.trim())}function gh(){return us.length===0?null:us.splice(0,us.length).join(`
|
|
351
|
+
`)}function $h(){let t=process.env.NEX_LANGUAGE,e=process.env.NEX_CODE_LANGUAGE,s=process.env.NEX_COMMIT_LANGUAGE,n=!t||t==="auto"?null:t,o=[`# Language Rules (CRITICAL \u2014 enforce strictly)
|
|
352
352
|
`];n?o.push(`RESPONSE LANGUAGE: You MUST always respond in ${n}. This overrides any language defaults from your training. Never output Chinese, Japanese, or any other language in your responses \u2014 even when summarizing or thinking. ${n} only.`):o.push("RESPONSE LANGUAGE: Always respond in the same language as the user's message. If the user writes in German, respond in German; if in English, respond in English; etc."),o.push("CODE EXAMPLES: Always show actual, working code examples \u2014 never pseudocode or placeholder snippets."),o.push("COMPLETENESS RULES:"),o.push(" \u2022 ALWAYS show actual code when explaining implementations \u2014 never describe without showing"),o.push(" \u2022 Include complete examples with full context (imports, function signatures, error handling)"),o.push(' \u2022 Show alternative approaches when relevant (e.g., "Alternative: use util.promisify instead")'),o.push(" \u2022 Include edge cases in explanations (empty input, null values, boundary conditions)"),o.push(" \u2022 Provide platform-specific guidance when commands differ by OS (Linux/macOS/Windows)"),o.push(" \u2022 For Makefiles, always display the actual .PHONY declarations and dependency chains"),o.push(" \u2022 For dataclasses, always show the complete class definition with field types and defaults");let r=e||(n?"English":null);r&&o.push(`CODE LANGUAGE: Write all code comments, docstrings, variable descriptions, and inline documentation in ${r}.`);let i=s||(n?"English":null);return i&&o.push(`COMMIT MESSAGES: Write all git commit messages in ${i}.`),n&&o.push(`
|
|
353
353
|
This is a hard requirement. Do NOT fall back to English or any other language for your responses, even if the user writes in a different language first.`),o.join(`
|
|
354
354
|
`)+`
|
|
355
355
|
|
|
356
|
-
`}function
|
|
356
|
+
`}function yh(){if(Pt!==null)return Pt;try{let e=Jp().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:Kp(r.id,o.name),name:r.name})));if(e.length<2)return Pt="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
|
|
357
357
|
# Sub-Agent Model Routing
|
|
358
358
|
|
|
359
359
|
`;n+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',n+=`| Model | Tier | Auto-assigned for |
|
|
360
360
|
|---|---|---|
|
|
361
361
|
`;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
|
|
362
|
-
`;return
|
|
362
|
+
`;return Pt=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Pt="",""}}async function Pc(){let t=await Nc();if(mn!==null&&t===Ho)return mn;let e=await Tp(process.cwd()),s=Mp(),n=Wp(),o=ds()?qp():"",r=$h();return mn=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
|
|
363
363
|
|
|
364
364
|
WORKING DIRECTORY: ${process.cwd()}
|
|
365
365
|
All relative paths resolve from this directory.
|
|
@@ -480,7 +480,7 @@ When performing audits, code reviews, bug hunts, or security reviews:
|
|
|
480
480
|
- Good for: reading multiple files, analyzing separate modules.
|
|
481
481
|
- Bad for: tasks that depend on each other or modify the same file.
|
|
482
482
|
- Max 5 parallel agents.
|
|
483
|
-
${
|
|
483
|
+
${yh()}
|
|
484
484
|
|
|
485
485
|
# Edit Reliability (Critical)
|
|
486
486
|
|
|
@@ -531,19 +531,19 @@ You have access to a persistent knowledge base in .nex/brain/.
|
|
|
531
531
|
- Include tags in frontmatter for better retrieval
|
|
532
532
|
- The user reviews all brain writes via /brain review or git diff
|
|
533
533
|
|
|
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} ${
|
|
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
|
-
`),
|
|
534
|
+
`,Ho=t,mn}function wh(){ee=[]}function bh(){ee.length>Cc&&ee.splice(0,ee.length-Cc)}function xh(){return ee.length}function _h(){return ee}function kh(t){ee=t}async function vh(){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(`
|
|
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=zo.join(s,"package.json");if(e.existsSync(d))try{let f=JSON.parse(e.readFileSync(d,"utf-8")),m=Object.keys({...f.dependencies||{},...f.devDependencies||{}});if(m.length>0){let h=m.slice(0,5).join(" \xB7 "),p=m.length>5?` +${m.length-5}`:"";u+=`
|
|
536
|
+
\u{1F4E6} ${h}${p}`}}catch{}return u}function ht(t,e,s,n,o){if(t<1)return;let r=[...e.values()].reduce((c,l)=>c+l,0),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(`
|
|
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 Sh(){if(!process.stdout.isTTY)return{action:"quit"};let t=fn(),e=Wo(),s=fs.fast?.[t],n=fs.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}
|
|
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 Eh(t){let e=Oc(t);ee.push({role:"user",content:e}),bh();let{setOnChange:s}=Gn(),n=null,o=0;s((de,A)=>{de==="create"?(n&&n.stop(),n=new xp(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}=sn(),A=await de(t);A&&(i=r+`
|
|
539
539
|
`+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),ht(S,T,F,I,V),pt(ee);return}S++,S>1&&(A=!1);for(let E of nt){let j=E.function.name;T.set(j,(T.get(j)||0)+1)}let
|
|
542
|
-
${_.yellow}\u26A0 Max iterations reached.${_.reset}`),await
|
|
543
|
-
`),await t(c,i,d)}catch(u){if(s=u,
|
|
540
|
+
`)}catch(de){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",de.message)}let c=[{role:"system",content:i},...ee],l=new Mt("Thinking...");l.start();let d=ee.length===1?vh().catch(()=>null):Promise.resolve(null),f=Nt(),[{messages:m,compressed:h,compacted:p,tokensRemoved:g},w]=await Promise.all([Rp(c,f),d]),$=Ap(c,f);if(l.stop(),w&&console.log(`${_.dim}${w}${_.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,C=0,S=0,T=new Map,F=new Set,I=new Set,V=Date.now(),D,ne=Bo,ie=0,ue=10;e:for(;;){for(D=0;D<ne&&!cs()?.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 Mt(E),L.start()}let se=!0,z="",q=new Dp,U,H=Date.now(),ae=!1,je=new AbortController,gt=setInterval(()=>{let E=Date.now()-H;if(E>=ch)q._clearCursorLine(),console.log(`${_.yellow} \u26A0 Stream stale for ${Math.round(E/1e3)}s \u2014 aborting and retrying${_.reset}`),je.abort();else if(E>=ah&&!ae){ae=!0,q._clearCursorLine();let j=fs.fast?.[fn()];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=Mc(Nt()),j=ds()?E.filter(pe=>Ac.has(pe.function.name)):E,$t=cs(),W=new AbortController;$t&&$t.addEventListener("abort",()=>W.abort(),{once:!0}),je.signal.addEventListener("abort",()=>W.abort(),{once:!0}),U=await Sp(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(gt),ke&&(clearTimeout(ke),ke=null),me&&q&&(q.push(me),me=""),n&&!n._paused&&n.pause(),L&&L.stop(),q.stopCursor(),je.signal.aborted&&!cs()?.aborted){if(v++,v>Fo){if(C<1){C++,console.log(`${_.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${_.reset}`);let jt=Nt(),{messages:Dt,tokensRemoved:yt}=Po(x,jt);x=Dt,console.log(`${_.dim} [force-compressed \u2014 ~${yt} tokens freed]${_.reset}`),v=0,D--;continue}n&&(n.stop(),n=null);let he=await Sh();if(he.action==="quit"){s(null),ht(S,T,F,I,V),pt(ee);break}he.action==="switch"&&(Sc(`${he.provider}:${he.model}`),console.log(`${_.green} \u2713 Switched to ${he.provider}:${he.model}${_.reset}`)),v=0,C=0,D--;continue}let W=v===1?3e3:5e3;if(v>=2&&C<1){C++,console.log(`${_.yellow} \u26A0 Stale retry ${v}/${Fo} \u2014 force-compressing before retry...${_.reset}`);let he=Nt(),{messages:jt,tokensRemoved:Dt}=Po(x,he);if(x=jt,console.log(`${_.dim} [force-compressed \u2014 ~${Dt} tokens freed]${_.reset}`),lh){let yt=fs.fast?.[fn()];yt&&yt!==Wo()&&(Sc(`${fn()}:${yt}`),console.log(`${_.cyan} \u26A1 Auto-switched to ${yt} 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}/${Fo} \u2014 retrying in ${W/1e3}s...${_.reset}`);let pe=new Mt(`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),ht(S,T,F,I,V),pt(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&&C<1){C++,console.log(`${_.yellow} \u26A0 Context too long \u2014 force-compressing and retrying...${_.reset}`);let he=Nt(),{messages:jt,tokensRemoved:Dt}=Po(x,he);x=jt,console.log(`${_.dim} [force-compressed \u2014 ~${Dt} 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>jo){console.log(`${_.red} Rate limit: max retries (${jo}) exceeded. Try again later or use /budget to check your limits.${_.reset}`),n&&(n.stop(),n=null),s(null),ht(S,T,F,I,V),pt(ee);break}let W=Math.min(1e4*Math.pow(2,O-1),12e4),pe=new Mt(`Rate limit \u2014 waiting ${Math.round(W/1e3)}s (retry ${O}/${jo})`);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>Do){console.log(`${_.red} Network error: max retries (${Do}) exceeded. Check your connection and try again.${_.reset}`),n&&(n.stop(),n=null),s(null),ht(S,T,F,I,V),pt(ee);break}let W=Math.min(2e3*Math.pow(2,k-1),3e4),pe=new Mt(`Network error \u2014 retrying in ${Math.round(W/1e3)}s (${k}/${Do})`);pe.start(),await new Promise(he=>setTimeout(he,W)),pe.stop(),D--;continue}n&&(n.stop(),n=null),s(null),ht(S,T,F,I,V),pt(ee);break}clearInterval(gt),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&&(Gp(fn(),Wo(),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:$s,tool_calls:nt}=U,ys={role:"assistant",content:$s||""};if(nt&&nt.length>0&&(ys.tool_calls=nt),ee.push(ys),x.push(ys),!nt||nt.length===0){let E=($s||"").trim().length>0||z.trim().length>0;if(!E&&S>0&&D<Bo-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(ds()&&E){let j=($s||z||"").trim();jp(j),uh(j),console.log(`
|
|
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),ht(S,T,F,I,V),pt(ee);return}S++,S>1&&(A=!1);for(let E of nt){let j=E.function.name;T.set(j,(T.get(j)||0)+1)}let $n=await Promise.all(nt.map(E=>dh(E))),ws=n?{skipSpinner:!0,skipSummaries:!0}:{},fr=!ws.skipSummaries&&!A;fr&&(A=!0),n&&n._paused&&n.resume();let{results:mr,summaries:yn}=await ph($n,!0,{...ws,skipSummaries:!0});if(!ws.skipSummaries)if(fr){let E=vp($n,S);if(yn.length===1)console.log(E+yn[0]);else{console.log(E);for(let j of yn)console.log(j)}}else for(let E of yn)console.log(E);for(let E=0;E<$n.length;E++){let j=$n[E];if(!j.canExecute)continue;let $t=mr[E].content,W=!$t.startsWith("ERROR")&&!$t.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 mr)ee.push(E),x.push(E);let pr=gh();if(pr){let E={role:"user",content:`[User note mid-run]: ${pr}`};ee.push(E),x.push(E),console.log(`${_.cyan} \u270E Kontext hinzugef\xFCgt${_.reset}`)}}if(D>=ne){n&&(n.stop(),n=null),s(null),ht(S,T,F,I,V),pt(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(`
|
|
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:Eh,clearConversation:wh,getConversationLength:xh,getConversationMessages:_h,setConversationMessages:kh,setAbortSignalGetter:Qp,setMaxIterations:Vp,invalidateSystemPromptCache:rh,clearToolFilterCache:oh,getCachedFilteredTools:Mc,buildSystemPrompt:Pc,getProjectContextHash:Nc,buildUserContent:Oc,injectMidRunNote:hh}});var ge=N((P$,Fc)=>{var{OllamaProvider:Ch}=Mr(),{OpenAIProvider:Th}=Yr(),{AnthropicProvider:Rh}=Zr(),{GeminiProvider:Ah}=si(),{LocalProvider:Oh}=ii(),{checkBudget:Mh}=_t(),Ko={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(Ko))for(let s of Object.values(e))Ic[s]=t;function qc(t,e){let s=Ic[t];return s&&Ko[s][e]||t}var fe={},_e=null,le=null,pn=[];function Te(){if(Object.keys(fe).length>0)return;Lt("ollama",new Ch),Lt("openai",new Th),Lt("anthropic",new Rh),Lt("gemini",new Ah),Lt("local",new Oh);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&&(pn=s.split(",").map(n=>n.trim()).filter(Boolean))}function Lt(t,e){fe[t]=e}function Nh(t){return Te(),fe[t]||null}function Jo(){return Te(),fe[_e]||null}function Ph(){return Te(),_e}function Lh(){return Te(),le}function Ih(){Te();let t=Jo();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 qh(t){Te();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,ms(),!0):!1}let n=Jo();if(n&&n.getModel(s))return le=s,ms(),!0;for(let[o,r]of Object.entries(fe))if(r.getModel(s))return _e=o,le=s,ms(),!0;return!1}function ms(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=ce();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Re();t()}catch{}}function jh(){Te();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 Dh(){return Te(),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 Fh(){Te();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 Uh(t){pn=Array.isArray(t)?t:[]}function Wh(){return[...pn]}function Bh(t){let e=t.message||"",s=t.code||"";return!!(e.includes("429")||e.includes("500")||e.includes("502")||e.includes("503")||e.includes("504")||s==="ECONNABORTED"||s==="ETIMEDOUT"||s==="ECONNREFUSED"||s==="ECONNRESET"||s==="EHOSTUNREACH"||s==="ENETUNREACH"||s==="EPIPE"||s==="ERR_SOCKET_CONNECTION_TIMEOUT"||e.includes("socket disconnected")||e.includes("TLS")||e.includes("ECONNRESET")||e.includes("ECONNABORTED")||e.includes("network")||e.includes("ETIMEDOUT"))}async function Dc(t){let e=[_e,...pn.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=Mh(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}]
|
|
543
|
+
`),await t(c,i,d)}catch(u){if(s=u,Bh(u)&&r<e.length-1)continue;throw u}}throw n>0&&n===o?new Error("All providers are over budget. Use /budget to check limits or /budget <provider> off to remove a limit."):o===0?new Error("No configured provider available"):s||new Error("No configured provider available")}async function Hh(t,e,s={}){return Te(),Dc((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function Gh(t,e,s={}){if(Te(),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 zh(){Te();let t=[];for(let[e,s]of Object.entries(fe))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function Kh(){for(let t of Object.keys(fe))delete fe[t];_e=null,le=null,pn=[]}Fc.exports={registerProvider:Lt,getProvider:Nh,getActiveProvider:Jo,getActiveProviderName:Ph,getActiveModelId:Lh,getActiveModel:Ih,setActiveModel:qh,getModelNames:jh,parseModelSpec:jc,listProviders:Dh,listAllModels:Fh,callStream:Hh,callChat:Gh,getConfiguredProviders:zh,setFallbackChain:Uh,getFallbackChain:Wh,resolveModelForProvider:qc,MODEL_EQUIVALENTS:Ko,_reset:Kh}});var Wc=N((L$,Uc)=>{"use strict";var Jh="\x1B[2m",Yh="\x1B[0m";function Xh(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Yo=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 Jh+"\u2500".repeat(this._cols)+Yh}drawFooter(e){!this._origWrite||this._drawing||(this._drawing=!0,this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K"+this._statusLine(e)+"\x1B8"),this._drawing=!1)}_setScrollRegion(){let e=Math.max(1,this._scrollEnd);this._origWrite(`\x1B[1;${e}r`)}_clearScrollRegion(){this._origWrite&&this._origWrite("\x1B[r")}_eraseStatus(){this._origWrite&&this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K\x1B8")}activate(e){if(!process.stdout.isTTY)return;this._rl=e,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let s=this,n=process.stdout.write.bind(process.stdout);this._origWrite=n,process.stdout.write=function(l,...u){if(s._active&&typeof l=="string"){if(s._cursorOnInputRow){let f=l.replace(/\n/g,"");return f?n(f,...u):!0}let d=(l.match(/\n/g)||[]).length;d>0&&(s._lastOutputRow=Math.min(s._lastOutputRow+d,s._scrollEnd))}return n(l,...u)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(l,...u){if(!s._active)return s._origStderrWrite(l,...u);if(typeof l=="string"&&l.includes("\r")){let d=Math.min(s._lastOutputRow+1,s._scrollEnd);s._origWrite(s._goto(d))}return s._origStderrWrite(l,...u)},this._origLog=console.log,this._origError=console.error;function o(...l){if(!s._active){s._origLog(...l);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origLog(...l),s.drawFooter()}function r(...l){if(!s._active){s._origError(...l);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origError(...l),s.drawFooter()}console.log=o,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(l){s._origSetPr(l),s._active&&s.drawFooter(l)},this._origPrompt=e.prompt.bind(e),e.prompt=function(l){if(!s._active)return s._origPrompt(l);e._prevPos=null,s._origWrite(s._goto(s._rowInput)),s._origPrompt(l),s._cursorOnInputRow=!0};let i=e._refreshLine?e._refreshLine.bind(e):null;this._origRefreshLine=i,i&&(e._refreshLine=function(){if(!s._active)return i();let l=s._cols,u=Xh(e._prompt||""),d=l-u-1;if(e.line.length<=d)return i();let f=e.line,m=e.cursor,h=Math.max(1,d-1),g=Math.max(0,m-h),w=(g>0?"\xAB":"")+f.slice(g,g+h+(g>0?0:1));e.line=w,e.cursor=w.length,i(),e.line=f,e.cursor=m}),e.on("line",l=>{s._active&&(s._cursorOnInputRow=!1,s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s.drawFooter())});let c=()=>{this._setScrollRegion(),this.drawFooter()};process.stdout.on("resize",c),this._offResize=()=>process.stdout.off("resize",c)}deactivate(){this._active&&(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine&&(this._rl._refreshLine=this._origRefreshLine,this._origRefreshLine=null)),this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null)}};Uc.exports={StickyFooter:Yo}});var Gc=N((I$,Hc)=>{var{C:J}=oe(),{listProviders:Vh,getActiveProviderName:Qh,getActiveModelId:Zh,setActiveModel:eg}=ge();function Bc(t,e,s={}){let{title:n="Select",hint:o="\u2191\u2193 navigate \xB7 Enter select \xB7 Esc cancel"}=s;return new Promise(r=>{let 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
|
|
544
544
|
`);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 C=e[v];if(C.isHeader){$.push(` ${J.bold}${J.dim}${C.label}${J.reset}`);continue}let S=i[l]===v,T=S?`${J.cyan}> `:" ",F=C.isCurrent?` ${J.yellow}<current>${J.reset}`:"";S?$.push(`${T}${J.bold}${C.label}${J.reset}${F}`):$.push(`${T}${J.dim}${C.label}${J.reset}${F}`)}O<e.length&&$.push(` ${J.dim}\u2193 more${J.reset}`);let k=$.join(`
|
|
545
545
|
`);process.stdout.write(k+`
|
|
546
|
-
`),m=$.length}t.pause();let
|
|
546
|
+
`),m=$.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",w),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function w($,x){if(x){if(x.name==="up"||x.ctrl&&x.name==="p"){l>0&&(l--,h());return}if(x.name==="down"||x.ctrl&&x.name==="n"){l<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",w),h()})}async function tg(t){let e=Vh(),s=Qh(),n=Zh(),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 Bc(t,o,{title:"Select Model"});return r?(eg(r),console.log(`${J.green}Switched to ${r}${J.reset}`),!0):(console.log(`${J.dim}Cancelled${J.reset}`),!1)}Hc.exports={pickFromList:Bc,showModelPicker:tg}});var Qo=N((j$,Qc)=>{var Xo=require("fs"),ng=require("path"),{callChat:zc}=ge(),{remember:sg,listMemories:q$,recall:og}=Qe(),Vo=4,rg=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
547
547
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
548
548
|
|
|
549
549
|
Return ONLY valid JSON in this exact format:
|
|
@@ -569,15 +569,15 @@ Rules:
|
|
|
569
569
|
- value: concise actionable instruction, max 120 chars
|
|
570
570
|
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
571
571
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
572
|
-
- Return ONLY the JSON, no markdown, no explanation`;function
|
|
572
|
+
- Return ONLY the JSON, no markdown, no explanation`;function Kc(t){return t.filter(e=>(e.role==="user"||e.role==="assistant")&&typeof e.content=="string"&&e.content.trim().length>10).slice(-40).map(e=>`[${e.role.toUpperCase()}]: ${e.content.substring(0,700)}`).join(`
|
|
573
573
|
|
|
574
|
-
`)}async function
|
|
574
|
+
`)}async function Jc(t){if(t.filter(o=>o.role==="user").length<Vo)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=Kc(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=[{role:"system",content:rg},{role:"user",content:`Conversation to analyze:
|
|
575
575
|
|
|
576
|
-
${s}`}];try{let i=((await
|
|
576
|
+
${s}`}];try{let i=((await zc(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 Yc(t){let e=[];for(let{key:s,value:n}of t||[]){if(!s||!n||typeof s!="string"||typeof n!="string")continue;let o=s.trim().replace(/\s+/g,"-").substring(0,60),r=n.trim().substring(0,200);if(!o||!r)continue;let i=og(o);i!==r&&(sg(o,r),e.push({key:o,value:r,action:i?"updated":"added"}))}return e}function Xc(t){if(!t||t.length===0)return[];let e=ng.join(process.cwd(),"NEX.md"),s="";try{Xo.existsSync(e)&&(s=Xo.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(`
|
|
577
577
|
`)?o+i:o+`
|
|
578
578
|
`+i:i)}return n.length>0&&(o.endsWith(`
|
|
579
579
|
`)||(o+=`
|
|
580
|
-
`),
|
|
580
|
+
`),Xo.writeFileSync(e,o,"utf-8")),n}async function ig(t){let e=await Jc(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=Yc(e.memories),n=Xc(e.nex_additions);return{applied:s,nexAdded:n,summary:e.summary}}var ag=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
581
581
|
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
582
582
|
|
|
583
583
|
Return ONLY valid JSON in this exact format:
|
|
@@ -611,37 +611,37 @@ Rules:
|
|
|
611
611
|
---
|
|
612
612
|
- Maximum 3 documents per session. Quality over quantity.
|
|
613
613
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
614
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function
|
|
614
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function Vc(t){if(t.filter(o=>o.role==="user").length<Vo)return{documents:[],skip_reason:"Session too short"};let s=Kc(t);if(!s.trim())return{documents:[],skip_reason:"No usable content"};let n=[{role:"system",content:ag},{role:"user",content:`Conversation to analyze:
|
|
615
615
|
|
|
616
|
-
${s}`}];try{let i=((await
|
|
616
|
+
${s}`}];try{let i=((await zc(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 cg(t){let e=await Vc(t);if(e.error)return{written:[],skipped:[],error:e.error};if(!e.documents||e.documents.length===0)return{written:[],skipped:[],skip_reason:e.skip_reason};let{writeDocument:s,readDocument:n}=sn(),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=`
|
|
617
617
|
|
|
618
618
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
619
619
|
|
|
620
|
-
${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}}
|
|
620
|
+
${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}}Qc.exports={learnFromSession:ig,learnBrainFromSession:cg,reflectOnSession:Jc,reflectBrain:Vc,applyMemories:Yc,applyNexAdditions:Xc,LEARN_MIN_MESSAGES:Vo}});var sl=N((F$,nl)=>{var ye=require("fs"),qt=require("path"),D$=require("os"),lg=require("readline"),{C:R}=oe(),Zc=".nex",Zo=null;function ug(t){Zo=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(Zo)Zo.question(n,r);else{let i=lg.createInterface({input:process.stdin,output:process.stdout});i.question(n,c=>{i.close(),r(c)})}})}function It(t,e=!0){return Se(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(n=>n.toLowerCase()!=="n"&&n.toLowerCase()!=="no")}async function el(t,e,s){let n=e.map((c,l)=>`${R.dim}${l+1})${R.reset} ${c}`).join(" ");console.log(` ${R.cyan}${t}${R.reset}`),console.log(` ${n}`);let o=s?e.indexOf(s)+1:1,r=await Se("Enter number",String(o)),i=parseInt(r,10)-1;return e[Math.max(0,Math.min(i,e.length-1))]}async function dg(){let t=qt.join(process.cwd(),Zc),e=qt.join(t,"servers.json"),s={};if(ye.existsSync(e))try{s=JSON.parse(ye.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
621
621
|
${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}
|
|
622
|
-
`);let n=Object.keys(s);if(n.length>0&&(console.log(`${R.dim}Existing profiles: ${n.join(", ")}${R.reset}`),!await
|
|
622
|
+
`);let n=Object.keys(s);if(n.length>0&&(console.log(`${R.dim}Existing profiles: ${n.join(", ")}${R.reset}`),!await It("Add or update a server profile?",!0))){console.log(`${R.dim}No changes made.${R.reset}
|
|
623
623
|
`);return}let o={...s},r=!0;for(;r;){console.log(`
|
|
624
|
-
${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,
|
|
625
|
-
${R.green}\u2713${R.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${
|
|
624
|
+
${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 el("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await It("Allow sudo commands?",!0),w={host:u,user:d};m!==22&&(w.port=m),h&&(w.key=h),p!=="other"&&(w.os=p),g&&(w.sudo=!0),o[l]=w,console.log(`
|
|
625
|
+
${R.green}\u2713${R.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${p!=="other"?` [${p}]`:""}`),r=await It(`
|
|
626
626
|
Add another server?`,!1)}ye.existsSync(t)||ye.mkdirSync(t,{recursive:!0}),ye.writeFileSync(e,JSON.stringify(o,null,2)+`
|
|
627
627
|
`,"utf-8"),console.log(`
|
|
628
|
-
${R.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${R.reset}`);let i=
|
|
628
|
+
${R.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${R.reset}`);let i=qt.join(process.cwd(),".gitignore");ye.existsSync(i)&&(ye.readFileSync(i,"utf-8").includes(".nex/")||await It("Add .nex/ to .gitignore?",!0)&&(ye.appendFileSync(i,`
|
|
629
629
|
# nex-code server profiles
|
|
630
630
|
.nex/
|
|
631
|
-
`),console.log(`${R.green}\u2713 Added .nex/ to .gitignore${R.reset}`))),await
|
|
632
|
-
Set up deploy configs (.nex/deploy.json)?`,!1)&&await
|
|
631
|
+
`),console.log(`${R.green}\u2713 Added .nex/ to .gitignore${R.reset}`))),await It(`
|
|
632
|
+
Set up deploy configs (.nex/deploy.json)?`,!1)&&await tl(o,t),console.log(`
|
|
633
633
|
${R.dim}Use /servers to list profiles, /servers ping to check connectivity.${R.reset}
|
|
634
|
-
`)}async function
|
|
634
|
+
`)}async function tl(t,e){let s=e||qt.join(process.cwd(),Zc),n=qt.join(s,"deploy.json"),o={};if(ye.existsSync(n))try{o=JSON.parse(ye.readFileSync(n,"utf-8"))}catch{}if(!t){let u=qt.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(`
|
|
635
635
|
${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}
|
|
636
636
|
`);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(`
|
|
637
|
-
${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
|
|
638
|
-
${R.green}\u2713${R.reset} Deploy config "${u}": ${$} \u2192 ${d}:${m}`),
|
|
637
|
+
${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 el("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):[],w={server:d,local_path:f,remote_path:m};h&&(w.deploy_script=h),g.length>0&&(w.exclude=g),c[u]=w;let $=f.endsWith("/")?f:`${f}/`;console.log(`
|
|
638
|
+
${R.green}\u2713${R.reset} Deploy config "${u}": ${$} \u2192 ${d}:${m}`),h&&console.log(` ${R.dim} Then: ${h}${R.reset}`),l=await It(`
|
|
639
639
|
Add another deploy config?`,!1)}ye.existsSync(s)||ye.mkdirSync(s,{recursive:!0}),ye.writeFileSync(n,JSON.stringify(c,null,2)+`
|
|
640
640
|
`,"utf-8"),console.log(`
|
|
641
641
|
${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}
|
|
642
|
-
`)}
|
|
642
|
+
`)}nl.exports={runServerWizard:dg,runDeployWizard:tl,setWizardRL:ug}});var il=N((U$,rl)=>{var fg=require("axios"),hn=require("fs"),ol=require("path"),mg="nex-code",er=ol.join(process.cwd(),".nex"),tr=ol.join(er,"last-version-check");hn.existsSync(er)||hn.mkdirSync(er,{recursive:!0});async function pg(){try{let t=gg(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};$g(e);let s=hg(),o=(await fg.get(`https://registry.npmjs.org/${mg}/latest`,{timeout:5e3})).data.version,r=yg(o,s);return{hasNewVersion:r,latestVersion:r?o:void 0,currentVersion:r?s:void 0}}catch{return{hasNewVersion:!1}}}function hg(){return wn().version}function gg(){try{if(hn.existsSync(tr)){let t=hn.readFileSync(tr,"utf8");return parseInt(t,10)}}catch{}return null}function $g(t){try{hn.writeFileSync(tr,t.toString())}catch{}}function yg(t,e){try{let s=t.split(".").map(Number),n=e.split(".").map(Number);return s[0]>n[0]?!0:s[0]<n[0]?!1:s[1]>n[1]?!0:s[1]<n[1]?!1:s[2]>n[2]}catch{return!1}}rl.exports={checkForNewVersion:pg}});var xl=N((B$,bl)=>{var wg=require("readline"),tt=require("fs"),qe=require("path"),{C:a,banner:bg,cleanupTerminal:al}=oe(),{listProviders:sr,getActiveProviderName:Ze,listAllModels:W$,setFallbackChain:xg,getFallbackChain:_g,getProvider:kg}=ge(),{flushAutoSave:cl}=lt(),{getActiveModel:et,setActiveModel:ll}=An(),{printContext:ul}=bo(),{loadAllSkills:vg,getSkillCommands:or,handleSkillCommand:Sg}=Gt(),{setReadlineInterface:Eg,setAutoConfirm:Cg,getAutoConfirm:dl}=Me(),{StickyFooter:Tg}=Wc(),hs=process.cwd(),Ke=null;function fl(){return Ke?.signal??null}var gs=[{cmd:"/help",desc:"Show full help"},{cmd:"/model",desc:"Show/switch model"},{cmd:"/providers",desc:"List providers and models"},{cmd:"/fallback",desc:"Show/set fallback chain"},{cmd:"/tokens",desc:"Token usage and context budget"},{cmd:"/costs",desc:"Session token costs"},{cmd:"/budget",desc:"Show/set cost limits per provider"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/context",desc:"Show project context"},{cmd:"/autoconfirm",desc:"Toggle auto-confirm"},{cmd:"/save",desc:"Save session"},{cmd:"/load",desc:"Load a saved session"},{cmd:"/sessions",desc:"List saved sessions"},{cmd:"/resume",desc:"Resume last session"},{cmd:"/remember",desc:"Save a memory"},{cmd:"/forget",desc:"Delete a memory"},{cmd:"/memory",desc:"Show all memories"},{cmd:"/brain",desc:"Manage knowledge base"},{cmd:"/brain add",desc:"Add document: /brain add <name> [content]"},{cmd:"/brain list",desc:"List all brain documents"},{cmd:"/brain search",desc:"Search brain: /brain search <query>"},{cmd:"/brain show",desc:"Show document: /brain show <name>"},{cmd:"/brain remove",desc:"Remove document: /brain remove <name>"},{cmd:"/brain rebuild",desc:"Rebuild keyword index"},{cmd:"/brain embed",desc:"Build/rebuild embedding index"},{cmd:"/brain status",desc:"Show brain status (docs, index, embeddings)"},{cmd:"/brain review",desc:"Review pending brain changes (git diff)"},{cmd:"/brain undo",desc:"Undo last brain write"},{cmd:"/learn",desc:"Reflect on session and update memory"},{cmd:"/optimize",desc:"Show optimization opportunities"},{cmd:"/permissions",desc:"Show tool permissions"},{cmd:"/allow",desc:"Auto-allow a tool"},{cmd:"/deny",desc:"Block a tool"},{cmd:"/plan",desc:"Plan mode (analyze before executing)"},{cmd:"/plans",desc:"List saved plans"},{cmd:"/auto",desc:"Set autonomy level"},{cmd:"/commit",desc:"Smart commit (diff + message)"},{cmd:"/diff",desc:"Show current diff"},{cmd:"/review [--strict] [file]",desc:"Deep code review with score table and diff suggestions (--strict: force \u22653 critical findings)"},{cmd:"/branch",desc:"Create feature branch"},{cmd:"/mcp",desc:"MCP servers and tools"},{cmd:"/hooks",desc:"Show configured hooks"},{cmd:"/skills",desc:"List, enable, disable skills"},{cmd:"/tasks",desc:"Show task list"},{cmd:"/servers",desc:"List server profiles / ping"},{cmd:"/docker",desc:"List containers across all servers"},{cmd:"/deploy",desc:"List deploy configs / run named deploy"},{cmd:"/init",desc:"Interactive setup wizard (.nex/)"},{cmd:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function ml(){let t=or(),e=[...gs,...t],s=Math.max(...e.map(n=>n.cmd.length));console.log("");for(let{cmd:n,desc:o}of gs)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(`
|
|
643
643
|
${a.dim}Type /help for detailed usage${a.reset}
|
|
644
|
-
`)}function
|
|
644
|
+
`)}function pl(t){try{let e,s;t.endsWith("/")||t.endsWith(qe.sep)?(e=t,s=""):(e=qe.dirname(t),s=qe.basename(t)),e.startsWith("~")&&(e=qe.join(require("os").homedir(),e.slice(1)));let n=qe.isAbsolute(e)?e:qe.resolve(hs,e);if(!tt.existsSync(n)||!tt.statSync(n).isDirectory())return[];let o=tt.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(qe.sep)?t:qe.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?i.name:c+i.name;r.push(i.isDirectory()?l+"/":l)}return r}catch{return[]}}function hl(t){if(t.startsWith("/")){let n=[...gs,...or()],o=n.map(r=>r.cmd).filter(r=>r.startsWith(t));return[o.length?o:n.map(r=>r.cmd),t]}let e=t.split(/\s+/),s=e[e.length-1]||"";return s&&(s.includes("/")||s.startsWith("./")||s.startsWith("../")||s.startsWith("~"))?[pl(s),s]:[[],t]}function gl(){console.log(`
|
|
645
645
|
${a.bold}${a.cyan}Commands:${a.reset}
|
|
646
646
|
${a.cyan}/help${a.reset} ${a.dim}Show this help${a.reset}
|
|
647
647
|
${a.cyan}/model [spec]${a.reset} ${a.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${a.reset}
|
|
@@ -702,48 +702,48 @@ ${a.bold}${a.cyan}Undo / Redo:${a.reset}
|
|
|
702
702
|
${a.cyan}/history${a.reset} ${a.dim}Show file change history${a.reset}
|
|
703
703
|
|
|
704
704
|
${a.cyan}/exit${a.reset} ${a.dim}Quit${a.reset}
|
|
705
|
-
`)}function
|
|
706
|
-
${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
|
|
707
|
-
${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
|
|
708
|
-
${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}=
|
|
705
|
+
`)}function $l(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 nr(){let t=sr(),e=Ze(),s=et();console.log(`
|
|
706
|
+
${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 yl(t,e){let[s,...n]=t.split(/\s+/);switch(s){case"/help":return gl(),!0;case"/model":{let o=n.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=Gc();await r(e)}else{let r=et(),i=Ze();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 nr(),!0;if(ll(o)){let r=et(),i=Ze();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 nr(),!0;case"/fallback":{let o=n.join(" ").trim();if(!o){let i=_g();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 xg(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}=Ue(),c=o(),l=r(c,i),u=et(),d=Ze();console.log(`
|
|
707
|
+
${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=$l(l.percentage);return console.log(` ${f}`),console.log(`
|
|
708
|
+
${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}=_t();return n.join(" ").trim()==="reset"?(r(),console.log(`${a.green}Cost tracking reset${a.reset}`),!0):(console.log(`
|
|
709
709
|
${o()}
|
|
710
|
-
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=
|
|
711
|
-
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let w of
|
|
710
|
+
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=_t(),d=n[0];if(!d){let h=o(),p=sr();console.log(`
|
|
711
|
+
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let w of p){let $=r(w.provider),x=h[w.provider];if(x!==void 0){g=!0;let O=Math.min(100,Math.round($/x*100)),k=10,v=Math.round(O/100*k),C=k-v,T=`${O>=100?a.red:O>=80?a.yellow:a.green}${"\u2588".repeat(v)}${a.dim}${"\u2591".repeat(C)}${a.reset}`;console.log(` ${a.bold}${w.provider}:${a.reset} $${$.toFixed(2)} / $${x.toFixed(2)} (${O}%) ${T}`)}else w.provider==="ollama"||w.provider==="local"?console.log(` ${a.bold}${w.provider}:${a.reset} ${a.dim}free (no limit)${a.reset}`):$>0&&console.log(` ${a.bold}${w.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}=vt(),c=r();if(c.filter(u=>u.role==="user").length>=4){process.stdout.write(`${a.dim}Reflecting on session...${a.reset} `);let{learnFromSession:u}=Qo();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}
|
|
712
712
|
`)}else process.stdout.write(`${a.dim}nothing new${a.reset}
|
|
713
713
|
`)}).catch(()=>process.stdout.write(`
|
|
714
|
-
`))}return o(),i(),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/context":return await
|
|
714
|
+
`))}return o(),i(),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/context":return await ul(hs),!0;case"/autoconfirm":{let o=!dl();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}=lt(),{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=et(),u=Ze();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}=lt(),{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}=lt(),r=o();if(r.length===0)return console.log(`${a.dim}No saved sessions${a.reset}`),!0;console.log(`
|
|
715
715
|
${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}=lt(),{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}=Qe(),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}=Qe(),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}=Qe(),r=o();if(r.length===0)return console.log(`${a.dim}No memories saved${a.reset}`),!0;console.log(`
|
|
716
|
-
${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}=
|
|
717
|
-
|
|
718
|
-
`);let g=require("path").join(process.cwd(),".nex","brain",`${
|
|
719
|
-
${a.bold}${a.cyan}Brain Documents:${a.reset}`);let g=Math.max(8,...
|
|
720
|
-
${a.bold}${a.cyan}Brain Search: "${
|
|
721
|
-
${a.cyan}${g.name}${a.reset} ${a.dim}(score: ${w})${a.reset}`),console.log(` ${a.dim}${g.excerpt||""}${a.reset}`)}return console.log(),!0}case"show":{if(!
|
|
722
|
-
${a.bold}${a.cyan}${
|
|
723
|
-
`),console.log(
|
|
724
|
-
${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${
|
|
716
|
+
${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}=sn(),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}
|
|
717
|
+
|
|
718
|
+
`);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),w=h.substring(p+1);i(g,w),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(`
|
|
719
|
+
${a.bold}${a.cyan}Brain Documents:${a.reset}`);let g=Math.max(8,...p.map($=>$.name.length)),w=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd(w)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat(w)}${"-".repeat(7)} --------`);for(let $ of p){let{frontmatter:x}=r($.name),O=Array.isArray(x.tags)?x.tags.join(", "):"",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,w-1).padEnd(w)}${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(`
|
|
720
|
+
${a.bold}${a.cyan}Brain Search: "${h}"${a.reset}`);for(let g of p){let w=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
|
|
721
|
+
${a.cyan}${g.name}${a.reset} ${a.dim}(score: ${w})${a.reset}`),console.log(` ${a.dim}${g.excerpt||""}${a.reset}`)}return console.log(),!0}case"show":{if(!h)return console.log(`${a.red}Usage: /brain show <name>${a.reset}`),!0;let p=r(h);return p.content?(console.log(`
|
|
722
|
+
${a.bold}${a.cyan}${h}.md${a.reset}
|
|
723
|
+
`),console.log(p.content),!0):(console.log(`${a.red}Document not found: ${h}${a.reset}`),!0)}case"remove":{if(!h)return console.log(`${a.red}Usage: /brain remove <name>${a.reset}`),!0;let{confirm:p}=Me();if(!await p(`Remove brain document "${h}"?`))return console.log(`${a.dim}Cancelled${a.reset}`),!0;let w=c(h);return console.log(w?`${a.green}Removed: ${h}.md${a.reset}`:`${a.red}Document not found: ${h}${a.reset}`),!0}case"rebuild":{let p=l(),g=Object.keys(p.documents).length;return console.log(`${a.green}Index rebuilt: ${g} document(s)${a.reset}`),!0}case"embed":{if(!await d())return console.log(`${a.yellow}Ollama embedding model not available.${a.reset}`),console.log(`${a.dim}Set NEX_EMBED_MODEL env var (default: nomic-embed-text) and ensure Ollama is running.${a.reset}`),!0;console.log(`${a.dim}Building embedding index...${a.reset}`);try{let g=await u(),w=Object.keys(g.documents||{}).length;console.log(`${a.green}Embedding index built: ${w} document(s)${a.reset}`)}catch(g){console.log(`${a.red}Embedding failed: ${g.message}${a.reset}`)}return!0}case"status":{let p=o(),g=require("fs"),w=require("path"),$=w.join(process.cwd(),".nex","brain",".brain-index.json"),x=w.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
|
|
724
|
+
${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync($)?a.green+"present"+a.reset:a.dim+"not built"+a.reset}`),console.log(` Embeddings: ${g.existsSync(x)?a.green+"present"+a.reset:a.dim+"not built (run /brain embed)"+a.reset}`),p.length>0){let O=p.reduce((k,v)=>k+v.size,0);console.log(` Total size: ${O<1024?O+"B":(O/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:p}=require("child_process"),{promisify:g}=require("util"),w=g(p);try{let{stdout:$}=await w("git diff .nex/brain/",{cwd:process.cwd()});$.trim()?(console.log(`
|
|
725
725
|
${a.bold}${a.cyan}Brain Changes (git diff):${a.reset}
|
|
726
|
-
`),console.log($)):console.log(`${a.dim}No pending brain changes (clean git state)${a.reset}`)}catch{console.log(`${a.dim}Not a git repo or no brain dir${a.reset}`)}return!0}case"undo":{let
|
|
726
|
+
`),console.log($)):console.log(`${a.dim}No pending brain changes (clean git state)${a.reset}`)}catch{console.log(`${a.dim}Not a git repo or no brain dir${a.reset}`)}return!0}case"undo":{let p=require("fs"),w=require("path").join(process.cwd(),".nex","brain");if(!p.existsSync(w))return console.log(`${a.dim}No brain directory found${a.reset}`),!0;let $=o();if($.length===0)return console.log(`${a.dim}No brain documents to undo${a.reset}`),!0;let x=$[0],{exec:O}=require("child_process"),{promisify:k}=require("util"),v=k(O);try{await v(`git checkout -- ".nex/brain/${x.name}.md"`,{cwd:process.cwd()}),l(),console.log(`${a.green}Undone: restored ${x.name}.md from git${a.reset}`)}catch{console.log(`${a.red}Could not undo \u2014 not tracked in git or no prior version${a.reset}`)}return!0}default:{let p=o();if(p.length===0)console.log(`
|
|
727
727
|
${a.bold}${a.cyan}Brain Knowledge Base${a.reset}`),console.log(`${a.dim}No documents yet. Create with /brain add <name>${a.reset}`),console.log(`
|
|
728
728
|
${a.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${a.reset}
|
|
729
729
|
`);else{console.log(`
|
|
730
|
-
${a.bold}${a.cyan}Brain: ${
|
|
730
|
+
${a.bold}${a.cyan}Brain: ${p.length} document(s)${a.reset}`);for(let g of p){let{frontmatter:w}=r(g.name),$=Array.isArray(w.tags)?` [${w.tags.join(", ")}]`:"";console.log(` ${a.cyan}${g.name}${a.reset}${a.dim}${$}${a.reset}`)}console.log(`
|
|
731
731
|
${a.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${a.reset}
|
|
732
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=
|
|
732
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=Qo(),{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:w}of u.applied){let $=w==="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:w}of d.written){let $=w==="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}=Ue(),{listMemories:c}=Qe(),l=o(),u=r(l,i),d=et(),f=Ze(),m=c();console.log(`
|
|
733
733
|
${a.bold}${a.cyan}Optimization Report${a.reset}
|
|
734
|
-
`);let
|
|
734
|
+
`);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(`
|
|
735
735
|
${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((C,S)=>new Date(S.updatedAt)-new Date(C.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(`
|
|
736
|
-
${a.bold}Active Model:${a.reset} ${f}:${d.id}`);let
|
|
736
|
+
${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(`
|
|
737
737
|
${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 w=[],$=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync($)||w.push("Create NEX.md in project root to give nex-code project-specific instructions"),w.length>0){console.log(`
|
|
738
|
-
${a.bold}Quick Wins:${a.reset}`);for(let x of w)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}=
|
|
738
|
+
${a.bold}Quick Wins:${a.reset}`);for(let x of w)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}=Ot(),{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(`
|
|
739
739
|
${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}
|
|
740
740
|
${a.cyan}${a.bold}\u2502${a.reset} Analysis only \u2014 no file changes until approved ${a.cyan}${a.bold}\u2502${a.reset}
|
|
741
741
|
${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}
|
|
742
|
-
${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}=
|
|
743
|
-
${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}=
|
|
742
|
+
${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}=Ot(),r=o();if(r.length===0)return console.log(`${a.dim}No saved plans${a.reset}`),!0;console.log(`
|
|
743
|
+
${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}=Ot(),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}=un(),r=o();console.log(`
|
|
744
744
|
${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(`
|
|
745
745
|
${a.dim}Use /allow <tool> or /deny <tool> to change${a.reset}
|
|
746
|
-
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=
|
|
746
|
+
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=un(),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}=un(),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}=it(),{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}=it();return o()?(console.log(r()),!0):(console.log(`${a.red}Not a git repository${a.reset}`),!0)}case"/review":{let{isGitRepo:o,getDiff:r}=it(),{processInput:i}=ce(),c=n.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),f=`## Review Protocol
|
|
747
747
|
|
|
748
748
|
**Phase 1 \u2014 Broad Scan:** Read the target code and identify all issues at a high level.
|
|
749
749
|
|
|
@@ -780,76 +780,76 @@ For each issue, include:
|
|
|
780
780
|
|
|
781
781
|
\u26A0 STRICT MODE: You MUST identify at least 3 critical weaknesses. If the code appears clean, dig deeper \u2014 look for subtle error-swallowing, race conditions, missing validation, or architecture risks. Do not give a passing score without identifying at least 3 critical issues.`:""}`,m;if(u)m=`Do a thorough code review of \`${u}\`.
|
|
782
782
|
|
|
783
|
-
${f}`;else{if(!o())return console.log(`${a.red}Not a git repository \u2014 try /review <file>${a.reset}`),!0;let[p
|
|
783
|
+
${f}`;else{if(!o())return console.log(`${a.red}Not a git repository \u2014 try /review <file>${a.reset}`),!0;let[h,p]=await Promise.all([r(!1),r(!0)]),g=p||h;if(!g||!g.trim())return console.log(`${a.yellow}No changes to review \u2014 commit something or specify a file: /review <file>${a.reset}`),!0;m=`Review the following code diff.
|
|
784
784
|
|
|
785
785
|
${f}
|
|
786
786
|
|
|
787
787
|
\`\`\`diff
|
|
788
788
|
${g.substring(0,2e4)}
|
|
789
|
-
\`\`\``}return await i(m),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:i}=it();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}=
|
|
789
|
+
\`\`\``}return await i(m),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:i}=it();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}=Ln(),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(`
|
|
790
790
|
${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(`
|
|
791
791
|
${a.dim}Use /mcp connect to connect all servers${a.reset}
|
|
792
|
-
`),!0}case"/hooks":{let{listHooks:o}=
|
|
793
|
-
${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}=
|
|
794
|
-
${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
|
|
792
|
+
`),!0}case"/hooks":{let{listHooks:o}=No(),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(`
|
|
793
|
+
${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}=Gt(),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(`
|
|
794
|
+
${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(`
|
|
795
795
|
${a.dim}Use /skills enable <name> or /skills disable <name>${a.reset}
|
|
796
|
-
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=
|
|
796
|
+
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=Gn();return n.join(" ").trim()==="clear"?(r(),console.log(`${a.green}Tasks cleared${a.reset}`),!0):(console.log(`
|
|
797
797
|
`+o()+`
|
|
798
|
-
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=
|
|
798
|
+
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=vt(),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}=vt(),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}=vt(),c=o(20);if(c.length===0)return console.log(`${a.dim}No file changes in this session${a.reset}`),!0;console.log(`
|
|
799
799
|
${a.bold}File Change History${a.reset}
|
|
800
800
|
`);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(`
|
|
801
801
|
${a.dim}${r()} undo / ${i()} redo available${a.reset}
|
|
802
802
|
`),!0}case"/k8s":{let o=n.join(" ").trim(),{exec:r}=require("child_process"),{promisify:i}=require("util"),c=i(r),l=o||null,u=l?`ssh -o ConnectTimeout=10 -o BatchMode=yes ${l.replace(/[^a-zA-Z0-9@._-]/g,"")} `:"",d=f=>l?`${u}"${f.replace(/"/g,'\\"')}"`:f;console.log(`
|
|
803
803
|
${a.bold}${a.cyan}Kubernetes Overview${a.reset}${l?a.dim+" (remote: "+l+")"+a.reset:""}
|
|
804
804
|
`);try{let{stdout:f}=await c(d("kubectl get namespaces --no-headers -o custom-columns=NAME:.metadata.name"),{timeout:15e3}),m=f.trim().split(`
|
|
805
|
-
`).filter(Boolean);console.log(`${a.bold}Namespaces (${m.length}):${a.reset}`);for(let
|
|
805
|
+
`).filter(Boolean);console.log(`${a.bold}Namespaces (${m.length}):${a.reset}`);for(let h of m)console.log(` ${a.cyan}${h}${a.reset}`);console.log()}catch{return console.log(`${a.dim}Could not reach cluster \u2014 is kubectl configured?${a.reset}
|
|
806
806
|
`),!0}try{let{stdout:f}=await c(d("kubectl get pods -A --no-headers -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,READY:.status.containerStatuses[0].ready,STATUS:.status.phase,RESTARTS:.status.containerStatuses[0].restartCount"),{timeout:2e4}),m=f.trim().split(`
|
|
807
|
-
`).filter(Boolean),
|
|
807
|
+
`).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}
|
|
808
808
|
`);let w=m.filter($=>!$.includes("Running")&&!$.includes("<none>"));if(w.length>0){console.log(`${a.bold}${a.red}Unhealthy Pods:${a.reset}`);for(let $ of w)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}
|
|
809
809
|
`)}catch(f){console.log(`${a.dim}Could not list pods: ${f.message}${a.reset}
|
|
810
|
-
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:r,sshExec:i}=
|
|
810
|
+
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:r,sshExec:i}=Ct(),c=o(),l=Object.keys(c);if(l.length===0)return console.log(`
|
|
811
811
|
${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}
|
|
812
812
|
`),!0;if(n[0]==="ping"){let f=n[1]?[n[1]]:l;return console.log(`
|
|
813
|
-
${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
|
|
813
|
+
${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}=Ct();console.log(`
|
|
814
814
|
${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(`
|
|
815
815
|
${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}
|
|
816
|
-
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=
|
|
817
|
-
${a.bold}${a.cyan}Docker Containers:${a.reset}`);for(let[m,
|
|
818
|
-
`).forEach(w=>console.log(` ${a.dim}${w}${a.reset}`)))}catch(g){console.log(` ${
|
|
816
|
+
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=Ct(),{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(`
|
|
817
|
+
${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:w}=await l(u,{timeout:8e3});g=(w||"").trim()}else{let w=await r(h,u,{timeout:1e4});if(g=[w.stdout,w.stderr].filter(Boolean).join("").trim(),w.exitCode!==0){console.log(` ${p}: ${a.red}SSH error (${w.exitCode})${a.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${p}: ${a.dim}(no containers)${a.reset}`):(console.log(` ${p}:`),g.split(`
|
|
818
|
+
`).forEach(w=>console.log(` ${a.dim}${w}${a.reset}`)))}catch(g){console.log(` ${p}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=Zs(),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}=Ue();console.log(`
|
|
819
819
|
${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(`
|
|
820
820
|
${a.dim}No deploy configs. Run /init to create .nex/deploy.json${a.reset}
|
|
821
821
|
`),!0;console.log(`
|
|
822
822
|
${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(`
|
|
823
823
|
${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}
|
|
824
|
-
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:i}=
|
|
825
|
-
${a.dim}Bye!${a.reset}`),process.exit(0);default:return
|
|
826
|
-
`).filter(Boolean).slice(-
|
|
827
|
-
`)}catch{}}function Ee(){let{isPlanMode:t,getAutonomyLevel:e}=
|
|
828
|
-
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:A}=
|
|
824
|
+
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:i}=sl();return i(e),n[0]==="deploy"?await r():await o(),!0}case"/exit":case"/quit":console.log(`
|
|
825
|
+
${a.dim}Bye!${a.reset}`),process.exit(0);default:return Sg(t)||console.log(`${a.red}Unknown command: ${s}. Type /help${a.reset}`),!0}}var rr=1e3;function ir(){return qe.join(process.cwd(),".nex","repl_history")}function wl(){try{let t=ir();if(tt.existsSync(t))return tt.readFileSync(t,"utf-8").split(`
|
|
826
|
+
`).filter(Boolean).slice(-rr)}catch{}return[]}function ps(t){try{let e=ir(),s=qe.dirname(e);tt.existsSync(s)||tt.mkdirSync(s,{recursive:!0}),tt.appendFileSync(e,t+`
|
|
827
|
+
`)}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"),ll("local:llama3"),!0}catch{return!1}}async function Mg(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=ce();t(fl);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}
|
|
828
|
+
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:A}=il();return await A()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,i,c]);!u&&!o&&(console.error(`
|
|
829
829
|
${a.red}\u2717 No provider configured and no local Ollama detected.${a.reset}
|
|
830
|
-
`),process.exit(1));let f
|
|
831
|
-
`),await
|
|
830
|
+
`),process.exit(1));let f=wl(),m=wg.createInterface({input:process.stdin,output:process.stdout,prompt:Ee(),completer:hl,history:f,historySize:rr});Eg(m);let h=new Tg;h.activate(m);let p=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;bg(p,hs,{yolo:dl()}),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}
|
|
831
|
+
`),await ul(hs);let g=!1,w=0,$=!1,x=null;function O(){cl(),h.deactivate(),al(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write(`
|
|
832
832
|
${a.dim}Bye!${a.reset}
|
|
833
|
-
`),process.exit(0)}process.on("SIGTERM",O),process.on("exit",()=>{
|
|
833
|
+
`),process.exit(0)}process.on("SIGTERM",O),process.on("exit",()=>{cl()}),m.on("SIGINT",()=>{if(al(),g){if(w++,w>=2){O();return}Ke&&Ke.abort();let{cancelPendingAskUser:A}=Ue();A(),console.log(`
|
|
834
834
|
${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(`
|
|
835
835
|
${a.dim} (Press Ctrl+C again to exit)${a.reset}
|
|
836
836
|
`),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=[],C=0,S={},T=!1;function F(){let A=v.join(`
|
|
837
837
|
`).replace(/\r/g,"").trim();if(v=[],k=!1,!A)return!0;C++,T=!0;let L=C;S[L]=A;let se=A.split(`
|
|
838
|
-
`).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(){C=0,S={},T=!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(
|
|
839
|
-
`)),F()}if(q){k=!0,v=[];let H=
|
|
840
|
-
`)),!0}if(U){let H=
|
|
841
|
-
`)),F()}if(k){let H=
|
|
842
|
-
`)),!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=[...
|
|
838
|
+
`).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(){C=0,S={},T=!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(ar),U=z.includes(cr);if(q&&U){let H=gn(z);return H&&v.push(...H.split(`
|
|
839
|
+
`)),F()}if(q){k=!0,v=[];let H=gn(z);return H&&v.push(...H.split(`
|
|
840
|
+
`)),!0}if(U){let H=gn(z);return H&&v.push(...H.split(`
|
|
841
|
+
`)),F()}if(k){let H=gn(z);return H&&v.push(...H.split(`
|
|
842
|
+
`)),!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=[...gs,...or()].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:je}of z){let gt=ae.substring(0,A.length),me=ae.substring(A.length),ke=" ".repeat(Math.max(0,q-ae.length+2));U+=`
|
|
843
843
|
\x1B[2K ${a.cyan}${gt}${a.reset}${a.dim}${me}${ke}${je}${a.reset}`}D=z.length,L.length>se&&(U+=`
|
|
844
844
|
\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}
|
|
845
845
|
`)}return}if(ue!==null){if(ue._mode==="triple"){if(A.trim()==='"""'){let q=ue.join(`
|
|
846
|
-
`).trim();if(ue=null,q){
|
|
846
|
+
`).trim();if(ue=null,q){ps(q.replace(/\n/g,"\\n")),g=!0,w=0,$=!1,x&&(clearTimeout(x),x=null),Ke=new AbortController;try{await s(q)}catch(H){if(!Ke?.signal?.aborted){let ae=H.message?.split(`
|
|
847
847
|
`)[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(`
|
|
848
|
-
`).trim();if(ue=null,q){
|
|
849
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${je}${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(
|
|
848
|
+
`).trim();if(ue=null,q){ps(q.replace(/\n/g,"\\n")),g=!0,w=0,$=!1,x&&(clearTimeout(x),x=null),Ke=new AbortController;try{await s(q)}catch(ae){if(!Ke?.signal?.aborted){let je=ae.message?.split(`
|
|
849
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${je}${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(ps(L),L==="/"){ml(),m.setPrompt(Ee()),m.prompt();return}if(L.startsWith("/")){await yl(L,m),m.setPrompt(Ee()),m.prompt();return}{let q="\x1B[48;5;237m",U=process.stdout.columns||80;L.split(`
|
|
850
850
|
`).forEach((ae,je)=>{let gt=je===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",me=2+ae.length,ke=" ".repeat(Math.max(0,U-me));console.log(`${q}${gt} ${ae}${ke}\x1B[0m`)})}g=!0,w=0,$=!1,x&&(clearTimeout(x),x=null),Ke=new AbortController;try{await s(L)}catch(q){if(!Ke?.signal?.aborted){let U=q.message?.split(`
|
|
851
851
|
`)[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(`
|
|
852
|
-
${a.dim}Bye!${a.reset}`),process.exit(0)})}
|
|
852
|
+
${a.dim}Bye!${a.reset}`),process.exit(0)})}bl.exports={startREPL:Mg,getPrompt:Ee,loadHistory:wl,appendHistory:ps,getHistoryPath:ir,HISTORY_MAX:rr,showCommandList:ml,completer:hl,completeFilePath:pl,handleSlashCommand:yl,showProviders:nr,showHelp:gl,renderBar:$l,hasPasteStart:Rg,hasPasteEnd:Ag,stripPasteSequences:gn,getAbortSignal:fl}});var vl=require("path");require("dotenv").config({path:vl.join(__dirname,"..",".env")});require("dotenv").config();var te=process.argv.slice(2);(te.includes("--help")||te.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
853
853
|
|
|
854
854
|
Options:
|
|
855
855
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -862,4 +862,4 @@ Options:
|
|
|
862
862
|
--json Output result as JSON (for CI parsing)
|
|
863
863
|
-h, --help Show this help
|
|
864
864
|
-v, --version Show version
|
|
865
|
-
`),process.exit(0));if(te.includes("-v")||te.includes("--version")){let t
|
|
865
|
+
`),process.exit(0));if(te.includes("-v")||te.includes("--version")){let t=wn();console.log(t.version),process.exit(0)}var Ng=te.includes("--yolo")||te.includes("-yolo");if(Ng){let{setAutoConfirm:t}=Me();t(!0)}var lr=te.indexOf("--model");if(lr!==-1&&te[lr+1]){let{setActiveModel:t}=ge();t(te[lr+1])}var ur=te.indexOf("--max-turns");if(ur!==-1&&te[ur+1]){let t=parseInt(te[ur+1],10);if(t>0){let{setMaxIterations:e}=ce();e(t)}}else try{let t=require("fs"),e=vl.join(process.cwd(),".nex","config.json");if(t.existsSync(e)){let s=JSON.parse(t.readFileSync(e,"utf-8")),n=parseInt(s.maxIterations,10);if(n>0){let{setMaxIterations:o}=ce();o(n)}}}catch{}function dr(){if(process.platform==="darwin")try{let{spawn:t}=require("child_process"),e=t("caffeinate",["-i","-m"],{stdio:"ignore",detached:!1});e.unref();let s=()=>{try{e.kill()}catch{}};process.on("exit",s),process.on("SIGINT",s),process.on("SIGTERM",s)}catch{}}function _l(t){if(te.includes("--auto")){let{setAutoConfirm:o}=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 kl=te.indexOf("--prompt-file");if(kl!==-1){let t=te[kl+1];(!t||t.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let e=require("fs"),s;try{s=e.readFileSync(t,"utf-8").trim()}catch(n){console.error(`--prompt-file: cannot read file: ${n.message}`),process.exit(1)}if(s||(console.error("--prompt-file: file is empty"),process.exit(1)),te.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}dr(),_l(s)}else{let t=te.indexOf("--task");if(t!==-1){let e=te[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),dr(),_l(e)}else{dr();let{startREPL:e}=xl();e()}}
|