nex-code 0.3.35 → 0.3.36
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 +257 -251
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,22 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var M=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var
|
|
2
|
+
var M=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var kn=M((Dg,Rl)=>{Rl.exports={name:"nex-code",version:"0.3.36",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 kr=M((Fg,_r)=>{var O={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"},wr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],br=["\u273D","\u2726","\u2727","\u2726"],vs=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=wr[this.frame%wr.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=` ${O.dim}${o}m ${String(r).padStart(2,"0")}s${O.reset}`}else n>=1&&(s=` ${O.dim}${n}s${O.reset}`)}process.stderr.write(`\x1B[2K\r${O.cyan}${e}${O.reset} ${O.dim}${this.text}${O.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}},xr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ss=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=xr[this.frame%xr.length],s=this._formatElapsed(),n=s?` ${O.dim}${s}${O.reset}`:"",o="";for(let r=0;r<this.labels.length;r++){let i,c;switch(this.statuses[r]){case"done":i=`${O.green}\u2713${O.reset}`,c=O.dim;break;case"error":i=`${O.red}\u2717${O.reset}`,c=O.dim;break;default:i=`${O.cyan}${e}${O.reset}`,c=""}let l=r===this.labels.length-1?n:"";o+=`\x1B[2K ${i} ${c}${this.labels[r]}${O.reset}${l}
|
|
3
3
|
`}this.lineCount>0&&(o+=`\x1B[${this.lineCount}A`),process.stderr.write(o),this.frame++}start(){this._stopped=!1,this.startTime=Date.now();let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
4
|
-
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${
|
|
5
|
-
`}process.stderr.write(n)}},
|
|
6
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=
|
|
4
|
+
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),80)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${O.dim}${e}${O.reset}`:"",n="";for(let o=0;o<this.labels.length;o++){let r;switch(this.statuses[o]){case"done":r=`${O.green}\u2713${O.reset}`;break;case"error":r=`${O.red}\u2717${O.reset}`;break;default:r=`${O.yellow}\u25CB${O.reset}`}let i=o===this.labels.length-1?s:"";n+=`\x1B[2K ${r} ${O.dim}${this.labels[o]}${O.reset}${i}
|
|
5
|
+
`}process.stderr.write(n)}},vn={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Sn={done:O.green,in_progress:O.cyan,pending:O.dim,failed:O.red},Xe=null,Es=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=br[this.frame%br.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${O.dim}(${o})${O.reset}`:"",i=`\x1B[2K${O.cyan}${e}${O.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=vn[l.status]||vn.pending,f=Sn[l.status]||Sn.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${O.dim}${u}${O.reset} ${f}${d}${O.reset} ${m}
|
|
7
7
|
`}i+=`\x1B[${this.lineCount}A`,process.stderr.write(i),this.frame++}start(){this._stopped=!1,this.startTime=Date.now(),this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
8
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),
|
|
8
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),Xe=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,Xe===this&&(Xe=null)}pause(){if(this._paused)return;this.interval&&(clearInterval(this.interval),this.interval=null);let e="";for(let s=0;s<this.lineCount;s++)e+=`\x1B[2K
|
|
9
9
|
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._paused=!0}resume(){if(!this._paused)return;this._paused=!1;let e="\x1B[?25l";for(let s=0;s<this.lineCount;s++)e+=`
|
|
10
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(c=>c.status==="done").length,n=this.tasks.filter(c=>c.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,i=`\x1B[2K${
|
|
11
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=
|
|
12
|
-
`}process.stderr.write(i)}};function
|
|
13
|
-
`),n=s.slice(0,e),o=s.length-e,r=`${
|
|
10
|
+
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,s){let n=this.tasks.find(o=>o.id===e);n&&(n.status=s)}setStats({tokens:e}){e!==void 0&&(this.tokens=e)}isActive(){return this.interval!==null||this._paused}_renderFinal(){let e=this._formatElapsed(),s=this.tasks.filter(c=>c.status==="done").length,n=this.tasks.filter(c=>c.status==="failed").length,o=this.tasks.length,r=n>0?`${s}/${o} done, ${n} failed`:`${s}/${o} done`,i=`\x1B[2K${O.green}\u2714${O.reset} ${this.name} ${O.dim}(${e} \xB7 ${r})${O.reset}
|
|
11
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=vn[l.status]||vn.pending,f=Sn[l.status]||Sn.pending,m=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${O.dim}${u}${O.reset} ${f}${d}${O.reset} ${O.dim}${m}${O.reset}
|
|
12
|
+
`}process.stderr.write(i)}};function Al(t){Xe=t}function Ol(){return Xe}function Nl(){Xe&&(Xe.stop(),Xe=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}_r.exports={C:O,Spinner:vs,MultiProgress:Ss,TaskProgress:Es,setActiveTaskProgress:Al,getActiveTaskProgress:Ol,cleanupTerminal:Nl}});var Sr=M((Ug,vr)=>{var L={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"},Ml={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"},Pl={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 Ll(t,e){let s=(t||[]).filter(r=>r&&r.canExecute!==!1);if(s.length===0)return`${L.cyan} \u25C6 Step ${e}${L.reset}`;let n=[...new Set(s.map(r=>Pl[r.fnName]||r.fnName))],o;if(n.length===1&&s.length===1){o=n[0];let i=s[0].args||{},c=` ${L.reset}${L.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`${L.cyan} \u25C6 ${o}${L.reset}`}function Il(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=Ml[t]||t.replace(/_/g," "),o=s?` ${L.dim}${s}${L.reset}`:"";return`${L.cyan} \u23FA${L.reset} ${L.bold}${n}${L.reset}${o}`}function ql(t,e=8){let s=t.split(`
|
|
13
|
+
`),n=s.slice(0,e),o=s.length-e,r=`${L.dim} \u23BF ${L.reset}`,i=" ",c=n.map((l,u)=>`${u===0?r:i}${L.green}${l}${L.reset}`).join(`
|
|
14
14
|
`);return o>0&&(c+=`
|
|
15
|
-
${
|
|
15
|
+
${L.gray} \u2026+${o} more lines${L.reset}`),c}function jl(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 Dl(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
|
+
${L.dim}${c[1].substring(0,100)}${L.reset}`:"";return` ${L.red}\u23BF ${i}${L.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(`
|
|
19
|
-
`).length;r=`Wrote ${i} line${i!==1?"s":""}`;break}case"edit_file":
|
|
19
|
+
`).length;r=`Wrote ${i} line${i!==1?"s":""}`;break}case"edit_file":{let i=(e.old_text||"").split(`
|
|
20
|
+
`),c=(e.new_text||"").split(`
|
|
21
|
+
`),l=i.length,u=c.length,d=3,f=i.slice(0,d).filter(p=>p.trim()),m=c.slice(0,d).filter(p=>p.trim()),h=[];for(let p of f)h.push(`${L.red} - ${p.trimEnd().substring(0,72)}${L.reset}`);i.length>d&&h.push(`${L.dim} \u2026 ${i.length-d} more removed${L.reset}`);for(let p of m)h.push(`${L.green} + ${p.trimEnd().substring(0,72)}${L.reset}`);c.length>d&&h.push(`${L.dim} \u2026 ${c.length-d} more added${L.reset}`),r=`${L.reset}${L.red}\u2212${l}${L.reset} ${L.green}+${u}${L.reset}`+(h.length>0?`
|
|
22
|
+
`+h.join(`
|
|
23
|
+
`):"");break}case"patch_file":{let i=e.patches||[],c=i.reduce((u,d)=>u+(d.old_text||"").split(`
|
|
24
|
+
`).length,0),l=i.reduce((u,d)=>u+(d.new_text||"").split(`
|
|
25
|
+
`).length,0);r=`${L.reset}${i.length} patch${i.length!==1?"es":""} ${L.red}\u2212${c}${L.reset} ${L.green}+${l}${L.reset}`;break}case"bash":{let i=o.match(/^EXIT (\d+)/);if(i){let c=i[1],l=o.match(/\nHINT: (.+)/);if(l)r=`Exit ${c} \u2014 ${l[1].substring(0,60)}`;else{let u=o.split(`
|
|
20
26
|
`).filter(f=>f&&!f.startsWith("EXIT ")),d=u[0]?` \xB7 ${u[0].substring(0,60)}`:"";r=`Exit ${c}${d}`}}else{let c=o.split(`
|
|
21
27
|
`).filter(Boolean);r=c.length>1?`${c.length} lines output`:(c[0]||"").substring(0,70)||"Done"}break}case"grep":case"search_files":{if(o.includes("(no matches)")||o==="no matches")r="No matches";else{let i=o.split(`
|
|
22
28
|
`).filter(Boolean).length;r=`${i} match${i!==1?"es":""}`}break}case"glob":{if(o==="(no matches)")r="No files found";else{let i=o.split(`
|
|
@@ -25,114 +31,114 @@ ${G.gray} \u2026+${o} more lines${G.reset}`),c}function Ll(t,e){switch(t){ca
|
|
|
25
31
|
`).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
32
|
`).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
33
|
|
|
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` ${
|
|
29
|
-
`),u=s.yolo?` ${n}${
|
|
34
|
+
`).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` ${L.dim}\u23BF ${r}${L.reset}`}vr.exports={C:L,formatToolCall:Il,formatResult:ql,getToolSpinnerText:jl,formatToolSummary:Dl,formatSectionHeader:Ll}});var ae=M((Wg,Er)=>{var vt={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 Fl(t,e){return[...t].map(s=>s===" "?s:`\x1B[38;2;${e[0]};${e[1]};${e[2]}m${s}`).join("")+vt.reset}function Ul(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 Wl(t,e,s={}){let n=vt.bold,o=vt.dim,r=vt.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 Fl(d,Ul(c,m))}).join(`
|
|
35
|
+
`),u=s.yolo?` ${n}${vt.yellow}\u26A1 YOLO${r}`:"";console.log(`
|
|
30
36
|
${l}
|
|
31
|
-
${o}Agentic Coding CLI v${
|
|
37
|
+
${o}Agentic Coding CLI v${kn().version}${r}
|
|
32
38
|
${o}Model: ${t}${r} ${o}\xB7 /help${r}${u}
|
|
33
|
-
`)}var{Spinner:
|
|
34
|
-
`);for(let d=0;d<s.length;d++){let f=d===o,m=f?`${
|
|
39
|
+
`)}var{Spinner:Bl,MultiProgress:Hl,TaskProgress:Gl,setActiveTaskProgress:zl,getActiveTaskProgress:Kl,cleanupTerminal:Jl}=kr(),{formatToolCall:Yl,formatResult:Xl,getToolSpinnerText:Vl,formatToolSummary:Ql,formatSectionHeader:Zl}=Sr();Er.exports={C:vt,banner:Wl,Spinner:Bl,MultiProgress:Hl,TaskProgress:Gl,setActiveTaskProgress:zl,getActiveTaskProgress:Kl,cleanupTerminal:Jl,formatToolCall:Yl,formatResult:Xl,getToolSpinnerText:Vl,formatToolSummary:Ql,formatSectionHeader:Zl}});var Ne=M((Bg,Or)=>{var eu=require("readline"),{C:Oe}=ae(),Tr=[/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/],Ts=[/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 Cr(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)):Ts.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Ts.some(c=>c.test(i))};return n.every(o)}var Cs=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],Rr=[/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/],Ar=[...Cs,...Rr],Rs=!1,lt=null;function tu(t){Rs=t}function nu(){return Rs}function su(t){lt=t}function ou(t){for(let e of Tr)if(e.test(t))return e;return null}function ru(t){if(/ssh\s/.test(t)&&Cr(t))return!1;for(let e of Ar)if(e.test(t))return!0;return!1}function iu(t){for(let e of Cs)if(e.test(t))return!0;return!1}function au(t,e={}){if(Rs)return Promise.resolve(!0);if(!process.stdout.isTTY||!process.stdin.isTTY)return cu(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0,r=!1;lt&<.pause();let i=()=>{r&&process.stdout.write(`\x1B[${s.length+1}A`),r=!0,process.stdout.write(`\r\x1B[K${Oe.yellow}${t}${Oe.reset}
|
|
40
|
+
`);for(let d=0;d<s.length;d++){let f=d===o,m=f?`${Oe.yellow}\u276F${Oe.reset}`:" ",h=f?`${Oe.yellow}${s[d]}${Oe.reset}`:s[d];process.stdout.write(`\r\x1B[K ${m} ${h}
|
|
35
41
|
`)}},c=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u),process.stdout.write(`\x1B[${s.length+1}A`);for(let f=0;f<s.length+1;f++)process.stdout.write(`\r\x1B[K
|
|
36
|
-
`);process.stdout.write(`\x1B[${s.length+1}A`),
|
|
37
|
-
`){l(o);return}if(f==="\x1B[A"){o=(o-1+s.length)%s.length,i();return}if(f==="\x1B[B"){o=(o+1)%s.length,i();return}let m=f.toLowerCase().trim();if(m==="y"){c(!0);return}if(m==="n"){c(!1);return}if(m==="a"&&e.toolName){
|
|
38
|
-
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){await this.discoverModels();let o=n.model||this.defaultModel,r=this.getModel(o),i=n.maxTokens||r?.maxTokens||16384,c=await
|
|
39
|
-
`);h=g.pop()||"";for(let y of g){if(!y.trim())continue;let $;try{$=JSON.parse(y)}catch{continue}if($.message?.content&&(c($.message.content),f+=$.message.content),$.message?.tool_calls&&(m=m.concat($.message.tool_calls)),$.done){u({content:f,tool_calls:this._normalizeToolCalls(m)});return}}}),l.data.on("error",p=>{n.signal?.aborted||d(new Error(`Stream error: ${p.message}`))}),l.data.on("end",()=>{if(h.trim())try{let p=JSON.parse(h);p.message?.content&&(c(p.message.content),f+=p.message.content),p.message?.tool_calls&&(m=m.concat(p.message.tool_calls))}catch{}u({content:f,tool_calls:this._normalizeToolCalls(m)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`ollama-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};
|
|
42
|
+
`);process.stdout.write(`\x1B[${s.length+1}A`),lt&<.resume(),n(d)},l=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&En(e.toolName),c(!0)},u=d=>{if(d[0]===3){c(!1);return}let f=d.toString();if(f==="\r"||f===`
|
|
43
|
+
`){l(o);return}if(f==="\x1B[A"){o=(o-1+s.length)%s.length,i();return}if(f==="\x1B[B"){o=(o+1)%s.length,i();return}let m=f.toLowerCase().trim();if(m==="y"){c(!0);return}if(m==="n"){c(!1);return}if(m==="a"&&e.toolName){En(e.toolName),c(!0);return}};i(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function cu(t,e){let s=e.toolName?"[Y/n/a] ":"[Y/n] ";return new Promise(n=>{let o=r=>{let i=r.trim().toLowerCase();i==="a"&&e.toolName?(En(e.toolName),n(!0)):n(i!=="n")};if(lt)lt.question(`${Oe.yellow}${t} ${s}${Oe.reset}`,o);else{let r=eu.createInterface({input:process.stdin,output:process.stdout});r.question(`${Oe.yellow}${t} ${s}${Oe.reset}`,i=>{r.close(),o(i)})}})}var En=()=>{};function lu(t){En=t}Or.exports={FORBIDDEN_PATTERNS:Tr,SSH_SAFE_PATTERNS:Ts,isSSHReadOnly:Cr,DANGEROUS_BASH:Ar,CRITICAL_BASH:Cs,NOTABLE_BASH:Rr,isForbidden:ou,isDangerous:ru,isCritical:iu,confirm:au,setAutoConfirm:tu,getAutoConfirm:nu,setReadlineInterface:su,setAllowAlwaysHandler:lu}});var St=M((Hg,Nr)=>{var As=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`)}};Nr.exports={BaseProvider:As}});var Lr=M((Gg,Pr)=>{var Tn=require("axios"),uu=require("http"),du=require("https"),{BaseProvider:fu}=St(),Cn=new uu.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Rn=new du.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Mr={"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}},Os=class extends fu{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||Mr,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){Tn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Cn,httpsAgent:Rn}).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 Tn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Cn,httpsAgent:Rn})).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(`
|
|
44
|
+
`)};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 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:i}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Cn,httpsAgent:Rn});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 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:i}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:Cn,httpsAgent:Rn})}catch(u){if(u.name==="CanceledError"||u.name==="AbortError"||u.code==="ERR_CANCELED")throw u;let d=u.response?.data?.error||u.message;throw new Error(`API Error: ${d}`)}return new Promise((u,d)=>{let f="",m=[],h="";n.signal&&n.signal.addEventListener("abort",()=>{l.data.destroy(),d(new DOMException("The operation was aborted","AbortError"))},{once:!0}),l.data.on("data",p=>{h+=p.toString();let g=h.split(`
|
|
45
|
+
`);h=g.pop()||"";for(let y of g){if(!y.trim())continue;let $;try{$=JSON.parse(y)}catch{continue}if($.message?.content&&(c($.message.content),f+=$.message.content),$.message?.tool_calls&&(m=m.concat($.message.tool_calls)),$.done){u({content:f,tool_calls:this._normalizeToolCalls(m)});return}}}),l.data.on("error",p=>{n.signal?.aborted||d(new Error(`Stream error: ${p.message}`))}),l.data.on("end",()=>{if(h.trim())try{let p=JSON.parse(h);p.message?.content&&(c(p.message.content),f+=p.message.content),p.message?.tool_calls&&(m=m.concat(p.message.tool_calls))}catch{}u({content:f,tool_calls:this._normalizeToolCalls(m)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`ollama-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};Pr.exports={OllamaProvider:Os,OLLAMA_MODELS:Mr}});var Ur=M((zg,Fr)=>{var{callChat:mu}=pe(),{estimateTokens:Ns}=Ce(),Ir=process.env.NEX_COMPACTION!=="false",qr=6,jr=500,pu=`Summarize this conversation history concisely. Focus on:
|
|
40
46
|
- What files were read, created, or modified
|
|
41
47
|
- Key decisions made and their rationale
|
|
42
48
|
- Current state of the task (what's done, what's pending)
|
|
43
49
|
- Any errors encountered and how they were resolved
|
|
44
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
45
|
-
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function
|
|
50
|
+
Be factual and brief. Use bullet points. Max 300 words.`;async function hu(t){if(!Ir||t.length<qr)return null;let e=[{role:"system",content:pu},{role:"user",content:Dr(t)}];try{let n=((await mu(e,[],{temperature:0,maxTokens:jr})).content||"").trim();if(!n)return null;let o=t.reduce((i,c)=>i+Ns(c.content||"")+(c.tool_calls?Ns(JSON.stringify(c.tool_calls)):0),0),r=Ns(n);return r>=o*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
51
|
+
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function Dr(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}
|
|
46
52
|
tools: ${o}`}return`[${s}] ${n}`}).join(`
|
|
47
53
|
|
|
48
|
-
`)}
|
|
54
|
+
`)}Fr.exports={compactMessages:hu,formatMessagesForSummary:Dr,COMPACTION_ENABLED:Ir,COMPACTION_MIN_MESSAGES:qr,COMPACTION_SUMMARY_BUDGET:jr}});var Ce=M((Kg,Jr)=>{function Br(){return pe().getActiveModel()}var gu={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},Ht=new Map,Wr=1e3,Ms=new WeakMap,Gt=null;function $u(){if(Gt!==null)return Gt;try{let e=Br()?.provider||"ollama";return Gt=gu[e]||4,Gt}catch{return 4}}function yu(){Gt=null}function dt(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=Ht.get(e);if(s!==void 0)return s;let n=Math.ceil(t.length/$u());if(Ht.size>=Wr){let o=Wr>>1,r=Ht.keys();for(let i=0;i<o;i++)Ht.delete(r.next().value)}return Ht.set(e,n),n}function wu(t){if(Ms.has(t))return Ms.get(t);let e=JSON.stringify(t);return Ms.set(t,e),e}function Et(t){let s=4;if(t.content&&(s+=dt(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=dt(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=dt(o):o&&(s+=dt(JSON.stringify(o)))}return s}function Re(t){let e=0;for(let s of t)e+=Et(s);return e}function bu(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+=Et(e[r]);return o}function An(t){return!t||t.length===0?0:dt(JSON.stringify(t))}function On(){return Br()?.contextWindow||32768}function xu(t,e){let s=Re(t),n=An(e),o=s+n,r=On(),i=r>0?o/r*100:0,c=0,l=0,u=0;for(let d of t){let f=Et(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 Hr=.75,Gr=.1,zr=10,_u=200,ku=500;function Kr(t,e){if(!t||t.length<=e)return t;let n=/^(ERROR|EXIT|BLOCKED|CANCELLED)/i.test(t)?e*3:e;if(t.length<=n)return t;let o=t.split(`
|
|
49
55
|
`);if(o.length<=10){let p=Math.floor(n*.6),g=Math.floor(n*.4),y=t.substring(0,p),$=t.substring(t.length-g);return y+`
|
|
50
56
|
...(${t.length} chars total)...
|
|
51
57
|
`+$}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(`
|
|
52
58
|
`)+`
|
|
53
59
|
...(${h} lines omitted, ${o.length} total)...
|
|
54
60
|
`+d.join(`
|
|
55
|
-
`)}function
|
|
56
|
-
...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(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
|
|
61
|
+
`)}function zt(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:ku,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:Kr(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
|
|
62
|
+
...(truncated)`),o.tool_calls&&e==="aggressive"&&(o.tool_calls=o.tool_calls.map(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 vu(t,e,s={}){let n=s.threshold??Hr,o=s.safetyMargin??Gr,r=s.keepRecent??zr,i=On(),c=An(e),l=Math.floor(i*(n-o)),u=l-c,d=Re(t),f=d+c;if(f<=l)return{messages:t,compressed:!1,compacted:!1,tokensRemoved:0};let m=d,h=null,p=0;t.length>0&&t[0].role==="system"&&(h=t[0],p=1);let g=Math.max(p,t.length-r),y=t.slice(p,g),$=t.slice(g),x=y.filter(S=>!S._compacted);if(x.length>=6)try{let{compactMessages:S}=Ur(),C=await S(x);if(C){let I=[...y.filter(de=>de._compacted),C.message],ee=ut(h,I,$),B=Re(ee);if(B+c<=l)return{messages:ee,compressed:!0,compacted:!0,tokensRemoved:m-B};y=I}}catch(S){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",S.message)}let A=(f-l)/l,k=y.map(S=>zt(S,"light")),v=ut(h,k,$),T=Re(v);if(T+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-T};if(k=y.map(S=>zt(S,"medium")),v=ut(h,k,$),T=Re(v),T+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-T};if(k=y.map(S=>zt(S,"aggressive")),v=ut(h,k,$),T=Re(v),T+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-T};for(;k.length>0&&T>u;){let S=k.shift();T-=Et(S)}return v=ut(h,k,$),T=Re(v),{messages:v,compressed:!0,compacted:!1,tokensRemoved:m-T}}function ut(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function Su(t,e){if(!t)return"";if(dt(t)<=e)return t;let n=e*4,o=t.split(`
|
|
57
63
|
`),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?`
|
|
58
64
|
`:"")+h,l++}let u="",d=0;for(let h=o.length-1;h>=l;h--){let p=o[h]+(u?`
|
|
59
65
|
`:"")+u;if(p.length>i)break;u=p,d++}let m=`
|
|
60
66
|
|
|
61
67
|
... (${o.length-l-d} lines omitted, ${o.length} total) ...
|
|
62
68
|
|
|
63
|
-
`;return c+m+u}var
|
|
64
|
-
`);g=$.pop()||"";for(let x of $){let
|
|
65
|
-
|
|
66
|
-
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let 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
|
|
67
|
-
`);
|
|
68
|
-
`);g=$.pop()||"";for(let x of $){let
|
|
69
|
-
`)};return o.length>0&&(r.images=o),r}return s})}async chat(e,s,n={}){this._modelsLoaded||await this.loadModels();let o=n.model||this.defaultModel;if(!o)throw new Error("No local model available. Is Ollama running?");let r=await
|
|
70
|
-
`);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let g;try{g=JSON.parse(p)}catch{continue}if(g.message?.content&&(r(g.message.content),u+=g.message.content),g.message?.tool_calls&&(d=d.concat(g.message.tool_calls)),g.done){c({content:u,tool_calls:this._normalizeToolCalls(d)});return}}}),i.data.on("error",m=>{n.signal?.aborted||l(new Error(`Stream error: ${m.message}`))}),i.data.on("end",()=>{if(f.trim())try{let m=JSON.parse(f);m.message?.content&&(r(m.message.content),u+=m.message.content),m.message?.tool_calls&&(d=d.concat(m.message.tool_calls))}catch{}c({content:u,tool_calls:this._normalizeToolCalls(d)})})})}normalizeResponse(e){let s=e.message||{};return{content:s.content||"",tool_calls:this._normalizeToolCalls(s.tool_calls||[])}}_parseContextFromModelfile(e){if(!e)return null;let s=e.match(/PARAMETER\s+num_ctx\s+(\d+)/i);return s?parseInt(s[1],10):null}_normalizeToolCalls(e){return e.map((s,n)=>({id:s.id||`local-${Date.now()}-${n}`,function:{name:s.function?.name||s.name||"unknown",arguments:s.function?.arguments||s.arguments||{}}}))}};
|
|
71
|
-
`)}}function
|
|
72
|
-
`)}function
|
|
73
|
-
`),c}catch(c){throw o.stop(),c}}async function
|
|
69
|
+
`;return c+m+u}var Eu=6;function Tu(t,e){let s=On(),n=An(e),o=Math.floor(s*.5)-n,r=Re(t),i=null,c=0;t.length>0&&t[0].role==="system"&&(i=t[0],c=1);let l=Math.max(c,t.length-Eu),u=t.slice(c,l),d=t.slice(l),f=u.map(p=>zt(p,"aggressive")),m=ut(i,f,d),h=Re(m);for(;f.length>0&&h>o;){let p=f.shift();h-=Et(p)}return m=ut(i,f,d),h=Re(m),{messages:m,tokensRemoved:r-h}}Jr.exports={estimateTokens:dt,estimateMessageTokens:Et,estimateMessagesTokens:Re,estimateDeltaTokens:bu,estimateToolsTokens:An,serializeMessage:wu,getContextWindow:On,getUsage:xu,compressMessage:zt,compressToolResult:Kr,fitToContext:vu,forceCompress:Tu,truncateFileContent:Su,invalidateTokenRatioCache:yu,COMPRESSION_THRESHOLD:Hr,SAFETY_MARGIN:Gr,KEEP_RECENT:zr}});var Qr=M((Yg,Vr)=>{var Yr=require("axios"),{BaseProvider:Cu}=St(),{serializeMessage:Jg}=Ce(),Xr={"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}},Ps=class extends Cu{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Xr,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 Yr.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 Yr.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},g="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let $=g.split(`
|
|
70
|
+
`);g=$.pop()||"";for(let x of $){let A=x.trim();if(!A||!A.startsWith("data: "))continue;let k=A.slice(6);if(k==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let v;try{v=JSON.parse(k)}catch{continue}let T=v.choices?.[0]?.delta;if(T&&(T.content&&(c(T.content),h+=T.content),T.tool_calls))for(let S of T.tool_calls){let C=S.index??0;p[C]||(p[C]={id:S.id||"",name:"",arguments:""}),S.id&&(p[C].id=S.id),S.function?.name&&(p[C].name+=S.function.name),S.function?.arguments&&(p[C].arguments+=S.function.arguments)}}}),d.data.on("error",y=>{n.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`openai-${Date.now()}`,function:{name:s.name,arguments:s.arguments}}))}};Vr.exports={OpenAIProvider:Ps,OPENAI_MODELS:Xr}});var ni=M((Vg,ti)=>{var Zr=require("axios"),{BaseProvider:Ru}=St(),{serializeMessage:Xg}=Ce(),ei={"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}},Au="2023-06-01",Ls=class extends Ru{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||ei,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||Au}isConfigured(){return!!this.getApiKey()}getApiKey(){return process.env.ANTHROPIC_API_KEY||null}_getHeaders(){let e=this.getApiKey();if(!e)throw new Error("ANTHROPIC_API_KEY not set");return{"x-api-key":e,"anthropic-version":this.apiVersion,"Content-Type":"application/json"}}_messageFormatCache=new WeakMap;_messageStringCache=new Map;_maxCacheSize=200;formatMessages(e){let s="",n=[];for(let o of e){if(o.role==="system"){s+=(s?`
|
|
71
|
+
|
|
72
|
+
`:"")+o.content;continue}if(o.role!=="system"&&o.role!=="tool"&&this._messageFormatCache.has(o)){n.push(this._messageFormatCache.get(o));continue}let 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 Zr.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 Zr.post(`${this.baseUrl}/messages`,f,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(p){if(p.name==="CanceledError"||p.name==="AbortError"||p.code==="ERR_CANCELED")throw p;let g=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${g}`)}return new Promise((p,g)=>{let y="",$=[],x=-1,A="";n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",k=>{A+=k.toString();let v=A.split(`
|
|
73
|
+
`);A=v.pop()||"";for(let T of v){let S=T.trim();if(S.startsWith("data: ")){let C=S.slice(6),U;try{U=JSON.parse(C)}catch{continue}switch(U.type){case"content_block_start":{let I=U.content_block;I?.type==="tool_use"&&(x=$.length,$.push({id:I.id,name:I.name,inputJson:""}));break}case"content_block_delta":{let I=U.delta;I?.type==="text_delta"&&I.text&&(l(I.text),y+=I.text),I?.type==="input_json_delta"&&I.partial_json!==void 0&&x>=0&&($[x].inputJson+=I.partial_json);break}case"content_block_stop":x=-1;break;case"message_stop":p({content:y,tool_calls:this._buildToolCalls($)});return}}}}),h.data.on("error",k=>{n.signal?.aborted||g(new Error(`Stream error: ${k.message}`))}),h.data.on("end",()=>{p({content:y,tool_calls:this._buildToolCalls($)})})})}normalizeResponse(e){let s="",n=[];for(let o of e.content||[])o.type==="text"?s+=o.text:o.type==="tool_use"&&n.push({id:o.id,function:{name:o.name,arguments:o.input}});return{content:s,tool_calls:n}}_buildToolCalls(e){return e.filter(s=>s.name).map(s=>{let n={};if(s.inputJson)try{n=JSON.parse(s.inputJson)}catch{n=s.inputJson}return{id:s.id||`anthropic-${Date.now()}`,function:{name:s.name,arguments:n}}})}};ti.exports={AnthropicProvider:Ls,ANTHROPIC_MODELS:ei}});var ii=M((Zg,ri)=>{var si=require("axios"),{BaseProvider:Ou}=St(),{serializeMessage:Qg}=Ce(),oi={"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}},Is=class extends Ou{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||oi,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 si.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 si.post(`${this.baseUrl}/chat/completions`,u,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(f){if(f.name==="CanceledError"||f.name==="AbortError"||f.code==="ERR_CANCELED")throw f;let m=f.response?.data?.error?.message||f.message;throw new Error(`API Error: ${m}`)}return new Promise((f,m)=>{let h="",p={},g="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),m(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let $=g.split(`
|
|
74
|
+
`);g=$.pop()||"";for(let x of $){let A=x.trim();if(!A||!A.startsWith("data: "))continue;let k=A.slice(6);if(k==="[DONE]"){f({content:h,tool_calls:this._buildToolCalls(p)});return}let v;try{v=JSON.parse(k)}catch{continue}let T=v.choices?.[0]?.delta;if(T&&(T.content&&(c(T.content),h+=T.content),T.tool_calls))for(let S of T.tool_calls){let C=S.index??0;p[C]||(p[C]={id:S.id||"",name:"",arguments:""}),S.id&&(p[C].id=S.id),S.function?.name&&(p[C].name+=S.function.name),S.function?.arguments&&(p[C].arguments+=S.function.arguments)}}}),d.data.on("error",y=>{n.signal?.aborted||m(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{f({content:h,tool_calls:this._buildToolCalls(p)})})})}normalizeResponse(e){let s=e.choices?.[0]?.message||{},n=(s.tool_calls||[]).map(o=>({id:o.id,function:{name:o.function.name,arguments:o.function.arguments}}));return{content:s.content||"",tool_calls:n}}_buildToolCalls(e){return Object.values(e).filter(s=>s.name).map(s=>({id:s.id||`call-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,function:{name:s.name,arguments:s.arguments}}))}};ri.exports={GeminiProvider:Is,GEMINI_MODELS:oi}});var li=M((e$,ci)=>{var Nn=require("axios"),{BaseProvider:Nu}=St(),ai="http://localhost:11434",qs=class extends Nu{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||ai,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 Nn.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 Nn.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(`
|
|
75
|
+
`)};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 Nn.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 Nn.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(`
|
|
76
|
+
`);f=h.pop()||"";for(let p of h){if(!p.trim())continue;let g;try{g=JSON.parse(p)}catch{continue}if(g.message?.content&&(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||{}}}))}};ci.exports={LocalProvider:qs,DEFAULT_LOCAL_URL:ai}});var Tt=M((t$,gi)=>{var ft=require("fs"),js=require("path"),ui={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:{}},Mn=[],Ve={};function Mu(t,e,s,n){if(Mn.push({provider:t,model:e,input:s,output:n}),Ve[t]!==void 0){let o=pi(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
|
|
77
|
+
`)}}function Ds(t,e){let s=ui[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function di(t){let e=Ds(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function fi(){let t={};for(let r of Mn){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:di(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 Pu(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=fi();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(`
|
|
78
|
+
`)}function Lu(t,e,s,n){let o=Ds(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function Iu(){Mn=[]}function qu(t,e){Ve[t]=e}function ju(t){delete Ve[t]}function Du(){return{...Ve}}function mi(t){let e=0;for(let s of Mn)s.provider===t&&(e+=di(s));return e}function pi(t){let e=mi(t),s=Ve[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 hi(){let t=js.join(process.cwd(),".nex","config.json");if(ft.existsSync(t))try{let e=JSON.parse(ft.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(Ve={...e.costLimits})}catch{}}function Fu(){let t=js.join(process.cwd(),".nex"),e=js.join(t,"config.json"),s={};if(ft.existsSync(e))try{s=JSON.parse(ft.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=Ve,ft.existsSync(t)||ft.mkdirSync(t,{recursive:!0}),ft.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function Uu(){Ve={}}hi();gi.exports={PRICING:ui,trackUsage:Mu,getSessionCosts:fi,formatCosts:Pu,formatCostHint:Lu,resetCosts:Iu,getPricing:Ds,setCostLimit:qu,removeCostLimit:ju,getCostLimits:Du,getProviderSpend:mi,checkBudget:pi,loadCostLimits:hi,saveCostLimits:Fu,resetCostLimits:Uu}});var Pn=M((n$,$i)=>{var Kt=pe(),Wu={"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 Bu(){return Kt.getActiveModel()}function Hu(t){return Kt.setActiveModel(t)}function Gu(){return Kt.getModelNames()}function zu(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 Ku(t,e){let{C:s}=ae(),{Spinner:n}=ae(),o=new n("Thinking...");o.start();let r=!0,i="";try{let c=await Kt.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}
|
|
79
|
+
`),c}catch(c){throw o.stop(),c}}async function Ju(t,e){return Kt.callChat(t,e)}$i.exports={MODELS:Wu,getActiveModel:Bu,setActiveModel:Hu,getModelNames:Gu,callOllamaStream:Ku,callOllama:Ju,parseToolArgs:zu}});var bi=M((s$,wi)=>{var Ln=require("path"),{C:b}=ae(),{confirm:Yu,getAutoConfirm:Xu}=Ne(),yi=2e3;function Jt(t,e){let s=t.split(`
|
|
74
80
|
`),n=e.split(`
|
|
75
|
-
`),o=[],r=s.length,i=n.length;if(r>
|
|
76
|
-
${b.bold}${b.cyan} Diff: ${t}${b.reset}`);let o=
|
|
77
|
-
${b.bold}${b.cyan} File exists \u2014 showing changes: ${t}${b.reset}`);let n=
|
|
81
|
+
`),o=[],r=s.length,i=n.length;if(r>yi||i>yi){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 Vu(t,e,s,n=3){console.log(`
|
|
82
|
+
${b.bold}${b.cyan} Diff: ${t}${b.reset}`);let o=Jt(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 Qu(t,e,s){console.log(`
|
|
83
|
+
${b.bold}${b.cyan} File exists \u2014 showing changes: ${t}${b.reset}`);let n=Jt(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 Zu(t,e){console.log(`
|
|
78
84
|
${b.bold}${b.cyan} New file: ${t}${b.reset}`);let s=e.split(`
|
|
79
|
-
`),n=s.slice(0,20);for(let o of n)console.log(`${b.green} + ${o}${b.reset}`);s.length>20&&console.log(`${b.gray} ...+${s.length-20} more lines${b.reset}`),console.log()}async function
|
|
80
|
-
${b.bold}${b.cyan} Side-by-side: ${t}${b.reset}`),console.log(` ${b.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${b.reset}`);let i=
|
|
81
|
-
`)}function
|
|
85
|
+
`),n=s.slice(0,20);for(let o of n)console.log(`${b.green} + ${o}${b.reset}`);s.length>20&&console.log(`${b.gray} ...+${s.length-20} more lines${b.reset}`),console.log()}async function ed(t){return Xu()?!0:Yu(` ${t}?`)}function td(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
|
|
86
|
+
${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=Jt(e,s),c=[],l=0;for(;l<i.length;)if(i[l].type==="same")c.push({left:i[l].line,right:i[l].line,type:"same"}),l++;else if(i[l].type==="remove"){let h=[];for(;l<i.length&&i[l].type==="remove";)h.push(i[l].line),l++;let p=[];for(;l<i.length&&i[l].type==="add";)p.push(i[l].line),l++;let g=Math.max(h.length,p.length);for(let y=0;y<g;y++)c.push({left:y<h.length?h[y]:"",right:y<p.length?p[y]:"",type:"changed"})}else i[l].type==="add"&&(c.push({left:"",right:i[l].line,type:"changed"}),l++);let u=c.map((h,p)=>h.type!=="same"?p:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${b.gray}(no changes)${b.reset}`);return}let d=Math.max(0,u[0]-2),f=Math.min(c.length,u[u.length-1]+3),m=(h,p)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=p?h.substring(0,p):h+" ".repeat(p-g.length)};d>0&&console.log(` ${b.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${b.reset}`);for(let h=d;h<f;h++){let p=c[h];if(p.type==="same")console.log(` ${b.gray}${m(p.left,r)}${b.reset}\u2502${b.gray}${m(p.right,r)}${b.reset}`);else{let g=p.left?`${b.red}${m(p.left,r)}${b.reset}`:`${m("",r)}`,y=p.right?`${b.green}${m(p.right,r)}${b.reset}`:`${m("",r)}`;console.log(` ${g}\u2502${y}`)}}f<c.length&&console.log(` ${b.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${b.reset}`),console.log(` ${b.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${b.reset}
|
|
87
|
+
`)}function nd(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],c=Ln.isAbsolute(t)?Ln.relative(process.cwd(),t):t,l=Jt(e,s),u=1,d=1;for(let k of l)k.type==="same"?(k.oldLine=u++,k.newLine=d++):k.type==="remove"?(k.oldLine=u++,k.newLine=null):(k.oldLine=null,k.newLine=d++);let f=0,m=0;for(let k of l)k.type==="add"?f++:k.type==="remove"&&m++;if(console.log(`
|
|
82
88
|
${b.cyan}\u23FA${b.reset} ${b.bold}${o}(${c})${b.reset}`),f===0&&m===0){console.log(` ${b.dim}\u23BF (no changes)${b.reset}
|
|
83
|
-
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),i.length>0){let k=i.filter(C=>C.severity==="error").length,v=i.filter(C=>C.severity==="warn").length,T=i.filter(C=>C.severity==="info").length,S=[];k>0&&S.push(`${b.red}${k} error${k!==1?"s":""}${b.dim}`),v>0&&S.push(`${b.yellow}${v} warning${v!==1?"s":""}${b.dim}`),T>0&&S.push(`${b.cyan}${T} info${T!==1?"s":""}${b.dim}`),h.push(`found ${S.join(", ")}`)}console.log(` ${b.dim}\u23BF ${h.join(", ")}${b.reset}`);let g=[];l.forEach((k,v)=>{k.type!=="same"&&g.push(v)});let y=[],$=null,x=null;for(let k of g){let v=Math.max(0,k-r),T=Math.min(l.length-1,k+r);$===null?($=v,x=T):(v<=x+1||(y.push([$,x]),$=v),x=T)}$!==null&&y.push([$,x]);let
|
|
89
|
+
`);return}let h=[];if(f>0&&h.push(`Added ${f} line${f!==1?"s":""}`),m>0&&h.push(`removed ${m} line${m!==1?"s":""}`),i.length>0){let k=i.filter(C=>C.severity==="error").length,v=i.filter(C=>C.severity==="warn").length,T=i.filter(C=>C.severity==="info").length,S=[];k>0&&S.push(`${b.red}${k} error${k!==1?"s":""}${b.dim}`),v>0&&S.push(`${b.yellow}${v} warning${v!==1?"s":""}${b.dim}`),T>0&&S.push(`${b.cyan}${T} info${T!==1?"s":""}${b.dim}`),h.push(`found ${S.join(", ")}`)}console.log(` ${b.dim}\u23BF ${h.join(", ")}${b.reset}`);let g=[];l.forEach((k,v)=>{k.type!=="same"&&g.push(v)});let y=[],$=null,x=null;for(let k of g){let v=Math.max(0,k-r),T=Math.min(l.length-1,k+r);$===null?($=v,x=T):(v<=x+1||(y.push([$,x]),$=v),x=T)}$!==null&&y.push([$,x]);let A=" ";for(let k=0;k<y.length;k++){k>0&&console.log(`${A}${b.dim}\xB7\xB7\xB7${b.reset}`);let[v,T]=y[k];for(let S=v;S<=T;S++){let C=l[S],U=C.newLine!=null?C.newLine:C.oldLine,I=String(U).padStart(4),ee=C.type!=="remove"?i.filter(B=>B.line===C.newLine):[];C.type==="remove"?console.log(`${A}${b.red}${I} -${C.line}${b.reset}`):C.type==="add"?console.log(`${A}${b.green}${I} +${C.line}${b.reset}`):console.log(`${A}${b.dim}${I}${b.reset} ${C.line}`);for(let B of ee){let de=b.cyan,me="\u2139";B.severity==="error"?(de=b.red,me="\u2716"):B.severity==="warn"&&(de=b.yellow,me="\u26A0"),console.log(`${A} ${de}${me} ${B.message}${b.reset}`)}}}console.log()}function sd(t,e,s={}){let n=Ln.isAbsolute(t)?Ln.relative(process.cwd(),t):t,o=e.split(`
|
|
84
90
|
`),r=s.annotations||[];console.log(`
|
|
85
|
-
${b.cyan}\u23FA${b.reset} ${b.bold}Create(${n})${b.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(p=>p.severity==="error").length,f=r.filter(p=>p.severity==="warn").length,m=r.filter(p=>p.severity==="info").length,h=[];d>0&&h.push(`${b.red}${d} error${d!==1?"s":""}${b.dim}`),f>0&&h.push(`${b.yellow}${f} warning${f!==1?"s":""}${b.dim}`),m>0&&h.push(`${b.cyan}${m} info${m!==1?"s":""}${b.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${b.dim}\u23BF ${i.join(", ")}${b.reset}`);let l=" ",u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),m=d+1,h=r.filter(p=>p.line===m);console.log(`${l}${b.green}${f} +${o[d]}${b.reset}`);for(let p of h){let g=b.cyan,y="\u2139";p.severity==="error"?(g=b.red,y="\u2716"):p.severity==="warn"&&(g=b.yellow,y="\u26A0"),console.log(`${l} ${g}${y} ${p.message}${b.reset}`)}}o.length>20&&console.log(`${l}${b.dim} ...+${o.length-20} more lines${b.reset}`),console.log()}
|
|
86
|
-
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function
|
|
87
|
-
`);for(let f of d)f.startsWith("+")&&!f.startsWith("+++")&&o++,f.startsWith("-")&&!f.startsWith("---")&&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
|
|
88
|
-
${
|
|
89
|
-
${
|
|
90
|
-
${
|
|
91
|
+
${b.cyan}\u23FA${b.reset} ${b.bold}Create(${n})${b.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(p=>p.severity==="error").length,f=r.filter(p=>p.severity==="warn").length,m=r.filter(p=>p.severity==="info").length,h=[];d>0&&h.push(`${b.red}${d} error${d!==1?"s":""}${b.dim}`),f>0&&h.push(`${b.yellow}${f} warning${f!==1?"s":""}${b.dim}`),m>0&&h.push(`${b.cyan}${m} info${m!==1?"s":""}${b.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${b.dim}\u23BF ${i.join(", ")}${b.reset}`);let l=" ",u=Math.min(o.length,20);for(let d=0;d<u;d++){let f=String(d+1).padStart(4),m=d+1,h=r.filter(p=>p.line===m);console.log(`${l}${b.green}${f} +${o[d]}${b.reset}`);for(let p of h){let g=b.cyan,y="\u2139";p.severity==="error"?(g=b.red,y="\u2716"):p.severity==="warn"&&(g=b.yellow,y="\u26A0"),console.log(`${l} ${g}${y} ${p.message}${b.reset}`)}}o.length>20&&console.log(`${l}${b.dim} ...+${o.length-20} more lines${b.reset}`),console.log()}wi.exports={diffLines:Jt,showEditDiff:Vu,showWriteDiff:Qu,showNewFilePreview:Zu,confirmFileChange:ed,showSideBySideDiff:td,showClaudeDiff:nd,showClaudeNewFile:sd}});var mt=M((o$,ki)=>{var xi=require("util").promisify(require("child_process").exec),od=require("util").promisify(require("child_process").execFile),{C:se}=ae();async function Fs(t){try{let{stdout:e}=await xi(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function In(...t){try{let{stdout:e}=await od("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function rd(){return await Fs("git rev-parse --is-inside-work-tree")==="true"}async function id(){return await Fs("git branch --show-current")}async function Us(){try{let{stdout:t}=await xi("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
92
|
+
`).filter(Boolean).map(e=>{let s=e.substring(0,2).trim(),n=e.substring(3);return{status:s,file:n}})}catch{return[]}}async function qn(t=!1){return await Fs(`git diff ${t?"--cached":""}`)||""}async function Ws(){return(await Us()).map(e=>e.file)}async function _i(){let t=await Ws();if(t.length===0)return null;let e=await qn(),n=await qn(!0)||e,o=0,r=0;if(n){let d=n.split(`
|
|
93
|
+
`);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 ad(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await In("checkout","-b",s)!==null?s:null}async function cd(t){return await In("add","-A"),await In("commit","-m",t)?await In("rev-parse","--short","HEAD"):null}async function ld(){let t=await _i();if(!t)return`${se.dim}No changes${se.reset}`;let e=[];e.push(`
|
|
94
|
+
${se.bold}${se.cyan}Git Diff Summary:${se.reset}`),e.push(` ${se.green}+${t.stats.additions}${se.reset} ${se.red}-${t.stats.deletions}${se.reset} in ${t.files.length} file(s)`),e.push(`
|
|
95
|
+
${se.bold}${se.cyan}Files:${se.reset}`);for(let s of t.files.slice(0,20))e.push(` ${se.dim}${s}${se.reset}`);return t.files.length>20&&e.push(` ${se.dim}...+${t.files.length-20} more${se.reset}`),e.push(`
|
|
96
|
+
${se.bold}${se.cyan}Suggested message:${se.reset}`),e.push(` ${se.cyan}${t.summary}${se.reset}
|
|
91
97
|
`),e.join(`
|
|
92
|
-
`)}async function
|
|
98
|
+
`)}async function ud(){return(await Us()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function dd(){let t=await Ws();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 qn();if(s){let n=s.length>5e3?s.substring(0,5e3)+`
|
|
93
99
|
...(truncated)`:s;e.push(`
|
|
94
100
|
DIFF:
|
|
95
101
|
${n}`)}return e.join(`
|
|
96
|
-
`)}
|
|
102
|
+
`)}ki.exports={isGitRepo:rd,getCurrentBranch:id,getStatus:Us,getDiff:qn,getChangedFiles:Ws,analyzeDiff:_i,createBranch:ad,commit:cd,formatDiffSummary:ld,getDiffContext:dd,getMergeConflicts:ud}});var Rt=M((r$,vi)=>{var Bs=require("fs").promises,fd=50,Fe=[],Ct=[];function md(t,e,s,n){for(Fe.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});Fe.length>fd;)Fe.shift();Ct.length=0}async function pd(){if(Fe.length===0)return null;let t=Fe.pop();if(t.oldContent===null)try{await Bs.unlink(t.filePath)}catch{}else await Bs.writeFile(t.filePath,t.oldContent,"utf-8");return Ct.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function hd(){if(Ct.length===0)return null;let t=Ct.pop();return await Bs.writeFile(t.filePath,t.newContent,"utf-8"),Fe.push(t),{tool:t.tool,filePath:t.filePath}}function gd(t=10){return Fe.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function $d(){return Fe.length}function yd(){return Ct.length}function wd(){Fe.length=0,Ct.length=0}vi.exports={recordChange:md,undo:pd,redo:hd,getHistory:gd,getUndoCount:$d,getRedoCount:yd,clearHistory:wd}});var Yt=M((i$,Ai)=>{var _e=require("fs"),At=require("path"),ye=[];function Hs(){return At.join(process.cwd(),".nex","skills")}function Si(){return At.join(process.cwd(),".nex","config.json")}function bd(){let t=Hs();return _e.existsSync(t)||_e.mkdirSync(t,{recursive:!0}),t}function Gs(){let t=Si();if(!_e.existsSync(t))return[];try{let e=JSON.parse(_e.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function Ei(t){let e=Si(),s={};if(_e.existsSync(e))try{s=JSON.parse(_e.readFileSync(e,"utf-8"))}catch{s={}}s.skills||(s.skills={}),s.skills.disabled=t;let n=At.dirname(e);_e.existsSync(n)||_e.mkdirSync(n,{recursive:!0}),_e.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function Ti(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 Ci(t){try{let e=_e.readFileSync(t,"utf-8").trim();return e?{name:At.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function Ri(t){try{let e=require(t),{valid:s,errors:n}=Ti(e,t);return s?{name:e.name||At.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}
|
|
97
103
|
${n.join(`
|
|
98
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
104
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function xd(){ye=[];let t=Hs();if(!_e.existsSync(t))return ye;let e=Gs(),s;try{s=_e.readdirSync(t)}catch{return ye}for(let n of s){let o=At.join(t,n),r;try{r=_e.statSync(o)}catch{continue}if(!r.isFile())continue;let i=null;n.endsWith(".md")?i=Ci(o):n.endsWith(".js")&&(i=Ri(o)),i&&(i.enabled=!e.includes(i.name),ye.push(i))}return ye}function _d(){let t=[];for(let e of ye)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
99
105
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
100
106
|
${t.join(`
|
|
101
107
|
|
|
102
|
-
`)}`}function
|
|
108
|
+
`)}`}function kd(){let t=[];for(let e of ye)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function vd(){let t=[];for(let e of ye)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 Sd(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of ye)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 Ed(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of ye)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 Td(){return ye.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 Cd(t){let e=ye.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=Gs().filter(n=>n!==t);return Ei(s),!0}function Rd(t){let e=ye.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=Gs();return s.includes(t)||(s.push(t),Ei(s)),!0}function Ad(){return ye}Ai.exports={initSkillsDir:bd,loadAllSkills:xd,getSkillInstructions:_d,getSkillCommands:kd,getSkillToolDefinitions:vd,routeSkillCall:Sd,handleSkillCommand:Ed,listSkills:Td,enableSkill:Cd,disableSkill:Rd,getLoadedSkills:Ad,_getSkillsDir:Hs,_validateScriptSkill:Ti,_loadMarkdownSkill:Ci,_loadScriptSkill:Ri}});var Dn=M((a$,Ii)=>{var{spawn:Od}=require("child_process"),Nd=require("path"),Oi=require("fs"),Ue=new Map;function Md(){return Nd.join(process.cwd(),".nex","config.json")}function zs(){let t=Md();if(!Oi.existsSync(t))return{};try{return JSON.parse(Oi.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function jn(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})+`
|
|
103
109
|
`,l="",u=setTimeout(()=>{f(),r(new Error(`MCP request timeout: ${e}`))},n);function d(m){l+=m.toString();let h=l.split(`
|
|
104
|
-
`);for(let p of h)if(p.trim())try{let g=JSON.parse(p);if(g.id===i){f(),g.error?r(new Error(`MCP error: ${g.error.message||JSON.stringify(g.error)}`)):o(g.result);return}}catch{}l=h[h.length-1]||""}function f(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(m){f(),r(new Error(`MCP write failed: ${m.message}`))}})}async function
|
|
105
|
-
`):JSON.stringify(o)}function
|
|
106
|
-
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),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=
|
|
110
|
+
`);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 Ni(t,e){if(Ue.has(t))return Ue.get(t);let s=["PATH","HOME","USER","SHELL","LANG","TERM","NODE_ENV"],n={};for(let i of s)process.env[i]&&(n[i]=process.env[i]);let o=Od(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await jn(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await jn(o,"tools/list",{});return r.tools=i&&i.tools||[],Ue.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function Mi(t){let e=Ue.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return Ue.delete(t),!0}function Pd(){for(let[t]of Ue)Mi(t)}async function Pi(t,e,s={}){let n=Ue.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await jn(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(`
|
|
111
|
+
`):JSON.stringify(o)}function Li(){let t=[];for(let[e,s]of Ue)for(let n of s.tools)t.push({server:e,name:n.name,description:n.description||"",inputSchema:n.inputSchema||{type:"object",properties:{}}});return t}function Ld(){return Li().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function Id(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 Pi(n,o,e)}function qd(){let t=zs();return Object.entries(t).map(([e,s])=>{let n=Ue.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function jd(){let t=zs(),e=[];for(let[s,n]of Object.entries(t))try{let o=await Ni(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}Ii.exports={loadMCPConfig:zs,sendRequest:jn,connectServer:Ni,disconnectServer:Mi,disconnectAll:Pd,callTool:Pi,getAllTools:Li,getMCPToolDefinitions:Ld,routeMCPCall:Id,listServers:qd,connectAll:jd}});var Ks=M((c$,Fi)=>{var{getSkillToolDefinitions:Dd}=Yt(),{getMCPToolDefinitions:Fd}=Dn(),Fn=new Map;function qi(){let{TOOL_DEFINITIONS:t}=We();return[...t,...Dd(),...Fd()]}function ji(t){if(Fn.has(t))return Fn.get(t);let s=qi().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return Fn.set(t,n),n}function Ud(){Fn.clear()}function Un(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=Di(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function Di(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 Wd(t,e){let s=ji(t);if(s===null){let d=qi().map(m=>m.function.name),f=Un(t,d);return{valid:!1,error:`Unknown tool "${t}".${f?` Did you mean "${f}"?`:""}
|
|
112
|
+
Available tools: ${d.join(", ")}`}}if(!s||!s.properties)return{valid:!0};let n=s.required||[],o=Object.keys(s.properties),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=Un(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=Un(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:
|
|
107
113
|
`+i.map(u=>` - ${u}`).join(`
|
|
108
114
|
`)+`
|
|
109
115
|
|
|
110
|
-
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}
|
|
116
|
+
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}Fi.exports={validateToolArgs:Wd,closestMatch:Un,levenshtein:Di,getCachedSchema:ji,clearSchemaCache:Ud}});var Hi=M((l$,Bi)=>{var{levenshtein:Wn}=Ks(),Bd=200,Hd=.3,Gd=2;function Js(t){return t.replace(/\r\n/g,`
|
|
111
117
|
`).replace(/\r/g,`
|
|
112
|
-
`).replace(/\t/g," ".repeat(
|
|
118
|
+
`).replace(/\t/g," ".repeat(Gd)).split(`
|
|
113
119
|
`).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(`
|
|
114
|
-
`)}function
|
|
120
|
+
`)}function zd(t,e){if(t.includes(e))return e;let s=Js(t),n=Js(e);if(!s.includes(n))return null;let o=t.split(`
|
|
115
121
|
`),r=s.split(`
|
|
116
122
|
`),i=n.split(`
|
|
117
123
|
`),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(`
|
|
118
|
-
`)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(n)!==-1)return o[u]}return null}function
|
|
124
|
+
`)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(n)!==-1)return o[u]}return null}function Kd(t,e){if(!t||!e)return null;let s=t.split(`
|
|
119
125
|
`),o=e.split(`
|
|
120
|
-
`).length;return s.length===0||o===0?null:o===1?
|
|
121
|
-
`),u=
|
|
122
|
-
`),h=
|
|
123
|
-
`),n=[],o=t?`.${t.split(".").pop()}`:"";for(let r=0;r<s.length;r++){let i=s[r],c=r+1;for(let l of
|
|
124
|
-
`).filter(Boolean),
|
|
126
|
+
`).length;return s.length===0||o===0?null:o===1?Jd(s,e):Xd(s,e,o)}function Ui(t){return Math.max(1,Math.floor(t/Bd))}function Wi(t,e){return t<=Math.ceil(e*Hd)}function Jd(t,e){let s=e.trim(),n=Ui(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=Wn(c.trim(),s);l<r&&(r=l,o={text:c,distance:l,line:i+1})}return o&&n>1&&(o=Yd(t,s,o,n)||o,r=o.distance),Wi(r,e.length)?o:null}function Yd(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=Wn(d.trim(),e);f<c&&(c=f,l={text:d,distance:f,line:u+1})}return l}function Xd(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=Ui(n),r=null,i=1/0;for(let c=0;c<n;c+=o){let l=t.slice(c,c+s).join(`
|
|
127
|
+
`),u=Wn(l,e);u<i&&(i=u,r={text:l,distance:u,line:c+1})}return r&&o>1&&(r=Vd(t,e,r,o,s,n)||r,i=r.distance),Wi(i,e.length)?r:null}function Vd(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(`
|
|
128
|
+
`),h=Wn(m,e);h<u&&(u=h,d={text:m,distance:h,line:f+1})}return d}Bi.exports={normalizeWhitespace:Js,fuzzyFindText:zd,findMostSimilar:Kd}});var zi=M((d$,Gi)=>{var{C:u$}=ae(),Qd=[{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}],Zd=[{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 ef(t,e){let s=e.split(`
|
|
129
|
+
`),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 Qd)l.regex.test(i)&&n.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of Zd)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}Gi.exports={runDiagnostics:ef}});var Vs=M((f$,Yi)=>{var tf=require("fs").promises,Ki=require("path"),{exec:nf}=require("util").promisify(require("child_process").exec),Ot=[],Xs=null,Bn=!1,Ys=0,sf=6e4;function Ji(t){return!(Ot.length===0||Xs!==t||Date.now()-Ys>sf)}async function of(t){if(!Bn&&!Ji(t)){Bn=!0,Xs=t;try{try{let{stdout:n}=await nf("rg --files",{cwd:t,timeout:5e3});Ot=n.split(`
|
|
130
|
+
`).filter(Boolean),Ys=Date.now(),Bn=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await tf.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(Ki.join(n,i.name),c):e.push(c)}};await s(t,""),Ot=e,Ys=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{Bn=!1}}}function rf(){return Ot}function af(){return Xs}function cf(t){return Ot.filter(e=>Ki.basename(e)===t)}function lf(t){let e=t.toLowerCase();return Ot.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}Yi.exports={refreshIndex:of,getFileIndex:rf,getIndexedCwd:af,findFileInIndex:cf,searchIndex:lf,isIndexValid:Ji}});var Nt=M((m$,Zi)=>{var Hn=require("fs"),zn=require("path"),Qs=require("os"),{execFile:uf}=require("child_process"),{promisify:df}=require("util"),Zs=df(uf),ff=zn.join(".nex","servers.json"),Gn=zn.join(Qs.tmpdir(),"nex-ssh-sockets");function mf(){return zn.join(process.cwd(),ff)}function Xi(){let t=mf();if(!Hn.existsSync(t))return{};try{return JSON.parse(Hn.readFileSync(t,"utf-8"))}catch{return{}}}function pf(t){let e=Xi();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 hf(){Hn.existsSync(Gn)||Hn.mkdirSync(Gn,{recursive:!0})}function Vi(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,Qs.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),hf();let s=t.user?`${t.user}@${t.host}`:t.host,n=zn.join(Gn,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function Qi(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,Qs.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function gf(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=Vi(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:c}=await Zs("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:Kn(l,t)}}}async function $f(t,e,s,{timeout:n=12e4}={}){let o=Qi(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:c}=await Zs("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(Kn(c,t)||c)}}async function yf(t,e,s,{timeout:n=12e4}={}){let o=Qi(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:c}=await Zs("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(Kn(c,t)||c)}}function Kn(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
|
|
125
131
|
HINT: Connection refused on ${e.host}:${s}. Check: server is running, SSH service is active (systemctl status sshd), firewall allows port ${s} (firewall-cmd --list-ports).`}if(/permission denied/i.test(t)){let s=e.key?`key: ${e.key}`:"SSH agent";return`${t}
|
|
126
132
|
HINT: Auth failed using ${s} as user "${e.user||"root"}". Check: authorized_keys on server, correct username, key passphrase.`}return/no route to host|network unreachable|name or service not known/i.test(t)?`${t}
|
|
127
133
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
128
134
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
129
135
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
130
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function
|
|
131
|
-
`,"utf-8")}
|
|
136
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function wf(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}`}Zi.exports={loadServerProfiles:Xi,resolveProfile:pf,buildSSHArgs:Vi,sshExec:gf,scpUpload:$f,scpDownload:yf,enrichSSHError:Kn,formatProfile:wf,SSH_SOCKET_DIR:Gn}});var no=M((p$,ta)=>{var Xt=require("fs"),eo=require("path"),bf=eo.join(".nex","deploy.json");function to(){return eo.join(process.cwd(),bf)}function ea(){let t=to();if(!Xt.existsSync(t))return{};try{return JSON.parse(Xt.readFileSync(t,"utf-8"))}catch{return{}}}function xf(t){let e=ea();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=eo.join(process.cwd(),".nex");Xt.existsSync(e)||Xt.mkdirSync(e,{recursive:!0}),Xt.writeFileSync(to(),JSON.stringify(t,null,2)+`
|
|
137
|
+
`,"utf-8")}ta.exports={loadDeployConfigs:ea,resolveDeployConfig:xf,saveDeployConfigs:_f,getDeployConfigPath:to}});var Qt=M((h$,oa)=>{var so=null,Be=null,Vt=null,na=`Playwright is not installed. Install with:
|
|
132
138
|
npm install playwright && npx playwright install chromium
|
|
133
|
-
Then restart nex-code.`;function
|
|
134
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function
|
|
135
|
-
`)}function
|
|
139
|
+
Then restart nex-code.`;function sa(){if(Vt!==null)return Vt;try{require("playwright"),Vt=!0}catch{Vt=!1}return Vt}async function Jn(){if(!sa())throw new Error(na);return so||(so=require("playwright")),(!Be||!Be.isConnected())&&(Be=await so.chromium.launch({headless:!0})),Be}async function kf(){if(Be){try{await Be.close()}catch{}Be=null}}process.on("exit",()=>{if(Be)try{Be.close()}catch{}});async function vf(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await Jn()).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?`
|
|
140
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function Sf(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await Jn()).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 Ef(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await Jn()).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 Tf(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 Jn()).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()}}oa.exports={isPlaywrightAvailable:sa,browserNavigate:vf,browserScreenshot:Sf,browserClick:Ef,browserFill:Tf,closeBrowser:kf,INSTALL_MSG:na}});var Yn=M((g$,ra)=>{var{C:V}=ae(),en="",he=[],Zt=0,pt=null;function Cf(t){pt=t}function Rf(t,e){en=t,he=[],Zt=0;for(let n of e){Zt++;let o=`t${Zt}`;he.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${Zt}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=he.map(n=>({...n}));return pt&&pt("create",{name:t,tasks:s}),s}function Af(t,e,s){let n=he.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),pt&&pt("update",{id:t,status:e,result:s}),{...n}):null}function Of(){return{name:en,tasks:he.map(t=>({...t}))}}function Nf(){en="",he=[],Zt=0,pt&&pt("clear",{})}function Mf(){return he.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=he.find(n=>n.id===e);return s&&s.status==="done"}))}function Pf(){if(he.length===0)return`${V.dim}No active tasks${V.reset}`;let t=[];en&&(t.push(` ${V.bold}${V.cyan}Tasks: ${en}${V.reset}`),t.push(` ${V.dim}${"\u2500".repeat(40)}${V.reset}`));for(let o of he){let r,i;switch(o.status){case"done":r="\u2713",i=V.green;break;case"in_progress":r="\u2192",i=V.cyan;break;case"failed":r="\u2717",i=V.red;break;default:r="\xB7",i=V.dim}let c=o.dependsOn.length>0?` ${V.dim}(after: ${o.dependsOn.join(", ")})${V.reset}`:"",l=`[${o.status}]`,u=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${V.reset} ${V.bold}${o.id}${V.reset} ${u.padEnd(40)} ${i}${l}${V.reset}${c}`),o.result&&o.status==="done"){let d=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${V.dim}\u2192 ${d}${V.reset}`)}}let e=he.filter(o=>o.status==="done").length,s=he.filter(o=>o.status==="failed").length,n=he.length;return t.push(` ${V.dim}${"\u2500".repeat(40)}${V.reset}`),t.push(` ${V.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${V.reset}`),t.join(`
|
|
141
|
+
`)}function Lf(){return he.length>0&&he.some(t=>t.status==="pending"||t.status==="in_progress")}ra.exports={createTasks:Rf,updateTask:Af,getTaskList:Of,clearTasks:Nf,getReadyTasks:Mf,renderTaskList:Pf,setOnChange:Cf,hasActiveTasks:Lf}});var ro=M(($$,aa)=>{var{getActiveModel:If,getActiveProviderName:qf}=pe(),tn={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},nn={"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"},sn={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},Me={};function ia(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(Me=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{Me={}}}ia();function oo(){let e=If()?.id,s=qf();return e&&Me[e]?Me[e]:s&&Me[`${s}:*`]?Me[`${s}:*`]:e&&nn[e]?nn[e]:s&&sn[s]?sn[s]:"full"}function jf(t,e){return t&&Me[t]?Me[t]:e&&Me[`${e}:*`]?Me[`${e}:*`]:t&&nn[t]?nn[t]:e&&sn[e]?sn[e]:"full"}function Df(t,e){let s=e||oo();if(s==="full"||!tn[s])return t;let n=new Set(tn[s]);return t.filter(o=>n.has(o.function.name))}function Ff(){let t=oo(),e=tn[t]?tn[t].length:"all";return{tier:t,toolCount:e}}aa.exports={filterToolsForModel:Df,getActiveTier:oo,getModelTier:jf,getTierInfo:Ff,TIERS:tn,MODEL_TIERS:nn,PROVIDER_DEFAULT_TIER:sn,loadConfigOverrides:ia}});var wa=M((w$,ya)=>{var{callStream:Uf,getActiveProviderName:Vn,getActiveModelId:Wf,getConfiguredProviders:Bf,getProvider:ca,getActiveProvider:la,parseModelSpec:ua}=pe(),{parseToolArgs:Hf}=Pn(),{filterToolsForModel:Gf,getModelTier:Xn}=ro(),{trackUsage:zf}=Tt(),{MultiProgress:Kf,C:y$}=ae(),Jf=15,da=5,fa=3,Qn=new Map;function Yf(t,e){let s=Qn.get(t);return s&&s!==e?!1:(Qn.set(t,e),!0)}function on(t){Qn.delete(t)}function io(){Qn.clear()}function ma(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 pa(t,e,s){let n;for(let o=0;o<=fa;o++)try{return await Uf(t,e,s)}catch(r){if(n=r,o<fa&&ma(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 Xf=new Set(["ask_user","task_list","spawn_agents"]),Vf=new Set(["write_file","edit_file","patch_file"]),Qf=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Zf=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function ha(t){return Zf.test(t)?"full":Qf.test(t)?"essential":"standard"}function ga(t){let e=Bf(),s=Vn(),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(Xn(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var em={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function ao(t){if(t.model){let{provider:o,model:r}=ua(t.model),i=o?ca(o):la(),c=o||Vn();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=Xn(r,c);return{provider:c,model:r,tier:l}}}let e=ha(t.task),s=em[e];if(s){let{provider:o,model:r}=ua(s),i=o?ca(o):la(),c=o||Vn();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=Xn(r,c);return{provider:c,model:r,tier:l}}}let n=ga(e);if(n){let o=Xn(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function $a(t,e={}){let s=Math.min(t.max_iterations||10,Jf),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.
|
|
136
142
|
|
|
137
143
|
TASK: ${t.task}
|
|
138
144
|
${t.context?`
|
|
@@ -154,116 +160,116 @@ TOOL STRATEGY:
|
|
|
154
160
|
ERROR RECOVERY:
|
|
155
161
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
156
162
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
157
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=
|
|
158
|
-
`)}let y={};d&&(y.provider=d),f&&(y.model=f);try{for(let $=0;$<s;$++){let x=await
|
|
159
|
-
...(truncated)`:
|
|
160
|
-
`)}catch(r){return o.stop(),
|
|
161
|
-
`);for(let r of o){let i=r.match(/^(\w+):\s*(.+)$/);if(!i)continue;let c=i[1].trim(),l=i[2].trim();l.startsWith("[")&&l.endsWith("]")?e[c]=l.slice(1,-1).split(",").map(u=>u.trim()).filter(Boolean):e[c]=l}s=n[2]}return{frontmatter:e,body:s}}function
|
|
162
|
-
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of
|
|
163
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=ao(t),d=u.provider,f=u.model,m=u.tier,{TOOL_DEFINITIONS:h,executeTool:p}=We(),g=Gf(h.filter($=>!Xf.has($.function.name)),m);if(f&&!t._skipLog){let $=m?` (${m})`:"";process.stderr.write(` [sub-agent: ${d}:${f}${$}]
|
|
164
|
+
`)}let y={};d&&(y.provider=d),f&&(y.model=f);try{for(let $=0;$<s;$++){let x=await pa(l,g,y);if(!x||typeof x!="object")throw new Error("Empty or invalid response from provider");if(x.usage){let C=x.usage.prompt_tokens||0,U=x.usage.completion_tokens||0;r.input+=C,r.output+=U;let I=d||Vn(),ee=f||Wf();zf(I,ee,C,U)}let A=x.content||"",k=x.tool_calls,v={role:"assistant",content:A||""};if(k&&k.length>0&&(v.tool_calls=k),l.push(v),!k||k.length===0){for(let C of i)on(C);return{task:t.task,status:"done",result:A||"(no response)",toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}let T=k.map(C=>{let U=C.function.name,I=Hf(C.function.arguments),ee=C.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!I)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${U}`,tool_call_id:ee});let B=null;if(Vf.has(U)&&I.path){let de=require("path"),me=de.isAbsolute(I.path)?I.path:de.resolve(process.cwd(),I.path);if(i.has(me)||!Yf(me,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:ee});i.add(me),B=me}return o.push(U),p(U,I,{autoConfirm:!0,silent:!0}).then(de=>{B&&(on(B),i.delete(B));let me=String(de??"");return{role:"tool",content:me.length>2e4?me.substring(0,2e4)+`
|
|
165
|
+
...(truncated)`:me,tool_call_id:ee}}).catch(de=>(B&&(on(B),i.delete(B)),{role:"tool",content:`ERROR: ${de.message}`,tool_call_id:ee}))}),S=await Promise.all(T);l.push(...S),e.onUpdate&&e.onUpdate(`step ${$+1}/${s}`)}for(let $ of i)on($);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)on(x);return{task:t.task,status:"failed",result:`Error: ${$.message}`,toolsUsed:o,tokensUsed:r,modelSpec:d&&f?`${d}:${f}`:null}}}async function tm(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>da)return`ERROR: Max ${da} parallel agents allowed, got ${e.length}`;let s=e.map(r=>ao(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 Kf(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 $a(h,{onUpdate:()=>{}}).then(p=>(o.update(f,p.status==="failed"?"error":"done"),p)).catch(p=>(o.update(f,"error"),{task:d.task,status:"failed",result:`Error: ${p.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),i=await Promise.all(r);o.stop(),io();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(`
|
|
166
|
+
`)}catch(r){return o.stop(),io(),`ERROR: Sub-agent execution failed: ${r.message}`}}ya.exports={runSubAgent:$a,executeSpawnAgents:tm,clearAllLocks:io,classifyTask:ha,pickModelForTier:ga,resolveSubAgentModel:ao,isRetryableError:ma,callWithRetry:pa}});var cn=M((b$,Na)=>{var te=require("fs"),He=require("path"),nm=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 Mt(){let t=He.join(process.cwd(),".nex","brain");return te.existsSync(t)||te.mkdirSync(t,{recursive:!0}),t}function ba(){return He.join(Mt(),".brain-index.json")}function uo(){return He.join(Mt(),".embeddings.json")}function rn(){let t=He.join(process.cwd(),".nex","brain");if(!te.existsSync(t))return[];try{return te.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=He.join(t,e),n=te.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 an(t){let e={},s=t,n=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);if(n){let o=n[1].split(`
|
|
167
|
+
`);for(let 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 xa(t){let e=He.join(Mt(),`${t}.md`);if(!te.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=te.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=an(s);return{name:t,content:s,body:o,frontmatter:n}}function sm(t,e){let s=He.join(Mt(),`${t}.md`);te.writeFileSync(s,e,"utf-8"),im(t,e),om()}function om(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=uo();te.existsSync(t)&&setImmediate(async()=>{try{await Ca()}catch{}})}function rm(t){let e=He.join(Mt(),`${t}.md`);return te.existsSync(e)?(te.unlinkSync(e),am(t),!0):!1}function Zn(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!nm.has(e))}function fo(t){let e={},{frontmatter:s,body:n}=an(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(`
|
|
168
|
+
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of Zn(c))e[l]=(e[l]||0)+3}for(let i of Zn(n||t))e[i]=(e[i]||0)+1;return e}function mo(){let t=ba();if(!te.existsSync(t))return{documents:{}};try{return JSON.parse(te.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function po(t){te.writeFileSync(ba(),JSON.stringify(t,null,2),"utf-8")}function im(t,e){let s=mo(),{frontmatter:n}=an(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:fo(e),tags:o,modified:new Date().toISOString()},po(s)}function am(t){let e=mo();delete e.documents[t],po(e)}function lo(){let t=rn(),e={documents:{}};for(let s of t){let n=te.readFileSync(s.path,"utf-8"),{frontmatter:o}=an(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:fo(n),tags:r,modified:s.modified.toISOString()}}return po(e),e}function _a(){let t=mo(),e=rn();for(let s of e){let n=t.documents[s.name];if(!n||new Date(n.modified)<s.modified)return lo()}for(let s of Object.keys(t.documents))if(!e.some(n=>n.name===s))return lo();return t}function ka(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=Zn(t);if(o.length===0)return[];let r=_a(),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 va=process.env.NEX_EMBED_MODEL||"nomic-embed-text",co=400,cm=50;async function Sa(){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(va.split(":")[0]))}catch{return!1}}async function ho(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:va,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 Ea(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 Ta(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+co).join(" ");if(s.push({text:o,offset:n}),n+co>=e.length)break;n+=co-cm}return s}async function Ca(){let t=rn(),e={documents:{}},s=uo();if(te.existsSync(s))try{e=JSON.parse(te.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=te.readFileSync(n.path,"utf-8"),i=Ta(r),c=[];for(let l of i){let u=await ho(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 te.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function Ra(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=uo();if(!te.existsSync(o))return[];let r;try{r=JSON.parse(te.readFileSync(o,"utf-8"))}catch{return[]}let i=await ho(t),c=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,f="";for(let m of u.chunks||[]){let h=Ea(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 Aa(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 Oa(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=ka(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await Sa()){let c=await Ra(t,{topK:s});r=Aa(o,c,{topK:s})}}catch{}return r.map(i=>{let c=xa(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 lm(t){if(!t||!t.trim())return"";let e=He.join(process.cwd(),".nex","brain");if(!te.existsSync(e)||rn().length===0)return"";let n;try{n=await Oa(t,{topK:3})}catch{return""}if(!n||n.length===0)return"";let o;try{o=Ce().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))+`
|
|
163
169
|
...(truncated)`}let f=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(i.push(`--- ${l.name} (relevance: ${f}) ---
|
|
164
170
|
${u}`),c+=o(u),c>=r)break}return i.length===0?"":`KNOWLEDGE BASE (auto-selected):
|
|
165
171
|
|
|
166
172
|
${i.join(`
|
|
167
173
|
|
|
168
|
-
`)}`}
|
|
169
|
-
${i.map(l=>
|
|
170
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
174
|
+
`)}`}Na.exports={getBrainDir:Mt,listDocuments:rn,readDocument:xa,writeDocument:sm,removeDocument:rm,buildIndex:lo,getIndex:_a,query:Oa,getBrainContext:lm,isEmbeddingAvailable:Sa,generateEmbedding:ho,buildEmbeddingIndex:Ca,semanticQuery:Ra,cosineSimilarity:Ea,_keywordQuery:ka,_extractKeywords:fo,_chunkText:Ta,parseFrontmatter:an,tokenize:Zn,_fuseResults:Aa}});var We=M((v$,Ba)=>{var ne=require("fs").promises,Ma=require("fs"),be=require("path"),oe=require("util").promisify(require("child_process").exec),Pa=require("util").promisify(require("child_process").execFile),{spawnSync:um}=require("child_process"),go=require("axios"),{isForbidden:dm,isDangerous:fm,isCritical:La,confirm:Pe}=Ne(),{showClaudeDiff:es,showClaudeNewFile:mm,showEditDiff:x$,confirmFileChange:ln}=bi(),{C:P,Spinner:Fa,getToolSpinnerText:pm}=ae(),{isGitRepo:$o,getCurrentBranch:Ia,getStatus:hm,getDiff:gm}=mt(),{recordChange:ts}=Rt(),{fuzzyFindText:qa,findMostSimilar:wo}=Hi(),{runDiagnostics:un}=zi(),{findFileInIndex:$m,getFileIndex:_$}=Vs(),{resolveProfile:Le,sshExec:Qe,scpUpload:ym,scpDownload:wm}=Nt(),{resolveDeployConfig:bm,loadDeployConfigs:k$}=no(),xm=/^(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/,km=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function ns(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=we(e);if(s&&await ne.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=be.extname(t);if(!o)for(let i of n){let c=we(t+i);if(c&&await ne.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=we(i+c);if(l&&await ne.access(l).then(()=>!0).catch(()=>!1))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${c})`}}}let r=be.basename(t);if(r&&r.length>2)try{let i=$m(r).map(c=>we(c));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${be.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
175
|
+
${i.map(l=>be.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
176
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function vm(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 Ua(t,e){let s=[];if(/command not found|not recognized/i.test(t)){let n=e.match(/^(\S+)/),o=n?n[1]:"";/^(npx|npm|node|yarn|pnpm|bun)$/.test(o)?s.push("HINT: Node.js/npm may not be in PATH. Check your Node.js installation."):/^(python|python3|pip|pip3)$/.test(o)?s.push("HINT: Python may not be installed. Try: brew install python3 (macOS) or apt install python3 (Linux)"):s.push(`HINT: "${o}" is not installed. Try installing it with your package manager.`)}if(/Cannot find module|MODULE_NOT_FOUND/i.test(t)){let n=t.match(/Cannot find module '([^']+)'/),o=n?n[1]:"";o&&!o.startsWith(".")&&!o.startsWith("/")?s.push(`HINT: Missing npm package "${o}". Run: npm install ${o}`):s.push("HINT: Module not found. Check the import path or run npm install.")}if(/permission denied|EACCES/i.test(t)&&s.push("HINT: Permission denied. Check file permissions or try a different approach."),/EADDRINUSE|address already in use/i.test(t)){let n=t.match(/port (\d+)|:(\d+)/),o=n?n[1]||n[2]:"";s.push(`HINT: Port ${o||""} is already in use. Kill the process or use a different port.`)}if(/SyntaxError|Unexpected token/i.test(t)&&s.push("HINT: Syntax error in the code. Check the file at the line number shown above."),/TS\d{4}:/i.test(t)&&s.push("HINT: TypeScript compilation error. Fix the type issue at the indicated line."),/Test Suites:.*failed|Tests:.*failed/i.test(t)&&s.push("HINT: Test failures detected. Read the error output above to identify failing tests."),/fatal: not a git repository/i.test(t)&&s.push("HINT: Not inside a git repository. Run git init or cd to a git project."),/^curl\b/.test(e)){let n=t.match(/curl:\s*\((\d+)\)/),o=n?parseInt(n[1],10):null;o===6||/Could not resolve host/i.test(t)?s.push("HINT: Hostname could not be resolved. Check DNS or use an IP address directly."):o===7||/Failed to connect|Connection refused/i.test(t)?s.push("HINT: Service not running or port wrong. Check if the service is up and the port is correct."):o===22||/HTTP error/i.test(t)?s.push("HINT: HTTP 4xx/5xx response. The endpoint exists but returned an error status."):o===28||/timed out/i.test(t)?s.push("HINT: Request timed out. The host may be unreachable or the service is slow."):(o===35||/SSL.*error/i.test(t))&&s.push("HINT: SSL/TLS handshake failed. Try with --insecure to bypass, or check the certificate.")}if(/remote port forwarding failed/i.test(t)){let n=t.match(/port (\d+)/),o=n?n[1]:"";s.push(`HINT: SSH remote port forwarding failed for port ${o}. The port may already be bound on the server. Check with: ssh server "ss -tuln | grep ${o}" and kill any lingering process with that port.`)}return/bind.*Cannot assign requested address|Address already in use/i.test(t)&&s.push("HINT: Port is already in use. Find the process with: ss -tuln | grep <port> and kill it, then retry."),/Connection.*timed out|ssh.*timeout/i.test(t)&&/^ssh\b/.test(e)&&s.push("HINT: SSH connection timed out. Check if the host is reachable: ping <host> and verify the port with: nc -zv <host> 22"),s.length===0?t:t+`
|
|
171
177
|
|
|
172
178
|
`+s.join(`
|
|
173
|
-
`)}function Da(t,e,s){let n=$o(t,e);if(!n)return null;let o=Math.max(3,Math.ceil(e.length*.05));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var La=!1,un=null;function _m(){un&&(un(),un=null)}async function go(){if(!La){La=!0;try{let{stdout:t}=await Z("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await Z('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await Z("git stash pop",{cwd:process.cwd(),timeout:1e4}),await Z("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var km=[/\.ssh\//i,/\.gnupg\//i,/\.aws\//i,/\.config\/gcloud/i,/\/etc\/shadow/,/\/etc\/passwd/,/\/etc\/sudoers/,/\.env(?:\.|$)/,/credentials/i,/\.npmrc$/,/\.docker\/config\.json/,/\.kube\/config/];function be(t){let e=xe.isAbsolute(t)?xe.resolve(t):xe.resolve(process.cwd(),t);for(let s of km)if(s.test(e))return null;return e}var vm=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Use this to find where functions/variables/classes are defined or used. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a question and wait for their response. Use when requirements are ambiguous, you need to choose between approaches, or a decision has significant impact. Do not ask unnecessary questions \u2014 proceed if the intent is clear.",parameters:{type:"object",properties:{question:{type:"string",description:"The question to ask the user"}},required:["question"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"deploy",description:'Deploy files to a remote server via rsync + optional remote script. Can use a named config from .nex/deploy.json (e.g. deploy("prod")) or explicit params. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},local_path:{type:"string",description:'Local directory or file to sync (e.g. "dist/", "./build"). Required if no config.'},remote_path:{type:"string",description:'Remote destination path (e.g. "/var/www/app"). Required if no config.'},deploy_script:{type:"string",description:"Shell command to run on the remote after sync. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from sync. Optional."},dry_run:{type:"boolean",description:"Show what would be synced without actually syncing. Default: false."}},required:[]}}}];function ln(t,{server:e,context:s}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,o=s?s.replace(/[^a-zA-Z0-9._/-]/g,""):null,r="kubectl";if(o&&(r+=` --context ${o}`),r+=` ${t}`,n){let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${i}"`}return r}async function Ia(t,e,s={}){switch(t){case"bash":{let n=e.command,o=cm(n);if(o){let u=xm(n);return`BLOCKED: Command matches forbidden pattern: ${o}${u?`
|
|
174
|
-
HINT: ${u}`:""}`}if(s.autoConfirm?
|
|
175
|
-
${P.yellow}${u}: ${n}${P.reset}`),!await
|
|
176
|
-
${f}`}}case"read_file":{let n=
|
|
177
|
-
`+m.message:""}`}let r=Buffer.alloc(8192),i=await
|
|
179
|
+
`)}function Wa(t,e,s){let n=wo(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 ja=!1,fn=null;function Sm(){fn&&(fn(),fn=null)}async function yo(){if(!ja){ja=!0;try{let{stdout:t}=await oe("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await oe('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await oe("git stash pop",{cwd:process.cwd(),timeout:1e4}),await oe("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Em=[/\.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 we(t){let e=be.isAbsolute(t)?be.resolve(t):be.resolve(process.cwd(),t);for(let s of Em)if(s.test(e))return null;return e}var Tm=[{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 dn(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 Da(t,e,s={}){switch(t){case"bash":{let n=e.command,o=dm(n);if(o){let u=vm(n);return`BLOCKED: Command matches forbidden pattern: ${o}${u?`
|
|
180
|
+
HINT: ${u}`:""}`}if(s.autoConfirm?La(n):fm(n)){let u=La(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
|
|
181
|
+
${P.yellow}${u}: ${n}${P.reset}`),!await Pe(" Execute?"))return"CANCELLED: User declined to execute this command."}let i=process.cwd();try{Ma.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())&&!km.test(n.trim());if(xm.test(n.trim())||c){s.silent||console.log(`${P.dim} \u25B6 interactive: ${n}${P.reset}`);let u=um("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 Fa(`Running: ${n.substring(0,60)}${n.length>60?"...":""}`);l&&l.start();try{let{stdout:u,stderr:d}=await oe(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=Ua(d,n);return`EXIT ${u.code||1}
|
|
182
|
+
${f}`}}case"read_file":{let n=we(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ne.access(n).then(()=>!0).catch(()=>!1)){let m=await ns(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${P.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${be.relative(process.cwd(),n)}${P.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
183
|
+
`+m.message:""}`}let r=Buffer.alloc(8192),i=await Ma.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 ne.readFile(n,"utf-8");if(!l&&(await ne.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let u=l.split(`
|
|
178
184
|
`),d=(e.line_start||1)-1,f=e.line_end||u.length;return u.slice(d,f).map((m,h)=>`${d+h+1}: ${m}`).join(`
|
|
179
|
-
`)}case"write_file":{await
|
|
180
|
-
`+d.message:""}`}let r=await
|
|
185
|
+
`)}case"write_file":{await yo();let n=we(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await ne.access(n).then(()=>!0).catch(()=>!1),r=null;if(s.autoConfirm)o&&(r=await ne.readFile(n,"utf-8"));else if(o){r=await ne.readFile(n,"utf-8");let l=await un(n,e.content);if(es(n,r,e.content,{annotations:l}),!await ln("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let l=await un(n,e.content);if(mm(n,e.content,{annotations:l}),!await ln("Create"))return"CANCELLED: User declined to create file."}let i=be.dirname(n);return await ne.access(i).then(()=>!0).catch(()=>!1)||await ne.mkdir(i,{recursive:!0}),await ne.writeFile(n,e.content,"utf-8"),ts("write_file",n,r,e.content),`Written: ${n} (${e.content.length} chars)`}case"edit_file":{await yo();let n=we(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ne.access(n).then(()=>!0).catch(()=>!1)){let d=await ns(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${P.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${be.relative(process.cwd(),n)}${P.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
186
|
+
`+d.message:""}`}let r=await ne.readFile(n,"utf-8"),i=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let d=qa(r,e.old_text);if(d)i=d,c=!0,console.log(`${P.dim} \u2713 fuzzy whitespace match applied${P.reset}`);else{let f=Wa(r,e.old_text,e.new_text);if(f){if(!s.autoConfirm){let p=await un(n,f.content);if(es(n,r,f.content,{annotations:p}),!await ln(`Apply (auto-fix, line ${f.line}, distance ${f.distance})`))return"CANCELLED: User declined to apply edit."}await ne.writeFile(n,f.content,"utf-8"),ts("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=wo(r,e.old_text);return m?`ERROR: old_text not found in ${n}
|
|
181
187
|
Most similar text (line ${m.line}, distance ${m.distance}):
|
|
182
|
-
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=r.split(i).join(e.new_text),f=await
|
|
183
|
-
`)||"(empty)"}case"search_files":{let n=
|
|
188
|
+
${m.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=r.split(i).join(e.new_text),f=await un(n,d);if(es(n,r,d,{annotations:f}),!await ln(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(i).join(e.new_text);return await ne.writeFile(n,u,"utf-8"),ts("edit_file",n,r,u),c?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=we(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ne.access(n).then(()=>!0).catch(()=>!1)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=we(u),f=await ne.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 ne.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(be.join(u,h.name),d+1,f+" ")}};return await l(n,1,""),c.join(`
|
|
189
|
+
`)||"(empty)"}case"search_files":{let n=we(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 Pa("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
184
190
|
`).slice(0,50).join(`
|
|
185
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?
|
|
186
|
-
`);return x?`${
|
|
191
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?we(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}=Vs(),g=f(),y=m();p(r)||(await h(r),g=f());let $=g.filter(k=>l.test(k)||d.test(be.basename(k))).map(k=>be.join(r,k));if($.length===0)return"(no matches)";let x=$.length>200,A=$.slice(0,200).join(`
|
|
192
|
+
`);return x?`${A}
|
|
187
193
|
|
|
188
|
-
\u26A0 Results truncated at 200. Use a more specific pattern.`:
|
|
194
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:A}case"grep":{let n=e.path?we(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 Pa("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152});return r.split(`
|
|
189
195
|
`).slice(0,100).join(`
|
|
190
|
-
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await
|
|
191
|
-
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await
|
|
196
|
+
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await yo();let n=we(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await ne.access(n).then(()=>!0).catch(()=>!1)){let m=await ns(e.path);if(m.fixedPath)n=m.fixedPath,console.log(`${P.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${be.relative(process.cwd(),n)}${P.reset}`);else return`ERROR: File not found: ${e.path}${m.message?`
|
|
197
|
+
`+m.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await ne.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=qa(i,h);if(g)c.push({old_text:g,new_text:p}),l=!0;else{let y=wo(i,h);if(y){let $=Math.max(3,Math.ceil(h.length*.05));if(y.distance<=$)c.push({old_text:y.text,new_text:p}),u=!0;else return`ERROR: Patch ${m+1} old_text not found in ${n}
|
|
192
198
|
Most similar text (line ${y.line}, distance ${y.distance}):
|
|
193
|
-
${y.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${n}`}}}let d=i;for(let{old_text:m,new_text:h}of c)d=d.split(m).join(h);if(!s.autoConfirm){let m=await
|
|
199
|
+
${y.text}`}else return`ERROR: Patch ${m+1} old_text not found in ${n}`}}}let d=i;for(let{old_text:m,new_text:h}of c)d=d.split(m).join(h);if(!s.autoConfirm){let m=await un(n,d);if(es(n,i,d,{annotations:m}),!await ln(l?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await ne.writeFile(n,d,"utf-8"),ts("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 go.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 go.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]
|
|
194
200
|
|
|
195
201
|
${r}`;return i.length>0&&(c+=`
|
|
196
202
|
|
|
197
203
|
Sources:
|
|
198
204
|
`+i.slice(0,n).map((l,u)=>`${u+1}. ${l}`).join(`
|
|
199
|
-
`)),c}catch(o){console.error(`${P.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${P.reset}`)}try{let r=(await
|
|
205
|
+
`)),c}catch(o){console.error(`${P.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${P.reset}`)}try{let r=(await go.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}
|
|
200
206
|
${u.url}`).join(`
|
|
201
207
|
|
|
202
|
-
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=
|
|
208
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=Qt();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
|
|
203
209
|
|
|
204
210
|
Links:
|
|
205
211
|
`+o.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
|
|
206
212
|
`):"";return`Title: ${o.title}
|
|
207
213
|
URL: ${o.url}
|
|
208
214
|
|
|
209
|
-
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=
|
|
215
|
+
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=Qt();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
|
|
210
216
|
Title: ${o.title}
|
|
211
217
|
URL: ${o.url}
|
|
212
218
|
|
|
213
|
-
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=
|
|
214
|
-
${P.cyan}${P.bold} ? ${n}${P.reset}`),r.question(`${P.cyan} > ${P.reset}`,i=>{
|
|
219
|
+
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=Qt();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=Qt();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});fn=()=>{r.close(),o("CANCELLED")},console.log(`
|
|
220
|
+
${P.cyan}${P.bold} ? ${n}${P.reset}`),r.question(`${P.cyan} > ${P.reset}`,i=>{fn=null,r.close(),o(i.trim()||"(no response)")})})}case"git_status":{if(!await $o())return"ERROR: Not a git repository";let n=await Ia()||"(detached)",o=await hm();if(o.length===0)return`Branch: ${n}
|
|
215
221
|
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(`
|
|
216
|
-
`)}case"git_diff":{if(!await
|
|
222
|
+
`)}case"git_diff":{if(!await $o())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 gm(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await $o())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}=Yn(),{getActiveTaskProgress:l}=ae(),u=l();switch(e.action){case"create":{if(!e.name||!e.tasks)return"ERROR: task_list create requires name and tasks";let d=n(e.name,e.tasks);return u||console.log(`
|
|
217
223
|
`+i()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
218
224
|
`+d.map(f=>` ${f.id}: ${f.description}`).join(`
|
|
219
225
|
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":o(e.task_id,e.status,e.result)?(u||console.log(`
|
|
220
226
|
`+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(`
|
|
221
|
-
`+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}=
|
|
227
|
+
`+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}=wa();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=pe();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 oe(`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(`
|
|
222
228
|
`)}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(`
|
|
223
|
-
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await
|
|
224
|
-
...(truncated)`:"")}let{stdout:n}=await
|
|
229
|
+
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await oe(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
|
|
230
|
+
...(truncated)`:"")}let{stdout:n}=await oe(`gh run view ${e.run_id} --json status,conclusion,name,headBranch,createdAt,updatedAt,jobs`,{cwd:process.cwd(),timeout:3e4}),o=JSON.parse(n),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(`
|
|
225
231
|
`)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
|
|
226
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=
|
|
227
|
-
${P.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${P.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await
|
|
228
|
-
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=
|
|
229
|
-
`)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",o=e.tail||100,r=`logs ${e.pod} -n ${n} --tail=${o}`;e.since&&(r+=` --since=${e.since}`),e.container&&(r+=` -c ${e.container}`);let i=
|
|
232
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=Ne(),o=e.branch||await Ia()||"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(`
|
|
233
|
+
${P.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${P.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await oe(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(`
|
|
234
|
+
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=dn(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:c}=await oe(r,{timeout:3e4,maxBuffer:2097152});return(i||c||"(no pods)").trim()}catch(i){let c=(i.stderr||i.message||"").toString().split(`
|
|
235
|
+
`)[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=dn(r,e);try{let{stdout:c,stderr:l}=await oe(i,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
|
|
230
236
|
...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
231
237
|
`)[0]}`}}case"k8s_exec":{if(!e.pod)return"ERROR: pod is required";if(!e.command)return"ERROR: command is required";let n=e.namespace||"default";if(console.log(`
|
|
232
|
-
${P.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${P.reset}`),console.log(`${P.dim} Command: ${e.command}${P.reset}`),!await
|
|
238
|
+
${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=dn(r,e);try{let{stdout:c,stderr:l}=await oe(i,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
233
239
|
`)[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(`
|
|
234
|
-
${P.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${P.reset}`),!await
|
|
240
|
+
${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=dn(o,e);try{let{stdout:i,stderr:c}=await oe(r,{timeout:12e4,maxBuffer:2097152});return(i||c||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
|
|
235
241
|
`)[0]}`}}case"k8s_rollout":{if(!e.action)return"ERROR: action is required";if(!e.deployment)return"ERROR: deployment is required";let n=e.namespace||"default";if(e.action==="restart"||e.action==="undo"){let c=e.action==="restart"?"Rolling restart":"Rollback (undo)";if(console.log(`
|
|
236
|
-
${P.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${n})${P.reset}`),!await
|
|
237
|
-
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:o}=
|
|
242
|
+
${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=dn(r,e);try{let{stdout:c,stderr:l}=await oe(i,{timeout:12e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
243
|
+
`)[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}=cn(),{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+`
|
|
238
244
|
|
|
239
|
-
`+i:i;return n(r,u),`Appended to brain document: ${r}.md`}return n(r,i),`${c==="create"?"Created":"Updated"} brain document: ${r}.md`}case"ssh_exec":{if(!e.server)return"ERROR: server is required";if(!e.command)return"ERROR: command is required";let n;try{n=
|
|
240
|
-
${P.yellow} \u26A0 Remote command on ${h}: ${o}${P.reset}`),!await
|
|
245
|
+
`+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(`
|
|
246
|
+
${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 Qe(n,o,{timeout:i,sudo:r}),m=[l,u].filter(Boolean).join(`
|
|
241
247
|
`).trim();return d!==0?`EXIT ${d}
|
|
242
|
-
${f||m||"(no output)"}`:m||"(command completed, no output)"}case"ssh_upload":{if(!e.server||!e.local_path||!e.remote_path)return"ERROR: server, local_path, and remote_path are required";let n;try{n=
|
|
243
|
-
${P.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${P.reset}`),!await
|
|
244
|
-
${P.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${P.reset}`),!await
|
|
245
|
-
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await
|
|
248
|
+
${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(`
|
|
249
|
+
${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 ym(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 wm(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(`
|
|
250
|
+
${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 oe(u,{timeout:15e3});return(d||f||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(d){let f=(d.stderr||d.message||"").toString().trim();return/not found|loaded.*not-found/i.test(f)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${d.code||1}
|
|
251
|
+
${f}`}}else{let{stdout:l,stderr:u,exitCode:d,error:f}=await Qe(i,c,{timeout:15e3,sudo:!0}),m=[l,u].filter(Boolean).join(`
|
|
246
252
|
`).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}
|
|
247
|
-
${f||m||"(no output)"}`:m||`systemctl ${e.action} ${e.service}: OK`}}case"service_logs":{if(!e.service)return"ERROR: service is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,r=e.since?`--since "${e.since}"`:"",i=e.follow?"-f":"",c=`journalctl -u ${e.service} -n ${o} ${r} ${i} --no-pager`.trim().replace(/\s+/g," ");if(n)try{let{stdout:p,stderr:g}=await
|
|
248
|
-
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=
|
|
253
|
+
${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 oe(c,{timeout:15e3});return(p||g||"(no log output)").trim()}catch(p){return`EXIT ${p.code||1}
|
|
254
|
+
${(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 Qe(l,c,{timeout:2e4}),h=[u,d].filter(Boolean).join(`
|
|
249
255
|
`).trim();return f!==0?`EXIT ${f}
|
|
250
|
-
${m||h||"(no output)"}`:h||"(no log output)"}case"container_list":{let n=!e.server||e.server==="local"||e.server==="localhost",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
|
|
251
|
-
${(m.stderr||m.message||"").toString().trim()}`}let i;try{i=
|
|
256
|
+
${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 oe(r,{timeout:1e4});return(m||h||"(no containers)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
257
|
+
${(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 Qe(i,r,{timeout:15e3}),f=[c,l].filter(Boolean).join(`
|
|
252
258
|
`).trim();return u!==0?`EXIT ${u}
|
|
253
|
-
${d||f}`:f||"(no containers)"}case"container_logs":{if(!e.container)return"ERROR: container is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=e.lines||50,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
|
|
254
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=
|
|
259
|
+
${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 oe(i,{timeout:15e3});return(h||p||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
260
|
+
${(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 Qe(c,i,{timeout:2e4}),m=[l,u].filter(Boolean).join(`
|
|
255
261
|
`).trim();return d!==0?`EXIT ${d}
|
|
256
262
|
${f||m}`:m||"(no log output)"}case"container_exec":{if(!e.container)return"ERROR: container is required";if(!e.command)return"ERROR: command is required";let n=!e.server||e.server==="local"||e.server==="localhost",o=/^(cat|ls|echo|env|printenv|df|du|ps|id|whoami|uname|hostname|date|pwd|which|find\s|head\s|tail\s|grep\s|curl\s+-[A-Za-z]*G|curl\s+https?:\/\/[^\s]+$)/;if(!s.autoConfirm&&!o.test(e.command.trim())){let h=n?"local":e.server;if(console.log(`
|
|
257
|
-
${P.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${P.reset}`),!await
|
|
258
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=
|
|
263
|
+
${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 oe(i,{timeout:3e4});return(h||p||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
264
|
+
${(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 Qe(c,i,{timeout:35e3}),m=[l,u].filter(Boolean).join(`
|
|
259
265
|
`).trim();return d!==0?`EXIT ${d}
|
|
260
266
|
${f||m}`:m||"(no output)"}case"container_manage":{if(!e.container)return"ERROR: container is required";if(!e.action)return"ERROR: action is required";let n=["start","stop","restart","remove","inspect"];if(!n.includes(e.action))return`ERROR: invalid action "${e.action}". Valid: ${n.join(", ")}`;let o=!e.server||e.server==="local"||e.server==="localhost";if(!(e.action==="inspect")&&!s.autoConfirm){let p=o?"local":e.server;if(console.log(`
|
|
261
|
-
${P.yellow} \u26A0 docker ${e.action} ${e.container} on ${p}${P.reset}`),!await
|
|
262
|
-
${(p.stderr||p.message||"").toString().trim()}`}let l;try{l=
|
|
267
|
+
${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 oe(c,{timeout:3e4});return(p||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(p){return`EXIT ${p.code||1}
|
|
268
|
+
${(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 Qe(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
|
|
263
269
|
`).trim();return f!==0?`EXIT ${f}
|
|
264
|
-
${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={
|
|
265
|
-
${P.yellow} \u26A0 Deploy: ${d} \u2192 ${o}:${e.remote_path}${P.reset}`),e.deploy_script&&console.log(`${P.yellow} Then run: ${e.deploy_script}${P.reset}`),!await
|
|
266
|
-
${m||"(nothing to sync)"}`;let h="";if(e.deploy_script){let{stdout:p,stderr:g,exitCode:y,error:$}=await
|
|
270
|
+
${m||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...bm(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(`
|
|
271
|
+
${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 oe(f,{timeout:12e4});m=(p||g||"").trim()}catch(p){return`ERROR (rsync): ${(p.stderr||p.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN:
|
|
272
|
+
${m||"(nothing to sync)"}`;let h="";if(e.deploy_script){let{stdout:p,stderr:g,exitCode:y,error:$}=await Qe(n,e.deploy_script,{timeout:6e4}),x=[p,g].filter(Boolean).join(`
|
|
267
273
|
`).trim();if(y!==0)return`rsync OK
|
|
268
274
|
|
|
269
275
|
ERROR (deploy_script, exit ${y}):
|
|
@@ -271,33 +277,33 @@ ${$||x}`;h=`
|
|
|
271
277
|
|
|
272
278
|
Remote script output:
|
|
273
279
|
${x||"(no output)"}`}return`Deployed ${d} \u2192 ${o}:${e.remote_path}
|
|
274
|
-
${m}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function
|
|
275
|
-
`)}function
|
|
280
|
+
${m}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function Cm(t,e,s={}){let n=s.silent?null:pm(t,e);if(!n)return Da(t,e,s);let o=new Fa(n);o.start();try{let r=await Da(t,e,s);return o.stop(),r}catch(r){throw o.stop(),r}}Ba.exports={TOOL_DEFINITIONS:Tm,executeTool:Cm,resolvePath:we,autoFixPath:ns,autoFixEdit:Wa,enrichBashError:Ua,cancelPendingAskUser:Sm}});var Ga=M((S$,Ha)=>{var{loadServerProfiles:xo}=Nt(),bo={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 Rm(){let t=xo();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&&bo[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 bo[o])s.push(`- ${i}`)}}return s.join(`
|
|
281
|
+
`)}function Am(t){let e=xo();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function Om(){return Object.keys(xo())}Ha.exports={getServerContext:Rm,hasServerOS:Am,getProfileNames:Om,OS_HINTS:bo}});var ko=M((E$,Ka)=>{var Ae=require("fs").promises,Ee=require("path"),ss=require("util").promisify(require("child_process").exec),{C:Ie}=ae(),{getMergeConflicts:za}=mt(),{getServerContext:Nm}=Ga(),_o=new Map,Pt=new Map,os=null,Mm=3e4;async function Ze(t){try{return await t()}catch{return null}}async function Pm(){if(!os||Date.now()>os)return!1;let t=[Ee.join(process.cwd(),"package.json"),Ee.join(process.cwd(),"README.md"),Ee.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await Ae.stat(e),n=Pt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(Pt.has(e))return!1}try{let e=Ee.join(process.cwd(),".git","HEAD"),s=await Ae.stat(e),n=Pt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function Lm(){let t=[Ee.join(process.cwd(),"package.json"),Ee.join(process.cwd(),"README.md"),Ee.join(process.cwd(),".gitignore"),Ee.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await Ae.stat(e);Pt.set(e,s.mtimeMs)}catch{Pt.delete(e)}}async function Im(t){let e="fileContext",s=_o.get(e),n=!1;if(s&&await Pm()&&(n=!0),!n){let u=[],d=Ee.join(t,"package.json");if(await Ze(()=>Ae.access(d).then(()=>!0).catch(()=>!1)))try{let y=await Ae.readFile(d,"utf-8"),$=JSON.parse(y),x={name:$.name,version:$.version};$.scripts&&(x.scripts=Object.keys($.scripts).slice(0,15)),$.dependencies&&(x.deps=Object.keys($.dependencies).length),$.devDependencies&&(x.devDeps=Object.keys($.devDependencies).length),u.push(`PACKAGE: ${JSON.stringify(x)}`)}catch{}let m=Ee.join(t,"README.md");if(await Ze(()=>Ae.access(m).then(()=>!0).catch(()=>!1))){let $=(await Ae.readFile(m,"utf-8")).split(`
|
|
276
282
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
277
283
|
${$.join(`
|
|
278
|
-
`)}`)}let p=
|
|
284
|
+
`)}`)}let p=Ee.join(t,".gitignore");if(await Ze(()=>Ae.access(p).then(()=>!0).catch(()=>!1))){let y=await Ae.readFile(p,"utf-8");u.push(`GITIGNORE:
|
|
279
285
|
${y.trim()}`)}s=u.join(`
|
|
280
286
|
|
|
281
|
-
`),
|
|
287
|
+
`),_o.set(e,s),os=Date.now()+Mm,await Lm()}let o=[s],[r,i,c,l]=await Promise.all([Ze(async()=>{let{stdout:u}=await ss("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),Ze(async()=>{let{stdout:u}=await ss("git status --short",{cwd:t,timeout:5e3});return u.trim()}),Ze(async()=>{let{stdout:u}=await ss("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),za()]);if(r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
|
|
282
288
|
${i}`),c&&o.push(`RECENT COMMITS:
|
|
283
289
|
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
284
290
|
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
285
|
-
${u}`)}try{let u=
|
|
291
|
+
${u}`)}try{let u=Nm();u&&o.push(u)}catch{}return o.join(`
|
|
286
292
|
|
|
287
|
-
`)}async function
|
|
288
|
-
${e}`);let s=
|
|
289
|
-
${s}`);let n=
|
|
293
|
+
`)}async function qm(t){let e=Ee.join(t,"package.json"),s="";if(await Ze(()=>Ae.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Ae.readFile(e,"utf-8"),c=JSON.parse(i);s=`${c.name||"?"} v${c.version||"?"}`}catch{}let[o,r]=await Promise.all([Ze(async()=>{let{stdout:i}=await ss("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),za()]);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()}Ka.exports={gatherProjectContext:Im,printContext:qm,_clearContextCache:()=>{_o.clear(),Pt.clear(),os=null}}});var gt=M((T$,Va)=>{var ze=require("fs"),vo=require("path");function rs(){return vo.join(process.cwd(),".nex","sessions")}function Ja(){let t=rs();ze.existsSync(t)||ze.mkdirSync(t,{recursive:!0})}function So(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return vo.join(rs(),`${e}.json`)}function Eo(t,e,s={}){Ja();let n=So(t),o={name:t,createdAt:s.createdAt||new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:e.length,model:s.model||null,provider:s.provider||null,messages:e};return ze.writeFileSync(n,JSON.stringify(o,null,2),"utf-8"),{path:n,name:t}}function Ya(t){let e=So(t);if(!ze.existsSync(e))return null;try{return JSON.parse(ze.readFileSync(e,"utf-8"))}catch{return null}}function Xa(){Ja();let t=rs(),e=ze.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(ze.readFileSync(vo.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 jm(t){let e=So(t);return ze.existsSync(e)?(ze.unlinkSync(e),!0):!1}function Dm(){let t=Xa();return t.length===0?null:Ya(t[0].name)}var ht=null,Ge=null,mn=null;function Fm(t,e={}){t.length!==0&&(ht&&clearTimeout(ht),Ge=t,mn=e||{},ht=setTimeout(()=>{Ge&&Ge.length>0&&Eo("_autosave",Ge,mn),ht=null,Ge=null,mn=null},5e3))}function Um(){ht&&(clearTimeout(ht),ht=null),Ge&&Ge.length>0&&(Eo("_autosave",Ge,mn),Ge=null,mn=null)}Va.exports={saveSession:Eo,loadSession:Ya,listSessions:Xa,deleteSession:jm,getLastSession:Dm,autoSave:Fm,flushAutoSave:Um,_getSessionsDir:rs}});var et=M((C$,sc)=>{var Ke=require("fs"),is=require("path"),Wm=require("os");function To(){return is.join(process.cwd(),".nex","memory")}function Co(){return is.join(To(),"memory.json")}function Bm(){return is.join(process.cwd(),"NEX.md")}function Qa(){return is.join(Wm.homedir(),".nex","NEX.md")}function Hm(){let t=To();Ke.existsSync(t)||Ke.mkdirSync(t,{recursive:!0})}function as(){let t=Co();if(!Ke.existsSync(t))return{};try{return JSON.parse(Ke.readFileSync(t,"utf-8"))}catch{return{}}}function Za(t){Hm(),Ke.writeFileSync(Co(),JSON.stringify(t,null,2),"utf-8")}function Gm(t,e){let s=as();s[t]={value:e,updatedAt:new Date().toISOString()},Za(s)}function zm(t){let e=as();return e[t]?e[t].value:null}function Km(t){let e=as();return t in e?(delete e[t],Za(e),!0):!1}function ec(){let t=as();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function tc(){let t=Qa();if(!Ke.existsSync(t))return"";try{return Ke.readFileSync(t,"utf-8").trim()}catch{return""}}function nc(){let t=Bm();if(!Ke.existsSync(t))return"";try{return Ke.readFileSync(t,"utf-8").trim()}catch{return""}}function Jm(){let t=[],e=tc();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
294
|
+
${e}`);let s=nc();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
295
|
+
${s}`);let n=ec();if(n.length>0){let o=n.map(r=>` ${r.key}: ${r.value}`).join(`
|
|
290
296
|
`);t.push(`PROJECT MEMORY:
|
|
291
297
|
${o}`)}return t.join(`
|
|
292
298
|
|
|
293
|
-
`)}
|
|
294
|
-
${
|
|
295
|
-
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${
|
|
296
|
-
`)}function
|
|
299
|
+
`)}sc.exports={remember:Gm,recall:zm,forget:Km,listMemories:ec,loadGlobalInstructions:tc,loadProjectInstructions:nc,getMemoryContext:Jm,_getMemoryDir:To,_getMemoryFile:Co,_getGlobalNexMdPath:Qa}});var pn=M((A$,ic)=>{var $t=require("fs"),Ro=require("path"),{C:R$}=ae(),cs={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"},Lt={...cs};function oc(){let t=Ro.join(process.cwd(),".nex","config.json");if($t.existsSync(t))try{let e=JSON.parse($t.readFileSync(t,"utf-8"));e.permissions&&(Lt={...cs,...e.permissions})}catch{}}function Ym(){let t=Ro.join(process.cwd(),".nex"),e=Ro.join(t,"config.json"),s={};if($t.existsSync(e))try{s=JSON.parse($t.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Lt,$t.existsSync(t)||$t.mkdirSync(t,{recursive:!0}),$t.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function rc(t){return Lt[t]||"ask"}function Xm(t,e){return["allow","ask","deny"].includes(e)?(Lt[t]=e,!0):!1}function Vm(t){return rc(t)}function Qm(){return Object.entries(Lt).map(([t,e])=>({tool:t,mode:e}))}function Zm(){Lt={...cs}}oc();ic.exports={getPermission:rc,setPermission:Xm,checkPermission:Vm,listPermissions:Qm,loadPermissions:oc,savePermissions:Ym,resetPermissions:Zm,DEFAULT_PERMISSIONS:cs}});var It=M((N$,dc)=>{var yt=require("fs"),ls=require("path"),O$=require("readline"),{C:K}=ae(),ce=null,Ao=!1,Oo=null,ac=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 us(){return ls.join(process.cwd(),".nex","plans")}function cc(){let t=us();yt.existsSync(t)||yt.mkdirSync(t,{recursive:!0})}function ep(t,e=[]){return ce={name:`plan-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,task:t,steps:e.map(s=>({description:s.description||s,files:s.files||[],status:"pending"})),status:"draft",createdAt:new Date().toISOString()},ce}function tp(){return ce}function np(t){Ao=t}function sp(){return Ao}function op(){return!ce||ce.status!=="draft"?!1:(ce.status="approved",ce.updatedAt=new Date().toISOString(),!0)}function rp(){return!ce||ce.status!=="approved"?!1:(ce.status="executing",!0)}function ip(t,e){return!ce||t<0||t>=ce.steps.length?!1:(ce.steps[t].status=e,ce.updatedAt=new Date().toISOString(),ce.steps.every(s=>s.status==="done"||s.status==="skipped")&&(ce.status="completed"),!0)}function ap(t){if(!t)return`${K.dim}No active plan${K.reset}`;let e={draft:`${K.yellow}DRAFT${K.reset}`,approved:`${K.green}APPROVED${K.reset}`,executing:`${K.blue}EXECUTING${K.reset}`,completed:`${K.green}COMPLETED${K.reset}`},s=[];s.push(`
|
|
300
|
+
${K.bold}${K.cyan}Plan: ${t.task}${K.reset}`),s.push(`${K.dim}Status: ${e[t.status]||t.status}${K.reset}
|
|
301
|
+
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${K.green}\u2713${K.reset}`;break;case"in_progress":r=`${K.blue}\u2192${K.reset}`;break;case"skipped":r=`${K.dim}\u25CB${K.reset}`;break;default:r=`${K.dim} ${K.reset}`}s.push(` ${r} ${K.bold}Step ${n+1}:${K.reset} ${o.description}`),o.files.length>0&&s.push(` ${K.dim}Files: ${o.files.join(", ")}${K.reset}`)}return s.push(""),s.join(`
|
|
302
|
+
`)}function cp(t){if(t||(t=ce),!t)return null;cc();let e=ls.join(us(),`${t.name}.json`);return yt.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function lp(t){let e=ls.join(us(),`${t}.json`);if(!yt.existsSync(e))return null;try{let s=JSON.parse(yt.readFileSync(e,"utf-8"));return ce=s,s}catch{return null}}function up(){cc();let t=us(),e=yt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(yt.readFileSync(ls.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 dp(t){Oo=t}function fp(){return Oo}function mp(){ce=null,Ao=!1,Oo=null}function pp(){return`
|
|
297
303
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
298
304
|
|
|
299
305
|
# Allowed Tools (read-only)
|
|
300
|
-
You may ONLY use these tools: ${[...
|
|
306
|
+
You may ONLY use these tools: ${[...ac].join(", ")}
|
|
301
307
|
Any other tool call will be blocked and returned with an error.
|
|
302
308
|
|
|
303
309
|
# Analysis Phase
|
|
@@ -328,47 +334,46 @@ Bullet list of potential issues and mitigations.
|
|
|
328
334
|
# Important
|
|
329
335
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
330
336
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
331
|
-
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var
|
|
332
|
-
`),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${w.dim}${"\u2500".repeat(40)}${w.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let i=o?` ${o} `:"";s.push(`${w.dim}${"\u2500".repeat(3)}${i}${"\u2500".repeat(Math.max(0,37-i.length))}${w.reset}`)}continue}if(n){s.push(` ${
|
|
333
|
-
`)}function
|
|
334
|
-
`)}function
|
|
337
|
+
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var lc=["interactive","semi-auto","autonomous"],uc="interactive";function hp(t){return lc.includes(t)?(uc=t,!0):!1}function gp(){return uc}dc.exports={createPlan:ep,getActivePlan:tp,setPlanMode:np,isPlanMode:sp,approvePlan:op,startExecution:rp,updateStep:ip,formatPlan:ap,savePlan:cp,loadPlan:lp,listPlans:up,clearPlan:mp,getPlanModePrompt:pp,setPlanContent:dp,getPlanContent:fp,PLAN_MODE_ALLOWED_TOOLS:ac,setAutonomyLevel:hp,getAutonomyLevel:gp,AUTONOMY_LEVELS:lc}});var xc=M((M$,bc)=>{var{C:w}=ae();function $p(t){if(!t)return"";let e=t.split(`
|
|
338
|
+
`),s=[],n=!1,o="";for(let r of e){if(r.trim().startsWith("```")){if(n)s.push(`${w.dim}${"\u2500".repeat(40)}${w.reset}`),n=!1,o="";else{n=!0,o=r.trim().substring(3).trim();let i=o?` ${o} `:"";s.push(`${w.dim}${"\u2500".repeat(3)}${i}${"\u2500".repeat(Math.max(0,37-i.length))}${w.reset}`)}continue}if(n){s.push(` ${Mo(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${w.bold}${w.cyan} ${wt(r.substring(4))}${w.reset}`);continue}if(r.startsWith("## ")){s.push(`${w.bold}${w.cyan} ${wt(r.substring(3))}${w.reset}`);continue}if(r.startsWith("# ")){s.push(`${w.bold}${w.cyan}${wt(r.substring(2))}${w.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let i=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,"");s.push(`${i}${w.cyan}\u2022${w.reset} ${bt(c)}`);continue}if(/^\s*\d+\.\s/.test(r)){let i=r.match(/^(\s*)(\d+)\.\s(.*)/);if(i){s.push(`${i[1]}${w.cyan}${i[2]}.${w.reset} ${bt(i[3])}`);continue}}s.push(bt(r))}return s.join(`
|
|
339
|
+
`)}function wt(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function bt(t){return t?t.replace(/`([^`]+)`/g,`${w.cyan}$1${w.reset}`).replace(/\*\*([^*]+)\*\*/g,`${w.bold}$1${w.reset}`).replace(/\*([^*]+)\*/g,`${w.dim}$1${w.reset}`).replace(/\[([^\]]+)\]\(([^)]+)\)/g,`${w.cyan}$1${w.reset} ${w.dim}($2)${w.reset}`):""}function Mo(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?fc(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?mc(t):e==="json"||e==="jsonc"?pc(t):e==="python"||e==="py"?hc(t):e==="go"||e==="golang"?gc(t):e==="rust"||e==="rs"?$c(t):e==="css"||e==="scss"||e==="less"?yc(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?wc(t):t:""}function fc(t){let e=/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|require|async|await|new|this|throw|try|catch|switch|case|break|default|typeof|instanceof)\b/g,s=/(["'`])(?:(?=(\\?))\2.)*?\1/g,n=/(\/\/.*$)/,o=/\b(\d+\.?\d*)\b/g,r=t;return r=r.replace(o,`${w.yellow}$1${w.reset}`),r=r.replace(e,`${w.magenta}$1${w.reset}`),r=r.replace(s,`${w.green}$&${w.reset}`),r=r.replace(n,`${w.dim}$1${w.reset}`),r}function mc(t){let e=/^(\s*)([\w-]+)/,s=/(--?\w[\w-]*)/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(#.*$)/,r=t;return r=r.replace(s,`${w.cyan}$1${w.reset}`),r=r.replace(e,`$1${w.green}$2${w.reset}`),r=r.replace(n,`${w.yellow}$&${w.reset}`),r=r.replace(o,`${w.dim}$1${w.reset}`),r}function pc(t){let e=/("[\w-]+")\s*:/g,s=/:\s*("(?:[^"\\]|\\.)*")/g,n=/:\s*(\d+\.?\d*)/g,o=/:\s*(true|false|null)/g,r=t;return r=r.replace(e,`${w.cyan}$1${w.reset}:`),r=r.replace(s,`: ${w.green}$1${w.reset}`),r=r.replace(n,`: ${w.yellow}$1${w.reset}`),r=r.replace(o,`: ${w.magenta}$1${w.reset}`),r}function hc(t){let e=/\b(def|class|if|elif|else|for|while|return|import|from|as|try|except|finally|raise|with|yield|lambda|pass|break|continue|and|or|not|in|is|None|True|False|self|async|await|nonlocal|global)\b/g,s=/("""[\s\S]*?"""|'''[\s\S]*?'''|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g,n=/(#.*$)/,o=/\b(\d+\.?\d*)\b/g,r=/^(\s*@\w+)/,i=t;return i=i.replace(o,`${w.yellow}$1${w.reset}`),i=i.replace(e,`${w.magenta}$1${w.reset}`),i=i.replace(r,`${w.cyan}$1${w.reset}`),i=i.replace(s,`${w.green}$&${w.reset}`),i=i.replace(n,`${w.dim}$1${w.reset}`),i}function gc(t){let e=/\b(func|package|import|var|const|type|struct|interface|map|chan|go|defer|return|if|else|for|range|switch|case|default|break|continue|select|fallthrough|nil|true|false|make|new|len|cap|append|copy|delete|panic|recover)\b/g,s=/\b(string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|error|any)\b/g,n=/(["'`])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=t;return i=i.replace(r,`${w.yellow}$1${w.reset}`),i=i.replace(s,`${w.cyan}$1${w.reset}`),i=i.replace(e,`${w.magenta}$1${w.reset}`),i=i.replace(n,`${w.green}$&${w.reset}`),i=i.replace(o,`${w.dim}$1${w.reset}`),i}function $c(t){let e=/\b(fn|let|mut|const|struct|enum|impl|trait|pub|use|mod|crate|self|super|match|if|else|for|while|loop|return|break|continue|where|as|in|ref|move|async|await|unsafe|extern|type|static|dyn|macro_rules)\b/g,s=/\b(i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|f32|f64|bool|char|str|String|Vec|Option|Result|Box|Rc|Arc|Self|Some|None|Ok|Err|true|false)\b/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(\/\/.*$)/,r=/\b(\d+\.?\d*)\b/g,i=/\b(\w+!)/g,c=t;return c=c.replace(r,`${w.yellow}$1${w.reset}`),c=c.replace(s,`${w.cyan}$1${w.reset}`),c=c.replace(e,`${w.magenta}$1${w.reset}`),c=c.replace(i,`${w.yellow}$1${w.reset}`),c=c.replace(n,`${w.green}$&${w.reset}`),c=c.replace(o,`${w.dim}$1${w.reset}`),c}function yc(t){let e=/^(\s*)([\w-]+)\s*:/,s=/:\s*([^;]+)/,n=/^(\s*[.#@][\w-]+)/,o=/\b(\d+\.?\d*(px|em|rem|%|vh|vw|s|ms|deg|fr)?)\b/g,r=/(\/\*.*?\*\/|\/\/.*$)/,i=/(#[0-9a-fA-F]{3,8})\b/g,c=t;return c=c.replace(i,`${w.yellow}$1${w.reset}`),c=c.replace(o,`${w.yellow}$1${w.reset}`),c=c.replace(e,`$1${w.cyan}$2${w.reset}:`),c=c.replace(n,`$1${w.magenta}$&${w.reset}`),c=c.replace(r,`${w.dim}$1${w.reset}`),c}function wc(t){let e=/<\/?(\w[\w-]*)/g,s=/\s([\w-]+)=/g,n=/(["'])(?:(?=(\\?))\2.)*?\1/g,o=/(<!--.*?-->)/g,r=/(&\w+;)/g,i=t;return i=i.replace(o,`${w.dim}$1${w.reset}`),i=i.replace(n,`${w.green}$&${w.reset}`),i=i.replace(e,`<${w.magenta}$1${w.reset}`),i=i.replace(s,` ${w.cyan}$1${w.reset}=`),i=i.replace(r,`${w.yellow}$1${w.reset}`),i}function yp(t,e){if(!t||t.length===0)return"";let s=t.map((i,c)=>{let l=e.reduce((u,d)=>Math.max(u,(d[c]||"").length),0);return Math.max(i.length,l)}),n=s.map(i=>"\u2500".repeat(i+2)).join("\u253C"),o=t.map((i,c)=>` ${w.bold}${i.padEnd(s[c])}${w.reset} `).join("\u2502"),r=[];r.push(`${w.dim}\u250C${n.replace(/┼/g,"\u252C")}\u2510${w.reset}`),r.push(`${w.dim}\u2502${w.reset}${o}${w.dim}\u2502${w.reset}`),r.push(`${w.dim}\u251C${n}\u2524${w.reset}`);for(let i of e){let c=t.map((l,u)=>` ${(i[u]||"").padEnd(s[u])} `).join(`${w.dim}\u2502${w.reset}`);r.push(`${w.dim}\u2502${w.reset}${c}${w.dim}\u2502${w.reset}`)}return r.push(`${w.dim}\u2514${n.replace(/┼/g,"\u2534")}\u2518${w.reset}`),r.join(`
|
|
340
|
+
`)}function wp(t,e,s,n=30){let o=s>0?Math.round(e/s*100):0,r=Math.round(o/100*n),i=n-r,c=o>=100?w.green:o>50?w.yellow:w.cyan;return` ${t} ${c}${"\u2588".repeat(r)}${w.dim}${"\u2591".repeat(i)}${w.reset} ${o}% (${e}/${s})`}var No=class{constructor(){this.buffer="",this.inCodeBlock=!1,this.codeBlockLang="",this.lineCount=0,this._cursorTimer=null,this._cursorFrame=0,this._cursorActive=!1}_safeWrite(e){try{process.stdout.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}_cursorWrite(e){try{process.stderr.write(e)}catch(s){if(s.code!=="EPIPE")throw s}}startCursor(){process.stderr.isTTY&&(this._cursorActive=!0,this._cursorFrame=0,this._cursorWrite("\x1B[?25l"),this._renderCursor(),this._cursorTimer=setInterval(()=>this._renderCursor(),80))}_renderCursor(){let e=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],s=e[this._cursorFrame%e.length];this._cursorWrite(`\x1B[2K\r\x1B[36m${s}\x1B[0m`),this._cursorFrame++}_clearCursorLine(){this._cursorActive&&this._cursorWrite("\x1B[2K\r")}stopCursor(){this._cursorTimer&&(clearInterval(this._cursorTimer),this._cursorTimer=null),this._cursorActive&&(this._cursorWrite("\x1B[2K\r\x1B[?25h"),this._cursorActive=!1)}push(e){if(!e)return;this._clearCursorLine(),this.buffer+=e;let s;for(;(s=this.buffer.indexOf(`
|
|
335
341
|
`))!==-1;){let n=this.buffer.substring(0,s);this.buffer=this.buffer.substring(s+1),this._renderLine(n)}this._cursorActive&&(this._renderCursor(),this._cursorTimer&&clearInterval(this._cursorTimer),this._cursorTimer=setInterval(()=>this._renderCursor(),120))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${w.dim}${"\u2500".repeat(40)}${w.reset}
|
|
336
342
|
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${w.dim}${"\u2500".repeat(40)}${w.reset}
|
|
337
343
|
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let s=this.codeBlockLang?` ${this.codeBlockLang} `:"";this._safeWrite(`${w.dim}${"\u2500".repeat(3)}${s}${"\u2500".repeat(Math.max(0,37-s.length))}${w.reset}
|
|
338
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
339
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${w.bold}${w.cyan} ${
|
|
340
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${w.bold}${w.cyan} ${
|
|
341
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${w.bold}${w.cyan}${
|
|
342
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${w.cyan}\u2022${w.reset} ${
|
|
343
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${w.cyan}${s[2]}.${w.reset} ${
|
|
344
|
-
`);return}}this._safeWrite(`${
|
|
345
|
-
`)}}
|
|
344
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${Mo(e,this.codeBlockLang)}
|
|
345
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${w.bold}${w.cyan} ${wt(e.substring(4))}${w.reset}
|
|
346
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${w.bold}${w.cyan} ${wt(e.substring(3))}${w.reset}
|
|
347
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${w.bold}${w.cyan}${wt(e.substring(2))}${w.reset}
|
|
348
|
+
`);return}if(/^\s*[-*]\s/.test(e)){let s=e.match(/^(\s*)/)[1],n=e.replace(/^\s*[-*]\s/,"");this._safeWrite(`${s}${w.cyan}\u2022${w.reset} ${bt(n)}
|
|
349
|
+
`);return}if(/^\s*\d+\.\s/.test(e)){let s=e.match(/^(\s*)(\d+)\.\s(.*)/);if(s){this._safeWrite(`${s[1]}${w.cyan}${s[2]}.${w.reset} ${bt(s[3])}
|
|
350
|
+
`);return}}this._safeWrite(`${bt(e)}
|
|
351
|
+
`)}};bc.exports={renderMarkdown:$p,renderInline:bt,stripHeadingMarkers:wt,highlightCode:Mo,highlightJS:fc,highlightBash:mc,highlightJSON:pc,highlightPython:hc,highlightGo:gc,highlightRust:$c,highlightCSS:yc,highlightHTML:wc,renderTable:yp,renderProgress:wp,StreamRenderer:No}});var Io=M((P$,Sc)=>{var{execSync:bp}=require("child_process"),Po=require("path"),hn=require("fs"),Lo=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function _c(){return Po.join(process.cwd(),".nex","hooks")}function xp(){return Po.join(process.cwd(),".nex","config.json")}function kc(){let t=xp();if(!hn.existsSync(t))return{};try{return JSON.parse(hn.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function ds(t){if(!Lo.includes(t))return[];let e=[],s=_c(),n=Po.join(s,t);hn.existsSync(n)&&e.push(n);let o=kc();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function vc(t,e={},s=3e4){try{return{success:!0,output:bp(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=ds(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=vc(r,n);if(o.push({command:r,...i}),!i.success&&t.startsWith("pre-"))break}return o}function kp(t){return ds(t).length>0}function vp(){let t=[];for(let e of Lo){let s=ds(e);s.length>0&&t.push({event:e,commands:s})}return t}function Sp(){let t=_c();return hn.existsSync(t)||hn.mkdirSync(t,{recursive:!0}),t}Sc.exports={HOOK_EVENTS:Lo,loadHookConfig:kc,getHooksForEvent:ds,executeHook:vc,runHooks:_p,hasHooks:kp,listHooks:vp,initHooksDir:Sp}});var le=M((q$,jc)=>{var{C:_,Spinner:qt,TaskProgress:Ep,formatToolCall:Tp,formatResult:Cp,formatToolSummary:Oc,formatSectionHeader:Rp,setActiveTaskProgress:L$}=ae(),{callStream:Ap}=pe(),{parseToolArgs:Op}=Pn(),{executeTool:Np}=We(),{gatherProjectContext:Mp}=ko(),{fitToContext:Pp,forceCompress:qo,getUsage:Lp,estimateTokens:Ip}=Ce(),{autoSave:tt}=gt(),{getMemoryContext:qp}=et(),{checkPermission:jp,setPermission:Dp,savePermissions:Fp}=pn(),{confirm:Nc,setAllowAlwaysHandler:Up}=Ne(),{isPlanMode:hs,getPlanModePrompt:Wp,PLAN_MODE_ALLOWED_TOOLS:Mc,setPlanContent:Bp}=It(),{StreamRenderer:Hp}=xc(),{runHooks:Ec}=Io(),{routeMCPCall:Gp,getMCPToolDefinitions:zp}=Dn(),{getSkillInstructions:Kp,getSkillToolDefinitions:Jp,routeSkillCall:Yp}=Yt(),{trackUsage:Xp}=Tt(),{validateToolArgs:Vp}=Ks(),{filterToolsForModel:Tc,getModelTier:Qp,PROVIDER_DEFAULT_TIER:I$}=ro(),{getConfiguredProviders:Zp,getActiveProviderName:gn,getActiveModelId:Go,setActiveModel:Cc,MODEL_EQUIVALENTS:gs}=pe(),Jo=require("fs"),Yo=require("path"),Rc=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function eh(t){let e=[],s;for(Rc.lastIndex=0;(s=Rc.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):Yo.resolve(n);Jo.existsSync(o)&&e.push({raw:n,abs:o})}return e}function th(t){let e=Jo.readFileSync(t),s=Yo.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 Pc(t){let e=eh(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}=th(n.abs);s.push({type:"image",media_type:r,data:o})}catch{}return s.length>1?s:t}var jo=null,Do=null,Fo=null;function jt(){if(jo===null){let{TOOL_DEFINITIONS:t}=We();jo=t}return Do===null&&(Do=Jp()),Fo===null&&(Fo=zp()),[...jo,...Do,...Fo]}var zo=50;function nh(t){Number.isFinite(t)&&t>0&&(zo=t)}var fs=()=>null;function sh(t){fs=t}var $n=null,Ko=null,Dt=null,ms=new Map,oh=1e4,rh=6e3,ih=/\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 ah(t){return!t||typeof t!="string"?t:t.replace(ih,(e,s)=>`${s}=***REDACTED***`)}function ch(t){let e=ah(t);if(Ip(e)>oh)try{let{compressToolResult:n}=Ce();return n(e,rh)}catch{return e}return e}function Lc(t){try{let{getActiveModel:e}=pe(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(ms.has(n))return ms.get(n);let o=Tc(t);return ms.set(n,o),o}catch{return Tc(t)}}function lh(){ms.clear()}async function Ic(){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}=et(),i=r();i&&o.push(`memory:${i}`)}catch{}try{let r=e.join(process.cwd(),".nex","brain");if(Jo.existsSync(r)){let i=await t.stat(r);o.push(`brain:${i.mtimeMs}`)}}catch{}return o.join("|")}catch{return`fallback:${Date.now()}`}}function uh(){$n=null,Ko=null,Dt=null}var dh=new Set(["spawn_agents"]),Uo=5,Wo=3,Bo=2,fh=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),mh=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10),ph=process.env.NEX_STALE_AUTO_SWITCH!=="0";function hh(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{}}Up(t=>{Dp(t,"allow"),Fp(),console.log(`${_.green} \u2713 ${t}: always allow${_.reset}`)});async function gh(t){let e=t.function.name,s=Op(t.function.arguments),n=t.id||`cli-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!s){let l=jt().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.
|
|
346
352
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
347
353
|
|
|
348
354
|
Expected JSON schema for "${e}":
|
|
349
355
|
${u}
|
|
350
356
|
|
|
351
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=
|
|
352
|
-
`)[0]}${_.reset}`),{callId:n,fnName:e,args:s,canExecute:!1,errorResult:{role:"tool",content:o.error,tool_call_id:n}};let r=o.corrected||s;if(o.corrected){let c=Object.keys(s),l=Object.keys(o.corrected),u=c.filter(d=>!l.includes(d));u.length&&console.log(`${_.dim} \u2713 ${e}: corrected args (${u.join(", ")})${_.reset}`)}if(
|
|
357
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=Vp(e,s);if(!o.valid)return console.log(`${_.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
358
|
+
`)[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(hs()&&!Mc.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=jp(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 Nc(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 $h(t,e,s={}){let n=await Yp(t,e);if(n!==null)return n;let o=await Gp(t,e);return o!==null?o:Np(t,e,s)}function yh(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 Ho(t,e=!1){e||console.log(Tp(t.fnName,t.args)),Ec("pre-tool",{tool_name:t.fnName});let s=await $h(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),n=String(s??""),o=n.length>5e4?n.substring(0,5e4)+`
|
|
353
359
|
...(truncated ${n.length-5e4} chars)`:n,r=o.split(`
|
|
354
|
-
`)[0],i=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),c=
|
|
355
|
-
`)}function
|
|
360
|
+
`)[0],i=r.startsWith("ERROR")||r.includes("CANCELLED")||r.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(o)&&/✗ Agent/.test(o),c=Oc(t.fnName,t.args,o,i);return e||(console.log(Cp(o)),console.log(c)),Ec("post-tool",{tool_name:t.fnName}),{msg:{role:"tool",content:ch(o),tool_call_id:t.callId},summary:c}}async function wh(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=yh(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 qt(u),i.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await Ho(t[l],e);n[l]=u,o.push(d)}else{let l=r.map(d=>Ho(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(Oc(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(dh.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:f}=await Ho(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 Q=[],Ac=300,ps=[];function bh(t){ps.push(t.trim())}function xh(){return ps.length===0?null:ps.splice(0,ps.length).join(`
|
|
361
|
+
`)}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)
|
|
356
362
|
`];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(`
|
|
357
363
|
This is a hard requirement. Do NOT fall back to English or any other language for your responses, even if the user writes in a different language first.`),o.join(`
|
|
358
364
|
`)+`
|
|
359
365
|
|
|
360
|
-
`}function
|
|
366
|
+
`}function kh(){if(Dt!==null)return Dt;try{let e=Zp().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:Qp(r.id,o.name),name:r.name})));if(e.length<2)return Dt="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
|
|
361
367
|
# Sub-Agent Model Routing
|
|
362
368
|
|
|
363
369
|
`;n+='Sub-agents auto-select models by task complexity. Override with `model: "provider:model"` in agent definition.\n\n',n+=`| Model | Tier | Auto-assigned for |
|
|
364
370
|
|---|---|---|
|
|
365
371
|
`;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
|
|
366
|
-
`;return
|
|
372
|
+
`;return Dt=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Dt="",""}}async function qc(){let t=await Ic();if($n!==null&&t===Ko)return $n;let e=await Mp(process.cwd()),s=qp(),n=Kp(),o=hs()?Wp():"",r=_h();return $n=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
|
|
367
373
|
|
|
368
374
|
WORKING DIRECTORY: ${process.cwd()}
|
|
369
375
|
All relative paths resolve from this directory.
|
|
370
|
-
|
|
371
|
-
${r}`:""}PROJECT CONTEXT:
|
|
376
|
+
PROJECT CONTEXT:
|
|
372
377
|
${e}
|
|
373
378
|
${s?`
|
|
374
379
|
${s}
|
|
@@ -377,7 +382,8 @@ ${n}
|
|
|
377
382
|
`:""}${o?`
|
|
378
383
|
${o}
|
|
379
384
|
`:""}
|
|
380
|
-
|
|
385
|
+
${r?`${r}
|
|
386
|
+
`:""}# Core Behavior
|
|
381
387
|
|
|
382
388
|
- You can use tools OR respond with text. For simple questions, answer directly.
|
|
383
389
|
- For coding tasks, use tools to read files, make changes, run tests, etc.
|
|
@@ -484,7 +490,7 @@ When performing audits, code reviews, bug hunts, or security reviews:
|
|
|
484
490
|
- Good for: reading multiple files, analyzing separate modules.
|
|
485
491
|
- Bad for: tasks that depend on each other or modify the same file.
|
|
486
492
|
- Max 5 parallel agents.
|
|
487
|
-
${
|
|
493
|
+
${kh()}
|
|
488
494
|
|
|
489
495
|
# Edit Reliability (Critical)
|
|
490
496
|
|
|
@@ -535,20 +541,20 @@ You have access to a persistent knowledge base in .nex/brain/.
|
|
|
535
541
|
- Include tags in frontmatter for better retrieval
|
|
536
542
|
- The user reviews all brain writes via /brain review or git diff
|
|
537
543
|
|
|
538
|
-
`,
|
|
539
|
-
`):[]).filter(f=>{let m=f.split(".").pop();return r.has(m)});if(i.length<3)return null;let c={};for(let f of i){let m=f.split(".").pop();c[m]=(c[m]||0)+1}let u=` \u{1F4C1} ${Object.entries(c).sort((f,m)=>m[1]-f[1]).slice(0,4).map(([f,m])=>`${m} .${f}`).join(" \xB7 ")}`,d=
|
|
540
|
-
\u{1F4E6} ${h}${p}`}}catch{}return u}function
|
|
541
|
-
${_.dim} ${i}${_.reset}`),s.size>0?console.log(`${_.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${_.reset}`):n.size>=5&&s.size===0&&t>=3?console.log(`${_.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${_.reset}`):n.size>0&&t>=2&&console.log(`${_.dim} \u{1F4A1} /save \xB7 /clear${_.reset}`)}async function
|
|
542
|
-
`),m==="")return c({action:"quit"});let p=i.find(g=>g.key===h);!p||p.key==="q"||!p.model&&p.key!=="r"?c({action:"quit"}):p.key==="r"?c({action:"retry"}):c({action:"switch",model:p.model,provider:t})};l.on("data",f)})}async function
|
|
543
|
-
`+
|
|
544
|
-
`)}catch(
|
|
545
|
-
${_.cyan}${_.bold}Plan ready.${_.reset} ${_.dim}Type ${_.reset}${_.cyan}/plan approve${_.reset}${_.dim} to execute, or ask follow-up questions to refine.${_.reset}`)}n&&(n.stop(),n=null),s(null)
|
|
546
|
-
${_.yellow}\u26A0 Max iterations reached.${_.reset}`),await
|
|
547
|
-
`),await t(c,i,d)}catch(u){if(s=u,
|
|
548
|
-
`);for(let y=0;y<h.length;y++){let $=
|
|
549
|
-
`);process.stdout.write(`\x1B[${m}A`)}let $=[];$.push(` ${
|
|
544
|
+
`,Ko=t,$n}function vh(){Q=[]}function Sh(){Q.length>Ac&&Q.splice(0,Q.length-Ac)}function Eh(){return Q.length}function Th(){return Q}function Ch(t){Q=t}async function Rh(){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(`
|
|
545
|
+
`):[]).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=Yo.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+=`
|
|
546
|
+
\u{1F4E6} ${h}${p}`}}catch{}return u}function nt(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(`
|
|
547
|
+
${_.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 Ah(){if(!process.stdout.isTTY)return{action:"quit"};let t=gn(),e=Go(),s=gs.fast?.[t],n=gs.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}
|
|
548
|
+
`),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 Oh(t){let e=Pc(t);Q.push({role:"user",content:e}),Sh();let{setOnChange:s}=Yn(),n=null,o=0;s((W,F)=>{W==="create"?(n&&n.stop(),n=new Ep(F.name,F.tasks),n.setStats({tokens:o}),n.start()):W==="update"&&n?n.updateTask(F.id,F.status):W==="clear"&&n&&(n.stop(),n=null)});let r=await qc(),i=r;try{let{getBrainContext:W}=cn(),F=await W(t);F&&(i=r+`
|
|
549
|
+
`+F+`
|
|
550
|
+
`)}catch(W){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",W.message)}let c=[{role:"system",content:i},...Q],l=new qt("Thinking...");l.start();let d=Q.length===1?Rh().catch(()=>null):Promise.resolve(null),f=jt(),[{messages:m,compressed:h,compacted:p,tokensRemoved:g},y]=await Promise.all([Pp(c,f),d]),$=Lp(c,f);if(l.stop(),y&&console.log(`${_.dim}${y}${_.reset}`),p)console.log(`${_.dim} [context compacted \u2014 summary (~${g} tokens freed)]${_.reset}`);else if(h){let W=$.limit>0?Math.round(g/$.limit*100):0;console.log(`${_.dim} [context compressed \u2014 ~${g} tokens freed (${W}%)]${_.reset}`)}$.percentage>85&&console.log(`${_.yellow} \u26A0 Context ${Math.round($.percentage)}% full \u2014 consider /clear or /save + start fresh${_.reset}`);let x=m,A=0,k=0,v=0,T=0,S=0,C=new Map,U=new Set,I=new Set,ee=Date.now(),B=new Map,de=5,me=10,J,je=zo,N=0,j=10;e:for(;;){for(J=0;J<je&&!fs()?.aborted;J++){let F=!0,D=null;if(n&&n.isActive())n._paused&&n.resume();else if(!n){let E=S>0?`Thinking... (step ${S+1})`:"Thinking...";D=new qt(E),D.start()}let Y=!0,H="",G=new Hp,$e,xt=Date.now(),it=!1,at=new AbortController,hr=setInterval(()=>{let E=Date.now()-xt;if(E>=mh)G._clearCursorLine(),console.log(`${_.yellow} \u26A0 Stream stale for ${Math.round(E/1e3)}s \u2014 aborting and retrying${_.reset}`),at.abort();else if(E>=fh&&!it){it=!0,G._clearCursorLine();let q=gs.fast?.[gn()];console.log(`${_.yellow} \u26A0 No tokens received for ${Math.round(E/1e3)}s \u2014 waiting...${_.reset}`),q&&console.log(`${_.dim} \u{1F4A1} Ctrl+C \u2192 /model ${q} to switch to a faster model${_.reset}`)}},5e3),Se="",De=null;try{let E=Lc(jt()),q=hs()?E.filter(X=>Mc.has(X.function.name)):E,_t=fs(),z=new AbortController;_t&&_t.addEventListener("abort",()=>z.abort(),{once:!0}),at.signal.addEventListener("abort",()=>z.abort(),{once:!0}),$e=await Ap(x,q,{signal:z.signal,onToken:X=>{xt=Date.now(),it=!1,Se+=X,process.stdout.isTTY?De||(De=setTimeout(()=>{Se&&G&&G.push(Se),Se="",De=null},50)):(G.push(Se),Se=""),Y&&(n&&!n._paused?n.pause():D&&D.stop(),F||(F=!0),G.startCursor(),Y=!1),H+=X}})}catch(E){if(clearInterval(hr),De&&(clearTimeout(De),De=null),Se&&G&&(G.push(Se),Se=""),n&&!n._paused&&n.pause(),D&&D.stop(),G.stopCursor(),at.signal.aborted&&!fs()?.aborted){if(v++,v>Bo){if(T<1){T++,console.log(`${_.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${_.reset}`);let Ye=jt(),{messages:Bt,tokensRemoved:kt}=qo(x,Ye);x=Bt,console.log(`${_.dim} [force-compressed \u2014 ~${kt} tokens freed]${_.reset}`),v=0,J--;continue}n&&(n.stop(),n=null);let ie=await Ah();if(ie.action==="quit"){s(null),nt(S,C,U,I,ee),tt(Q);break}ie.action==="switch"&&(Cc(`${ie.provider}:${ie.model}`),console.log(`${_.green} \u2713 Switched to ${ie.provider}:${ie.model}${_.reset}`)),v=0,T=0,J--;continue}let z=v===1?3e3:5e3;if(v>=2&&T<1){T++,console.log(`${_.yellow} \u26A0 Stale retry ${v}/${Bo} \u2014 force-compressing before retry...${_.reset}`);let ie=jt(),{messages:Ye,tokensRemoved:Bt}=qo(x,ie);if(x=Ye,console.log(`${_.dim} [force-compressed \u2014 ~${Bt} tokens freed]${_.reset}`),ph){let kt=gs.fast?.[gn()];kt&&kt!==Go()&&(Cc(`${gn()}:${kt}`),console.log(`${_.cyan} \u26A1 Auto-switched to ${kt} 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}/${Bo} \u2014 retrying in ${z/1e3}s...${_.reset}`);let X=new qt(`Waiting ${z/1e3}s before retry...`);X.start(),await new Promise(ie=>setTimeout(ie,z)),X.stop(),J--;continue}if(E.name==="AbortError"||E.name==="CanceledError"||E.message?.includes("canceled")||E.message?.includes("aborted")){n&&(n.stop(),n=null),s(null),nt(S,C,U,I,ee),tt(Q);break}let q=E.message;if(E.code==="ECONNREFUSED"||E.message.includes("ECONNREFUSED"))q="Connection refused \u2014 please check your internet connection or API endpoint";else if(E.code==="ENOTFOUND"||E.message.includes("ENOTFOUND"))q="Network error \u2014 could not reach the API server. Please check your connection";else if(E.code==="ETIMEDOUT"||E.message.includes("timeout"))q="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"))q="Authentication failed \u2014 please check your API key in the .env file";else if(E.message.includes("403")||E.message.includes("Forbidden"))q="Access denied \u2014 your API key may not have permission for this model";else if(E.message.includes("400")){let z=(E.message||"").toLowerCase(),X=z.includes("context")||z.includes("token")||z.includes("length")||z.includes("too long")||z.includes("too many")||z.includes("prompt")||z.includes("size")||z.includes("exceeds")||z.includes("num_ctx")||z.includes("input");if(X&&T<1){T++,console.log(`${_.yellow} \u26A0 Context too long \u2014 force-compressing and retrying...${_.reset}`);let ie=jt(),{messages:Ye,tokensRemoved:Bt}=qo(x,ie);x=Ye,console.log(`${_.dim} [force-compressed \u2014 ~${Bt} tokens freed]${_.reset}`),J--;continue}X?q="Context too long \u2014 force compression exhausted. Use /clear to start fresh":q="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")?q="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(E.message.includes("fetch failed")||E.message.includes("fetch"))&&(q="Network request failed \u2014 please check your internet connection");if(console.log(`${_.red} \u2717 ${q}${_.reset}`),E.message.includes("429")){if(A++,A>Uo){console.log(`${_.red} Rate limit: max retries (${Uo}) exceeded. Try again later or use /budget to check your limits.${_.reset}`),n&&(n.stop(),n=null),s(null),nt(S,C,U,I,ee),tt(Q);break}let z=Math.min(1e4*Math.pow(2,A-1),12e4),X=new qt(`Rate limit \u2014 waiting ${Math.round(z/1e3)}s (retry ${A}/${Uo})`);X.start(),await new Promise(ie=>setTimeout(ie,z)),X.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>Wo){console.log(`${_.red} Network error: max retries (${Wo}) exceeded. Check your connection and try again.${_.reset}`),n&&(n.stop(),n=null),s(null),nt(S,C,U,I,ee),tt(Q);break}let z=Math.min(2e3*Math.pow(2,k-1),3e4),X=new qt(`Network error \u2014 retrying in ${Math.round(z/1e3)}s (${k}/${Wo})`);X.start(),await new Promise(ie=>setTimeout(ie,z)),X.stop(),J--;continue}n&&(n.stop(),n=null),s(null),nt(S,C,U,I,ee),tt(Q);break}clearInterval(hr),A=0,k=0,Y&&(n&&!n._paused&&n.pause(),D&&D.stop()),De&&(clearTimeout(De),De=null),Se&&G&&(G.push(Se),Se=""),H&&G.flush(),k=0,v=0,$e&&$e.usage&&(Xp(gn(),Go(),$e.usage.prompt_tokens||0,$e.usage.completion_tokens||0),o+=($e.usage.prompt_tokens||0)+($e.usage.completion_tokens||0),n&&n.setStats({tokens:o}));let{content:xs,tool_calls:ct}=$e,_s={role:"assistant",content:xs||""};if(ct&&ct.length>0&&(_s.tool_calls=ct),Q.push(_s),x.push(_s),!ct||ct.length===0){let E=(xs||"").trim().length>0||H.trim().length>0;if(!E&&S>0&&J<zo-1){let q={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(q),Q.push(q);continue}if(hs()&&E){let q=(xs||H||"").trim();Bp(q),hh(q),console.log(`
|
|
551
|
+
${_.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),nt(S,C,U,I,ee),tt(Q);return}S++,S>1&&(F=!1);for(let E of ct){let q=E.function.name;C.set(q,(C.get(q)||0)+1)}let xn=await Promise.all(ct.map(E=>gh(E))),ks=n?{skipSpinner:!0,skipSummaries:!0}:{},gr=!ks.skipSummaries&&!F;gr&&(F=!0),n&&n._paused&&n.resume();let{results:$r,summaries:_n}=await wh(xn,!0,{...ks,skipSummaries:!0});if(!ks.skipSummaries)if(gr){let E=Rp(xn,S);if(_n.length===1)console.log(E+_n[0]);else{console.log(E);for(let q of _n)console.log(q)}}else for(let E of _n)console.log(E);for(let E=0;E<xn.length;E++){let q=xn[E];if(!q.canExecute)continue;let _t=$r[E].content,z=!_t.startsWith("ERROR")&&!_t.includes("CANCELLED");if(z&&["write_file","edit_file","patch_file"].includes(q.fnName)&&q.args&&q.args.path){U.add(q.args.path);let X=(B.get(q.args.path)||0)+1;B.set(q.args.path,X);let ie=q.args.path.split("/").slice(-2).join("/");if(X===de){console.log(`${_.yellow} \u26A0 Loop warning: "${ie}" edited ${X}\xD7 \u2014 possible edit loop${_.reset}`);let Ye={role:"user",content:`[SYSTEM WARNING] You have edited "${q.args.path}" ${X} times in this session. This may indicate an edit loop. STOP editing this file repeatedly. Re-read it once to verify the current state, then make ONE final targeted edit or declare the task complete.`};Q.push(Ye),x.push(Ye)}else if(X>=me){console.log(`${_.red} \u2716 Loop abort: "${ie}" edited ${X}\xD7 \u2014 aborting to prevent runaway loop${_.reset}`),n&&(n.stop(),n=null),s(null),nt(S,C,U,I,ee),tt(Q);return}}z&&q.fnName==="read_file"&&q.args&&q.args.path&&I.add(q.args.path)}for(let E of $r)Q.push(E),x.push(E);let yr=xh();if(yr){let E={role:"user",content:`[User note mid-run]: ${yr}`};Q.push(E),x.push(E),console.log(`${_.cyan} \u270E Kontext hinzugef\xFCgt${_.reset}`)}}if(J>=je){n&&(n.stop(),n=null),s(null),nt(S,C,U,I,ee),tt(Q);let{getActiveProviderName:W}=pe();if(W()==="ollama"&&N<j){N++,je=20,console.log(`${_.dim} \u2500\u2500 auto-extending (+20 turns, ext ${N}/${j}) \u2500\u2500${_.reset}`);continue e}if(console.log(`
|
|
552
|
+
${_.yellow}\u26A0 Max iterations reached.${_.reset}`),await Nc(" Continue for 20 more turns?")){je=20;continue e}console.log(`${_.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${_.reset}`)}break e}}jc.exports={processInput:Oh,clearConversation:vh,getConversationLength:Eh,getConversationMessages:Th,setConversationMessages:Ch,setAbortSignalGetter:sh,setMaxIterations:nh,invalidateSystemPromptCache:uh,clearToolFilterCache:lh,getCachedFilteredTools:Lc,buildSystemPrompt:qc,getProjectContextHash:Ic,buildUserContent:Pc,injectMidRunNote:bh}});var pe=M((j$,Bc)=>{var{OllamaProvider:Nh}=Lr(),{OpenAIProvider:Mh}=Qr(),{AnthropicProvider:Ph}=ni(),{GeminiProvider:Lh}=ii(),{LocalProvider:Ih}=li(),{checkBudget:qh}=Tt(),Xo={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"}},Dc={};for(let[t,e]of Object.entries(Xo))for(let s of Object.values(e))Dc[s]=t;function Fc(t,e){let s=Dc[t];return s&&Xo[s][e]||t}var fe={},xe=null,ue=null,yn=[];function Te(){if(Object.keys(fe).length>0)return;Ft("ollama",new Nh),Ft("openai",new Mh),Ft("anthropic",new Ph),Ft("gemini",new Lh),Ft("local",new Ih);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;fe[t]?(xe=t,ue=e||fe[t].defaultModel):(xe="ollama",ue="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(yn=s.split(",").map(n=>n.trim()).filter(Boolean))}function Ft(t,e){fe[t]=e}function jh(t){return Te(),fe[t]||null}function Vo(){return Te(),fe[xe]||null}function Dh(){return Te(),xe}function Fh(){return Te(),ue}function Uh(){Te();let t=Vo();if(!t)return{id:ue,name:ue,provider:xe};let e=t.getModel(ue);return e?{...e,provider:xe}:{id:ue,name:ue,provider:xe}}function Uc(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 Wh(t){Te();let{provider:e,model:s}=Uc(t);if(e){let o=fe[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(xe=e,ue=s,$s(),!0):!1}let n=Vo();if(n&&n.getModel(s))return ue=s,$s(),!0;for(let[o,r]of Object.entries(fe))if(r.getModel(s))return xe=o,ue=s,$s(),!0;return!1}function $s(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=le();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=Ce();t()}catch{}}function Bh(){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 Hh(){return Te(),Object.entries(fe).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===xe&&s.id===ue}))}))}function Gh(){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 zh(t){yn=Array.isArray(t)?t:[]}function Kh(){return[...yn]}function Jh(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 Wc(t){let e=[xe,...yn.filter(r=>r!==xe)],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=qh(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?Fc(ue,i):ue;return u&&d!==ue&&process.stderr.write(` [fallback: ${i}:${d}]
|
|
553
|
+
`),await t(c,i,d)}catch(u){if(s=u,Jh(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 Yh(t,e,s={}){return Te(),Wc((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function Xh(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||ue,...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 Wc(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 Vh(){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 Qh(){for(let t of Object.keys(fe))delete fe[t];xe=null,ue=null,yn=[]}Bc.exports={registerProvider:Ft,getProvider:jh,getActiveProvider:Vo,getActiveProviderName:Dh,getActiveModelId:Fh,getActiveModel:Uh,setActiveModel:Wh,getModelNames:Bh,parseModelSpec:Uc,listProviders:Hh,listAllModels:Gh,callStream:Yh,callChat:Xh,getConfiguredProviders:Vh,setFallbackChain:zh,getFallbackChain:Kh,resolveModelForProvider:Fc,MODEL_EQUIVALENTS:Xo,_reset:Qh}});var zc=M((D$,Gc)=>{"use strict";var Zh="\x1B[2m",eg="\x1B[0m";function Hc(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Qo=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 Zh+"\u2500".repeat(this._cols)+eg}drawFooter(e){!this._origWrite||this._drawing||(this._drawing=!0,this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K"+this._statusLine(e)+"\x1B8"),this._drawing=!1)}_setScrollRegion(){let e=Math.max(1,this._scrollEnd);this._origWrite(`\x1B[1;${e}r`)}_clearScrollRegion(){this._origWrite&&this._origWrite("\x1B[r")}_eraseStatus(){this._origWrite&&this._origWrite("\x1B7"+this._goto(this._rowStatus)+"\x1B[2K\x1B8")}activate(e){if(!process.stdout.isTTY)return;this._rl=e,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let s=this,n=process.stdout.write.bind(process.stdout);this._origWrite=n,process.stdout.write=function(u,...d){if(s._active&&typeof u=="string"){if(s._cursorOnInputRow){let y=u.replace(/\n/g,"");return y?n(y,...d):!0}let f=s._cols||80,m=0,h=u.split(`
|
|
554
|
+
`);for(let y=0;y<h.length;y++){let $=Hc(h[y]);$>0&&(m+=Math.floor($/f))}let g=h.length-1+m;g>0&&(s._lastOutputRow=Math.min(s._lastOutputRow+g,s._scrollEnd))}return n(u,...d)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(u,...d){if(!s._active)return s._origStderrWrite(u,...d);if(typeof u=="string"&&u.includes("\r")){let f=Math.min(s._lastOutputRow+1,s._scrollEnd);s._origWrite(s._goto(f))}return s._origStderrWrite(u,...d)},this._origLog=console.log,this._origError=console.error;function o(...u){if(!s._active){s._origLog(...u);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origLog(...u),s.drawFooter()}function r(...u){if(!s._active){s._origError(...u);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origError(...u),s.drawFooter()}console.log=o,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(u){s._origSetPr(u),s._active&&s.drawFooter(u)},this._origPrompt=e.prompt.bind(e),e.prompt=function(u){if(!s._active)return s._origPrompt(u);e._prevPos=null,s._origWrite(s._goto(s._rowInput)),s._origPrompt(u),s._cursorOnInputRow=!0};let i=e.question.bind(e);e.question=function(u,d){if(!s._active)return i(u,d);s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),e._prevPos=null,s._cursorOnInputRow=!0,i(u,f=>{s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),s._cursorOnInputRow=!1,s.drawFooter(),d(f)})};let c=e._refreshLine?e._refreshLine.bind(e):null;this._origRefreshLine=c,c&&(e._refreshLine=function(){if(!s._active)return c();let u=s._cols,d=Hc(e._prompt||""),f=u-d-1;if(e.line.length<=f)return c();let m=e.line,h=e.cursor,p=Math.max(1,f-1),y=Math.max(0,h-p),$=(y>0?"\xAB":"")+m.slice(y,y+p+(y>0?0:1));e.line=$,e.cursor=$.length,c(),e.line=m,e.cursor=h}),e.on("line",u=>{s._active&&(s._cursorOnInputRow=!1,s._origWrite(s._goto(s._rowInput)+"\x1B[2K"),s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s.drawFooter())});let l=()=>{this._setScrollRegion(),this.drawFooter()};process.stdout.on("resize",l),this._offResize=()=>process.stdout.off("resize",l)}deactivate(){this._active&&(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._origStderrWrite&&(process.stderr.write=this._origStderrWrite,this._origStderrWrite=null),this._origLog&&(console.log=this._origLog,this._origLog=null),this._origError&&(console.error=this._origError,this._origError=null),this._origWrite&&(process.stdout.write=this._origWrite),this._rl&&(this._origPrompt&&(this._rl.prompt=this._origPrompt,this._origPrompt=null),this._origSetPr&&(this._rl.setPrompt=this._origSetPr,this._origSetPr=null),this._origRefreshLine&&(this._rl._refreshLine=this._origRefreshLine,this._origRefreshLine=null)),this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null)}};Gc.exports={StickyFooter:Qo}});var Yc=M((F$,Jc)=>{var{C:Z}=ae(),{listProviders:tg,getActiveProviderName:ng,getActiveModelId:sg,setActiveModel:og}=pe();function Kc(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
|
|
555
|
+
`);process.stdout.write(`\x1B[${m}A`)}let $=[];$.push(` ${Z.bold}${Z.cyan}${n}${Z.reset}`),$.push(` ${Z.dim}${o}${Z.reset}`),$.push("");let{start:x,end:A}=f();x>0&&$.push(` ${Z.dim}\u2191 more${Z.reset}`);for(let v=x;v<A;v++){let T=e[v];if(T.isHeader){$.push(` ${Z.bold}${Z.dim}${T.label}${Z.reset}`);continue}let S=i[l]===v,C=S?`${Z.cyan}> `:" ",U=T.isCurrent?` ${Z.yellow}<current>${Z.reset}`:"";S?$.push(`${C}${Z.bold}${T.label}${Z.reset}${U}`):$.push(`${C}${Z.dim}${T.label}${Z.reset}${U}`)}A<e.length&&$.push(` ${Z.dim}\u2193 more${Z.reset}`);let k=$.join(`
|
|
550
556
|
`);process.stdout.write(k+`
|
|
551
|
-
`),m=$.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function y($,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
|
|
557
|
+
`),m=$.length}t.pause();let p=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&p!==void 0&&process.stdin.setRawMode(p),t.resume()}function y($,x){if(x){if(x.name==="up"||x.ctrl&&x.name==="p"){l>0&&(l--,h());return}if(x.name==="down"||x.ctrl&&x.name==="n"){l<i.length-1&&(l++,h());return}if(x.name==="return"){let A=e[i[l]];g(),r(A?A.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",y),h()})}async function rg(t){let e=tg(),s=ng(),n=sg(),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 Kc(t,o,{title:"Select Model"});return r?(og(r),console.log(`${Z.green}Switched to ${r}${Z.reset}`),!0):(console.log(`${Z.dim}Cancelled${Z.reset}`),!1)}Jc.exports={pickFromList:Kc,showModelPicker:rg}});var tr=M((W$,nl)=>{var Zo=require("fs"),ig=require("path"),{callChat:Xc}=pe(),{remember:ag,listMemories:U$,recall:cg}=et(),er=4,lg=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
552
558
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
553
559
|
|
|
554
560
|
Return ONLY valid JSON in this exact format:
|
|
@@ -574,15 +580,15 @@ Rules:
|
|
|
574
580
|
- value: concise actionable instruction, max 120 chars
|
|
575
581
|
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
576
582
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
577
|
-
- Return ONLY the JSON, no markdown, no explanation`;function
|
|
583
|
+
- Return ONLY the JSON, no markdown, no explanation`;function Vc(t){return t.filter(e=>(e.role==="user"||e.role==="assistant")&&typeof e.content=="string"&&e.content.trim().length>10).slice(-40).map(e=>`[${e.role.toUpperCase()}]: ${e.content.substring(0,700)}`).join(`
|
|
578
584
|
|
|
579
|
-
`)}async function
|
|
585
|
+
`)}async function Qc(t){if(t.filter(o=>o.role==="user").length<er)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=Vc(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=[{role:"system",content:lg},{role:"user",content:`Conversation to analyze:
|
|
580
586
|
|
|
581
|
-
${s}`}];try{let i=((await
|
|
587
|
+
${s}`}];try{let i=((await Xc(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 Zc(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=cg(o);i!==r&&(ag(o,r),e.push({key:o,value:r,action:i?"updated":"added"}))}return e}function el(t){if(!t||t.length===0)return[];let e=ig.join(process.cwd(),"NEX.md"),s="";try{Zo.existsSync(e)&&(s=Zo.readFileSync(e,"utf-8"))}catch{}let n=[],o=s;for(let r of t){if(!r||typeof r!="string")continue;let i=r.trim();if(!i)continue;let c=i.substring(0,35).toLowerCase();s.toLowerCase().includes(c)||(n.push(i),o=o?o.endsWith(`
|
|
582
588
|
`)?o+i:o+`
|
|
583
589
|
`+i:i)}return n.length>0&&(o.endsWith(`
|
|
584
590
|
`)||(o+=`
|
|
585
|
-
`),
|
|
591
|
+
`),Zo.writeFileSync(e,o,"utf-8")),n}async function ug(t){let e=await Qc(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=Zc(e.memories),n=el(e.nex_additions);return{applied:s,nexAdded:n,summary:e.summary}}var dg=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
586
592
|
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
587
593
|
|
|
588
594
|
Return ONLY valid JSON in this exact format:
|
|
@@ -616,37 +622,37 @@ Rules:
|
|
|
616
622
|
---
|
|
617
623
|
- Maximum 3 documents per session. Quality over quantity.
|
|
618
624
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
619
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function
|
|
625
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function tl(t){if(t.filter(o=>o.role==="user").length<er)return{documents:[],skip_reason:"Session too short"};let s=Vc(t);if(!s.trim())return{documents:[],skip_reason:"No usable content"};let n=[{role:"system",content:dg},{role:"user",content:`Conversation to analyze:
|
|
620
626
|
|
|
621
|
-
${s}`}];try{let i=((await
|
|
627
|
+
${s}`}];try{let i=((await Xc(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 fg(t){let e=await tl(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}=cn(),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=`
|
|
622
628
|
|
|
623
629
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
624
630
|
|
|
625
|
-
${i.content}`;s(c,l.content+d),o.push({name:c,reason:i.reason||"",action:"updated"})}else s(c,i.content),o.push({name:c,reason:i.reason||"",action:"created"})}return{written:o,skipped:r}}
|
|
631
|
+
${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}}nl.exports={learnFromSession:ug,learnBrainFromSession:fg,reflectOnSession:Qc,reflectBrain:tl,applyMemories:Zc,applyNexAdditions:el,LEARN_MIN_MESSAGES:er}});var al=M((H$,il)=>{var ge=require("fs"),Wt=require("path"),B$=require("os"),mg=require("readline"),{C:R}=ae(),sl=".nex",nr=null;function pg(t){nr=t}function ke(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(nr)nr.question(n,r);else{let i=mg.createInterface({input:process.stdin,output:process.stdout});i.question(n,c=>{i.close(),r(c)})}})}function Ut(t,e=!0){return ke(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(n=>n.toLowerCase()!=="n"&&n.toLowerCase()!=="no")}async function ol(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 ke("Enter number",String(o)),i=parseInt(r,10)-1;return e[Math.max(0,Math.min(i,e.length-1))]}async function hg(){let t=Wt.join(process.cwd(),sl),e=Wt.join(t,"servers.json"),s={};if(ge.existsSync(e))try{s=JSON.parse(ge.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
626
632
|
${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}
|
|
627
|
-
`);let n=Object.keys(s);if(n.length>0&&(console.log(`${R.dim}Existing profiles: ${n.join(", ")}${R.reset}`),!await
|
|
633
|
+
`);let n=Object.keys(s);if(n.length>0&&(console.log(`${R.dim}Existing profiles: ${n.join(", ")}${R.reset}`),!await Ut("Add or update a server profile?",!0))){console.log(`${R.dim}No changes made.${R.reset}
|
|
628
634
|
`);return}let o={...s},r=!0;for(;r;){console.log(`
|
|
629
|
-
${R.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${R.reset}`);let l=await
|
|
630
|
-
${R.green}\u2713${R.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${p!=="other"?` [${p}]`:""}`),r=await
|
|
631
|
-
Add another server?`,!1)}
|
|
635
|
+
${R.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${R.reset}`);let l=await ke("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${R.red} Name is required.${R.reset}`);continue}let u=await ke("Host / IP address");if(!u){console.log(`${R.red} Host is required.${R.reset}`);continue}let d=await ke("SSH user","root"),f=await ke("SSH port","22"),m=parseInt(f,10)||22,h=await ke("SSH key path (leave empty for SSH agent)",""),p=await ol("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await Ut("Allow sudo commands?",!0),y={host:u,user:d};m!==22&&(y.port=m),h&&(y.key=h),p!=="other"&&(y.os=p),g&&(y.sudo=!0),o[l]=y,console.log(`
|
|
636
|
+
${R.green}\u2713${R.reset} Profile "${l}" added: ${d}@${u}${m!==22?`:${m}`:""}${p!=="other"?` [${p}]`:""}`),r=await Ut(`
|
|
637
|
+
Add another server?`,!1)}ge.existsSync(t)||ge.mkdirSync(t,{recursive:!0}),ge.writeFileSync(e,JSON.stringify(o,null,2)+`
|
|
632
638
|
`,"utf-8"),console.log(`
|
|
633
|
-
${R.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${R.reset}`);let i=
|
|
639
|
+
${R.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${R.reset}`);let i=Wt.join(process.cwd(),".gitignore");ge.existsSync(i)&&(ge.readFileSync(i,"utf-8").includes(".nex/")||await Ut("Add .nex/ to .gitignore?",!0)&&(ge.appendFileSync(i,`
|
|
634
640
|
# nex-code server profiles
|
|
635
641
|
.nex/
|
|
636
|
-
`),console.log(`${R.green}\u2713 Added .nex/ to .gitignore${R.reset}`))),await
|
|
637
|
-
Set up deploy configs (.nex/deploy.json)?`,!1)&&await
|
|
642
|
+
`),console.log(`${R.green}\u2713 Added .nex/ to .gitignore${R.reset}`))),await Ut(`
|
|
643
|
+
Set up deploy configs (.nex/deploy.json)?`,!1)&&await rl(o,t),console.log(`
|
|
638
644
|
${R.dim}Use /servers to list profiles, /servers ping to check connectivity.${R.reset}
|
|
639
|
-
`)}async function
|
|
645
|
+
`)}async function rl(t,e){let s=e||Wt.join(process.cwd(),sl),n=Wt.join(s,"deploy.json"),o={};if(ge.existsSync(n))try{o=JSON.parse(ge.readFileSync(n,"utf-8"))}catch{}if(!t){let u=Wt.join(s,"servers.json");if(ge.existsSync(u))try{t=JSON.parse(ge.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
640
646
|
${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}
|
|
641
647
|
`);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(`
|
|
642
|
-
${R.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${R.reset}`);let u=await
|
|
643
|
-
${R.green}\u2713${R.reset} Deploy config "${u}": ${$} \u2192 ${d}:${m}`),h&&console.log(` ${R.dim} Then: ${h}${R.reset}`),l=await
|
|
644
|
-
Add another deploy config?`,!1)}
|
|
648
|
+
${R.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${R.reset}`);let u=await ke("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 ol("Target server",r,r[0]):d=await ke("Target server (profile name or user@host)");let f=await ke("Local path to sync (e.g. dist/ or ./build)","dist/"),m=await ke("Remote destination path (e.g. /var/www/app)");if(!m){console.log(`${R.red} Remote path is required.${R.reset}`);continue}let h=await ke("Deploy script to run after sync (leave empty to skip)",""),p=await ke("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env"),g=p?p.split(",").map(x=>x.trim()).filter(Boolean):[],y={server:d,local_path:f,remote_path:m};h&&(y.deploy_script=h),g.length>0&&(y.exclude=g),c[u]=y;let $=f.endsWith("/")?f:`${f}/`;console.log(`
|
|
649
|
+
${R.green}\u2713${R.reset} Deploy config "${u}": ${$} \u2192 ${d}:${m}`),h&&console.log(` ${R.dim} Then: ${h}${R.reset}`),l=await Ut(`
|
|
650
|
+
Add another deploy config?`,!1)}ge.existsSync(s)||ge.mkdirSync(s,{recursive:!0}),ge.writeFileSync(n,JSON.stringify(c,null,2)+`
|
|
645
651
|
`,"utf-8"),console.log(`
|
|
646
652
|
${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}
|
|
647
|
-
`)}
|
|
653
|
+
`)}il.exports={runServerWizard:hg,runDeployWizard:rl,setWizardRL:pg}});var ul=M((G$,ll)=>{var gg=require("axios"),wn=require("fs"),cl=require("path"),$g="nex-code",sr=cl.join(process.cwd(),".nex"),or=cl.join(sr,"last-version-check");wn.existsSync(sr)||wn.mkdirSync(sr,{recursive:!0});async function yg(){try{let t=bg(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};xg(e);let s=wg(),o=(await gg.get(`https://registry.npmjs.org/${$g}/latest`,{timeout:5e3})).data.version,r=_g(o,s);return{hasNewVersion:r,latestVersion:r?o:void 0,currentVersion:r?s:void 0}}catch{return{hasNewVersion:!1}}}function wg(){return kn().version}function bg(){try{if(wn.existsSync(or)){let t=wn.readFileSync(or,"utf8");return parseInt(t,10)}}catch{}return null}function xg(t){try{wn.writeFileSync(or,t.toString())}catch{}}function _g(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}}ll.exports={checkForNewVersion:yg}});var Sl=M((K$,vl)=>{var kg=require("readline"),rt=require("fs"),qe=require("path"),{C:a,banner:vg,cleanupTerminal:dl}=ae(),{listProviders:ir,getActiveProviderName:st,listAllModels:z$,setFallbackChain:Sg,getFallbackChain:Eg,getProvider:Tg}=pe(),{flushAutoSave:fl}=gt(),{getActiveModel:ot,setActiveModel:ml}=Pn(),{printContext:pl}=ko(),{loadAllSkills:Cg,getSkillCommands:ar,handleSkillCommand:Rg}=Yt(),{setReadlineInterface:Ag,setAutoConfirm:Og,getAutoConfirm:hl}=Ne(),{StickyFooter:Ng}=zc(),ws=process.cwd(),Je=null;function gl(){return Je?.signal??null}var bs=[{cmd:"/help",desc:"Show full help"},{cmd:"/model",desc:"Show/switch model"},{cmd:"/providers",desc:"List providers and models"},{cmd:"/fallback",desc:"Show/set fallback chain"},{cmd:"/tokens",desc:"Token usage and context budget"},{cmd:"/costs",desc:"Session token costs"},{cmd:"/budget",desc:"Show/set cost limits per provider"},{cmd:"/clear",desc:"Clear conversation"},{cmd:"/context",desc:"Show project context"},{cmd:"/autoconfirm",desc:"Toggle auto-confirm"},{cmd:"/save",desc:"Save session"},{cmd:"/load",desc:"Load a saved session"},{cmd:"/sessions",desc:"List saved sessions"},{cmd:"/resume",desc:"Resume last session"},{cmd:"/remember",desc:"Save a memory"},{cmd:"/forget",desc:"Delete a memory"},{cmd:"/memory",desc:"Show all memories"},{cmd:"/brain",desc:"Manage knowledge base"},{cmd:"/brain add",desc:"Add document: /brain add <name> [content]"},{cmd:"/brain list",desc:"List all brain documents"},{cmd:"/brain search",desc:"Search brain: /brain search <query>"},{cmd:"/brain show",desc:"Show document: /brain show <name>"},{cmd:"/brain remove",desc:"Remove document: /brain remove <name>"},{cmd:"/brain rebuild",desc:"Rebuild keyword index"},{cmd:"/brain embed",desc:"Build/rebuild embedding index"},{cmd:"/brain status",desc:"Show brain status (docs, index, embeddings)"},{cmd:"/brain review",desc:"Review pending brain changes (git diff)"},{cmd:"/brain undo",desc:"Undo last brain write"},{cmd:"/learn",desc:"Reflect on session and update memory"},{cmd:"/optimize",desc:"Show optimization opportunities"},{cmd:"/permissions",desc:"Show tool permissions"},{cmd:"/allow",desc:"Auto-allow a tool"},{cmd:"/deny",desc:"Block a tool"},{cmd:"/plan",desc:"Plan mode (analyze before executing)"},{cmd:"/plans",desc:"List saved plans"},{cmd:"/auto",desc:"Set autonomy level"},{cmd:"/commit",desc:"Smart commit (diff + message)"},{cmd:"/diff",desc:"Show current diff"},{cmd:"/review [--strict] [file]",desc:"Deep code review with score table and diff suggestions (--strict: force \u22653 critical findings)"},{cmd:"/branch",desc:"Create feature branch"},{cmd:"/mcp",desc:"MCP servers and tools"},{cmd:"/hooks",desc:"Show configured hooks"},{cmd:"/skills",desc:"List, enable, disable skills"},{cmd:"/tasks",desc:"Show task list"},{cmd:"/servers",desc:"List server profiles / ping"},{cmd:"/docker",desc:"List containers across all servers"},{cmd:"/deploy",desc:"List deploy configs / run named deploy"},{cmd:"/init",desc:"Interactive setup wizard (.nex/)"},{cmd:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function $l(){let t=ar(),e=[...bs,...t],s=Math.max(...e.map(n=>n.cmd.length));console.log("");for(let{cmd:n,desc:o}of bs)console.log(` ${a.cyan}${n.padEnd(s+2)}${a.reset}${a.dim}${o}${a.reset}`);for(let{cmd:n,desc:o}of t)console.log(` ${a.cyan}${n.padEnd(s+2)}${a.reset}${a.dim}${o} ${a.yellow}[skill]${a.reset}`);console.log(`
|
|
648
654
|
${a.dim}Type /help for detailed usage${a.reset}
|
|
649
|
-
`)}function
|
|
655
|
+
`)}function yl(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(ws,e);if(!rt.existsSync(n)||!rt.statSync(n).isDirectory())return[];let o=rt.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 wl(t){if(t.startsWith("/")){let n=[...bs,...ar()],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("~"))?[yl(s),s]:[[],t]}function bl(){console.log(`
|
|
650
656
|
${a.bold}${a.cyan}Commands:${a.reset}
|
|
651
657
|
${a.cyan}/help${a.reset} ${a.dim}Show this help${a.reset}
|
|
652
658
|
${a.cyan}/model [spec]${a.reset} ${a.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${a.reset}
|
|
@@ -707,48 +713,48 @@ ${a.bold}${a.cyan}Undo / Redo:${a.reset}
|
|
|
707
713
|
${a.cyan}/history${a.reset} ${a.dim}Show file change history${a.reset}
|
|
708
714
|
|
|
709
715
|
${a.cyan}/exit${a.reset} ${a.dim}Quit${a.reset}
|
|
710
|
-
`)}function
|
|
711
|
-
${a.bold}${a.cyan}Providers:${a.reset}`);for(let n of t){let o=n.provider===e,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
|
|
712
|
-
${a.bold}${a.cyan}Token Usage:${a.reset}`),console.log(` ${a.dim}Model:${a.reset} ${d}:${u.id} (${(l.limit/1e3).toFixed(0)}k context)`),console.log(` ${a.dim}Used:${a.reset} ${l.used.toLocaleString()} / ${l.limit.toLocaleString()} (${l.percentage}%)`);let f=
|
|
713
|
-
${a.dim}Breakdown:${a.reset}`),console.log(` System prompt: ${l.breakdown.system.toLocaleString()} tokens`),console.log(` Conversation: ${l.breakdown.conversation.toLocaleString()} tokens`),console.log(` Tool results: ${l.breakdown.toolResults.toLocaleString()} tokens`),console.log(` Tool definitions: ${l.breakdown.toolDefinitions.toLocaleString()} tokens`),console.log(` Messages: ${l.messageCount}`),console.log(),!0}case"/costs":{let{formatCosts:o,resetCosts:r}=
|
|
716
|
+
`)}function xl(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 rr(){let t=ir(),e=st(),s=ot();console.log(`
|
|
717
|
+
${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 _l(t,e){let[s,...n]=t.split(/\s+/);switch(s){case"/help":return bl(),!0;case"/model":{let o=n.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=Yc();await r(e)}else{let r=ot(),i=st();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 rr(),!0;if(ml(o)){let r=ot(),i=st();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 rr(),!0;case"/fallback":{let o=n.join(" ").trim();if(!o){let i=Eg();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 Sg(r),console.log(`${a.green}Fallback chain: ${r.join(" \u2192 ")}${a.reset}`),!0}case"/tokens":{let{getConversationMessages:o}=le(),{getUsage:r}=Ce(),{TOOL_DEFINITIONS:i}=We(),c=o(),l=r(c,i),u=ot(),d=st();console.log(`
|
|
718
|
+
${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=xl(l.percentage);return console.log(` ${f}`),console.log(`
|
|
719
|
+
${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}=Tt();return n.join(" ").trim()==="reset"?(r(),console.log(`${a.green}Cost tracking reset${a.reset}`),!0):(console.log(`
|
|
714
720
|
${o()}
|
|
715
|
-
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=
|
|
716
|
-
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let y of p){let $=r(y.provider),x=h[y.provider];if(x!==void 0){g=!0;let
|
|
721
|
+
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=Tt(),d=n[0];if(!d){let h=o(),p=ir();console.log(`
|
|
722
|
+
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let y of p){let $=r(y.provider),x=h[y.provider];if(x!==void 0){g=!0;let A=Math.min(100,Math.round($/x*100)),k=10,v=Math.round(A/100*k),T=k-v,C=`${A>=100?a.red:A>=80?a.yellow:a.green}${"\u2588".repeat(v)}${a.dim}${"\u2591".repeat(T)}${a.reset}`;console.log(` ${a.bold}${y.provider}:${a.reset} $${$.toFixed(2)} / $${x.toFixed(2)} (${A}%) ${C}`)}else y.provider==="ollama"||y.provider==="local"?console.log(` ${a.bold}${y.provider}:${a.reset} ${a.dim}free (no limit)${a.reset}`):$>0&&console.log(` ${a.bold}${y.provider}:${a.reset} $${$.toFixed(2)} ${a.dim}(no limit)${a.reset}`)}return g||console.log(` ${a.dim}No limits set. Use /budget <provider> <amount> to set one.${a.reset}`),console.log(),!0}let f=n[1];if(!f){let h=i(d);return h.limit!==null?console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} / $${h.limit.toFixed(2)} ($${h.remaining.toFixed(2)} remaining)`):console.log(`${a.bold}${d}:${a.reset} $${h.spent.toFixed(2)} ${a.dim}(no limit)${a.reset}`),!0}if(f==="off"||f==="remove"||f==="clear")return c(d),l(),console.log(`${a.green}Removed cost limit for ${d}${a.reset}`),!0;let m=parseFloat(f);return isNaN(m)||m<=0?(console.log(`${a.red}Invalid amount: ${f}. Use a positive number or 'off'.${a.reset}`),!0):(u(d,m),l(),console.log(`${a.green}Set ${d} budget limit: $${m.toFixed(2)}${a.reset}`),!0)}case"/clear":{let{clearConversation:o,getConversationMessages:r}=le(),{clearHistory:i}=Rt(),c=r();if(c.filter(u=>u.role==="user").length>=4){process.stdout.write(`${a.dim}Reflecting on session...${a.reset} `);let{learnFromSession:u}=tr();u(c).then(d=>{if(!d.skipped&&!d.error&&(d.applied.length>0||d.nexAdded.length>0)){let f=d.applied.length+d.nexAdded.length;process.stdout.write(`${a.green}${f} learning(s) saved${a.reset}
|
|
717
723
|
`)}else process.stdout.write(`${a.dim}nothing new${a.reset}
|
|
718
724
|
`)}).catch(()=>process.stdout.write(`
|
|
719
|
-
`))}return o(),i(),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/context":return await
|
|
720
|
-
${a.bold}${a.cyan}Sessions:${a.reset}`);for(let i of r){let c=i.updatedAt?new Date(i.updatedAt).toLocaleString():"?",l=i.name==="_autosave"?` ${a.dim}(auto)${a.reset}`:"";console.log(` ${a.cyan}${i.name}${a.reset}${l} \u2014 ${i.messageCount} msgs, ${c}`)}return console.log(),!0}case"/resume":{let{getLastSession:o}=
|
|
721
|
-
${a.bold}${a.cyan}Memory:${a.reset}`);for(let i of r)console.log(` ${a.cyan}${i.key}${a.reset} = ${i.value}`);return console.log(),!0}case"/brain":{let{listDocuments:o,readDocument:r,writeDocument:i,removeDocument:c,buildIndex:l,buildEmbeddingIndex:u,isEmbeddingAvailable:d,query:f}=
|
|
725
|
+
`))}return o(),i(),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/context":return await pl(ws),!0;case"/autoconfirm":{let o=!hl();return Og(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}=gt(),{getConversationMessages:r}=le(),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=ot(),u=st();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}=gt(),{setConversationMessages:r}=le(),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}=gt(),r=o();if(r.length===0)return console.log(`${a.dim}No saved sessions${a.reset}`),!0;console.log(`
|
|
726
|
+
${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}=gt(),{setConversationMessages:r}=le(),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}=et(),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}=et(),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}=et(),r=o();if(r.length===0)return console.log(`${a.dim}No memories saved${a.reset}`),!0;console.log(`
|
|
727
|
+
${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}=cn(),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}
|
|
722
728
|
|
|
723
729
|
`);let g=require("path").join(process.cwd(),".nex","brain",`${h}.md`);console.log(`${a.green}Created .nex/brain/${h}.md${a.reset}`),console.log(`${a.dim}Edit it directly at: ${g}${a.reset}`)}else{let g=h.substring(0,p),y=h.substring(p+1);i(g,y),console.log(`${a.green}Added to brain: ${g}${a.reset}`)}return!0}case"list":{let p=o();if(p.length===0)return console.log(`${a.dim}No brain documents yet. Use /brain add <name> to create one.${a.reset}`),!0;console.log(`
|
|
724
|
-
${a.bold}${a.cyan}Brain Documents:${a.reset}`);let g=Math.max(8,...p.map($=>$.name.length)),y=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd(y)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat(y)}${"-".repeat(7)} --------`);for(let $ of p){let{frontmatter:x}=r($.name),
|
|
730
|
+
${a.bold}${a.cyan}Brain Documents:${a.reset}`);let g=Math.max(8,...p.map($=>$.name.length)),y=20;console.log(` ${"Name".padEnd(g+2)}${"Tags".padEnd(y)}${"Size".padStart(7)} Modified`),console.log(` ${"-".repeat(g+2)}${"-".repeat(y)}${"-".repeat(7)} --------`);for(let $ of p){let{frontmatter:x}=r($.name),A=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}${A.substring(0,y-1).padEnd(y)}${k.padStart(7)} ${v}${a.reset}`)}return console.log(),!0}case"search":{if(!h)return console.log(`${a.red}Usage: /brain search <query>${a.reset}`),!0;let p=await f(h,{topK:5});if(p.length===0)return console.log(`${a.dim}No matching brain documents for: ${h}${a.reset}`),!0;console.log(`
|
|
725
731
|
${a.bold}${a.cyan}Brain Search: "${h}"${a.reset}`);for(let g of p){let y=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
|
|
726
732
|
${a.cyan}${g.name}${a.reset} ${a.dim}(score: ${y})${a.reset}`),console.log(` ${a.dim}${g.excerpt||""}${a.reset}`)}return console.log(),!0}case"show":{if(!h)return console.log(`${a.red}Usage: /brain show <name>${a.reset}`),!0;let p=r(h);return p.content?(console.log(`
|
|
727
733
|
${a.bold}${a.cyan}${h}.md${a.reset}
|
|
728
|
-
`),console.log(p.content),!0):(console.log(`${a.red}Document not found: ${h}${a.reset}`),!0)}case"remove":{if(!h)return console.log(`${a.red}Usage: /brain remove <name>${a.reset}`),!0;let{confirm:p}=
|
|
729
|
-
${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${p.length}`),console.log(` Index: ${g.existsSync($)?a.green+"present"+a.reset:a.dim+"not built"+a.reset}`),console.log(` Embeddings: ${g.existsSync(x)?a.green+"present"+a.reset:a.dim+"not built (run /brain embed)"+a.reset}`),p.length>0){let
|
|
734
|
+
`),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}=Ne();if(!await p(`Remove brain document "${h}"?`))return console.log(`${a.dim}Cancelled${a.reset}`),!0;let y=c(h);return console.log(y?`${a.green}Removed: ${h}.md${a.reset}`:`${a.red}Document not found: ${h}${a.reset}`),!0}case"rebuild":{let p=l(),g=Object.keys(p.documents).length;return console.log(`${a.green}Index rebuilt: ${g} document(s)${a.reset}`),!0}case"embed":{if(!await d())return console.log(`${a.yellow}Ollama embedding model not available.${a.reset}`),console.log(`${a.dim}Set NEX_EMBED_MODEL env var (default: nomic-embed-text) and ensure Ollama is running.${a.reset}`),!0;console.log(`${a.dim}Building embedding index...${a.reset}`);try{let g=await u(),y=Object.keys(g.documents||{}).length;console.log(`${a.green}Embedding index built: ${y} document(s)${a.reset}`)}catch(g){console.log(`${a.red}Embedding failed: ${g.message}${a.reset}`)}return!0}case"status":{let p=o(),g=require("fs"),y=require("path"),$=y.join(process.cwd(),".nex","brain",".brain-index.json"),x=y.join(process.cwd(),".nex","brain",".embeddings.json");if(console.log(`
|
|
735
|
+
${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 A=p.reduce((k,v)=>k+v.size,0);console.log(` Total size: ${A<1024?A+"B":(A/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:p}=require("child_process"),{promisify:g}=require("util"),y=g(p);try{let{stdout:$}=await y("git diff .nex/brain/",{cwd:process.cwd()});$.trim()?(console.log(`
|
|
730
736
|
${a.bold}${a.cyan}Brain Changes (git diff):${a.reset}
|
|
731
|
-
`),console.log($)):console.log(`${a.dim}No pending brain changes (clean git state)${a.reset}`)}catch{console.log(`${a.dim}Not a git repo or no brain dir${a.reset}`)}return!0}case"undo":{let p=require("fs"),y=require("path").join(process.cwd(),".nex","brain");if(!p.existsSync(y))return console.log(`${a.dim}No brain directory found${a.reset}`),!0;let $=o();if($.length===0)return console.log(`${a.dim}No brain documents to undo${a.reset}`),!0;let x=$[0],{exec:
|
|
737
|
+
`),console.log($)):console.log(`${a.dim}No pending brain changes (clean git state)${a.reset}`)}catch{console.log(`${a.dim}Not a git repo or no brain dir${a.reset}`)}return!0}case"undo":{let p=require("fs"),y=require("path").join(process.cwd(),".nex","brain");if(!p.existsSync(y))return console.log(`${a.dim}No brain directory found${a.reset}`),!0;let $=o();if($.length===0)return console.log(`${a.dim}No brain documents to undo${a.reset}`),!0;let x=$[0],{exec:A}=require("child_process"),{promisify:k}=require("util"),v=k(A);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(`
|
|
732
738
|
${a.bold}${a.cyan}Brain Knowledge Base${a.reset}`),console.log(`${a.dim}No documents yet. Create with /brain add <name>${a.reset}`),console.log(`
|
|
733
739
|
${a.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${a.reset}
|
|
734
740
|
`);else{console.log(`
|
|
735
741
|
${a.bold}${a.cyan}Brain: ${p.length} document(s)${a.reset}`);for(let g of p){let{frontmatter:y}=r(g.name),$=Array.isArray(y.tags)?` [${y.tags.join(", ")}]`:"";console.log(` ${a.cyan}${g.name}${a.reset}${a.dim}${$}${a.reset}`)}console.log(`
|
|
736
742
|
${a.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${a.reset}
|
|
737
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=
|
|
743
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=tr(),{getConversationMessages:i}=le(),c=i(),l=c.filter(u=>u.role==="user").length;if(l<4)return console.log(`${a.yellow}Session too short to learn from (need 4+ user messages, have ${l})${a.reset}`),!0;console.log(`${a.dim}Analyzing session for learnings...${a.reset}`);try{let[u,d]=await Promise.all([o(c),r(c)]);if(u.skipped&&(!d.written||d.written.length===0))return console.log(`${a.dim}Session too short${a.reset}`),!0;u.error&&console.log(`${a.red}Reflection error: ${u.error}${a.reset}`),console.log(""),u.summary&&(console.log(`${a.bold}Session:${a.reset} ${a.dim}${u.summary}${a.reset}`),console.log(""));let f=u.applied&&u.applied.length>0,m=u.nexAdded&&u.nexAdded.length>0,h=d.written&&d.written.length>0;if(!f&&!m&&!h)console.log(`${a.dim}No new learnings extracted from this session${a.reset}`);else{if(f){console.log(`${a.bold}${a.cyan}Memory updates:${a.reset}`);for(let{key:p,value:g,action:y}of u.applied){let $=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${$} ${a.bold}${p}${a.reset} = ${g}`)}}if(m){console.log(`${a.bold}${a.cyan}Added to NEX.md:${a.reset}`);for(let p of u.nexAdded)console.log(` ${a.green}+${a.reset} ${p}`)}if(h){console.log(`${a.bold}${a.cyan}Brain documents:${a.reset}`);for(let{name:p,reason:g,action:y}of d.written){let $=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${$} ${a.bold}${p}.md${a.reset}${g?a.dim+" \u2014 "+g+a.reset:""}`)}}}console.log("")}catch(u){console.log(`${a.red}Learn failed: ${u.message}${a.reset}`)}return!0}case"/optimize":{let{getConversationMessages:o}=le(),{getUsage:r}=Ce(),{TOOL_DEFINITIONS:i}=We(),{listMemories:c}=et(),l=o(),u=r(l,i),d=ot(),f=st(),m=c();console.log(`
|
|
738
744
|
${a.bold}${a.cyan}Optimization Report${a.reset}
|
|
739
745
|
`);let h=u.percentage>80?a.red:u.percentage>50?a.yellow:a.green;if(console.log(`${a.bold}Context Window:${a.reset} ${h}${u.percentage}%${a.reset} used (${u.used.toLocaleString()} / ${u.limit.toLocaleString()} tokens)`),u.percentage>75?console.log(` ${a.yellow}\u2192 Tip: Use /clear to free context (auto-learns first)${a.reset}`):u.percentage>50?console.log(` ${a.dim}\u2192 Context is filling up, consider /clear soon${a.reset}`):console.log(` ${a.green}\u2192 Context healthy${a.reset}`),console.log(`
|
|
740
|
-
${a.bold}Memory:${a.reset} ${m.length} entries`),m.length===0)console.log(` ${a.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${a.reset}`);else{let
|
|
746
|
+
${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 A=[...m].sort((T,S)=>new Date(S.updatedAt)-new Date(T.updatedAt))[0],k=A?Math.round((Date.now()-new Date(A.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(`
|
|
741
747
|
${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(`
|
|
742
748
|
${a.bold}Session:${a.reset} ${g} turns, ${l.length} messages total`),g>=4&&g%10===0&&console.log(` ${a.cyan}\u2192 Good time to /learn and capture session insights${a.reset}`);let y=[],$=require("path").join(process.cwd(),"NEX.md");if(require("fs").existsSync($)||y.push("Create NEX.md in project root to give nex-code project-specific instructions"),y.length>0){console.log(`
|
|
743
|
-
${a.bold}Quick Wins:${a.reset}`);for(let x of y)console.log(` ${a.cyan}\u2192${a.reset} ${x}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:r,startExecution:i,setPlanMode:c,getPlanContent:l,formatPlan:u}=
|
|
749
|
+
${a.bold}Quick Wins:${a.reset}`);for(let x of y)console.log(` ${a.cyan}\u2192${a.reset} ${x}`)}return console.log(""),!0}case"/plan":{let{getActivePlan:o,approvePlan:r,startExecution:i,setPlanMode:c,getPlanContent:l,formatPlan:u}=It(),{invalidateSystemPromptCache:d}=le(),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(`
|
|
744
750
|
${a.cyan}${a.bold}\u250C\u2500 PLAN MODE \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510${a.reset}
|
|
745
751
|
${a.cyan}${a.bold}\u2502${a.reset} Analysis only \u2014 no file changes until approved ${a.cyan}${a.bold}\u2502${a.reset}
|
|
746
752
|
${a.cyan}${a.bold}\u2502${a.reset} ${a.dim}Read-only tools only \xB7 /plan approve to execute${a.reset} ${a.cyan}${a.bold}\u2502${a.reset}
|
|
747
|
-
${a.cyan}${a.bold}\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518${a.reset}`),f&&console.log(`${a.dim}Task: ${f}${a.reset}`),!0}case"/plans":{let{listPlans:o}=
|
|
748
|
-
${a.bold}${a.cyan}Plans:${a.reset}`);for(let 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}=
|
|
753
|
+
${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}=It(),r=o();if(r.length===0)return console.log(`${a.dim}No saved plans${a.reset}`),!0;console.log(`
|
|
754
|
+
${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}=It(),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}=pn(),r=o();console.log(`
|
|
749
755
|
${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(`
|
|
750
756
|
${a.dim}Use /allow <tool> or /deny <tool> to change${a.reset}
|
|
751
|
-
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=
|
|
757
|
+
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=pn(),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}=pn(),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}=mt(),{confirm:l}=Ne();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}=mt();return o()?(console.log(r()),!0):(console.log(`${a.red}Not a git repository${a.reset}`),!0)}case"/review":{let{isGitRepo:o,getDiff:r}=mt(),{processInput:i}=le(),c=n.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),f=`## Review Protocol
|
|
752
758
|
|
|
753
759
|
**Phase 1 \u2014 Broad Scan:** Read the target code and identify all issues at a high level.
|
|
754
760
|
|
|
@@ -791,16 +797,16 @@ ${f}
|
|
|
791
797
|
|
|
792
798
|
\`\`\`diff
|
|
793
799
|
${g.substring(0,2e4)}
|
|
794
|
-
\`\`\``}return await i(m),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:i}=
|
|
800
|
+
\`\`\``}return await i(m),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:i}=mt();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}=Dn(),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(`
|
|
795
801
|
${a.bold}${a.cyan}MCP Servers:${a.reset}`);for(let u of l){let d=u.connected?`${a.green}\u2713 connected${a.reset}`:`${a.dim}\u25CB disconnected${a.reset}`;console.log(` ${d} ${a.bold}${u.name}${a.reset} (${u.command}) \u2014 ${u.toolCount} tools`)}return console.log(`
|
|
796
802
|
${a.dim}Use /mcp connect to connect all servers${a.reset}
|
|
797
|
-
`),!0}case"/hooks":{let{listHooks:o}=
|
|
798
|
-
${a.bold}${a.cyan}Hooks:${a.reset}`);for(let 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}=
|
|
803
|
+
`),!0}case"/hooks":{let{listHooks:o}=Io(),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(`
|
|
804
|
+
${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}=Yt(),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(`
|
|
799
805
|
${a.bold}${a.cyan}Skills:${a.reset}`);for(let u of l){let d=u.enabled?`${a.green}\u2713${a.reset}`:`${a.red}\u2717${a.reset}`,f=u.type==="prompt"?`${a.dim}(prompt)${a.reset}`:`${a.dim}(script)${a.reset}`,m=[];u.commands>0&&m.push(`${u.commands} cmd`),u.tools>0&&m.push(`${u.tools} tools`);let h=m.length>0?` \u2014 ${m.join(", ")}`:"";console.log(` ${d} ${a.bold}${u.name}${a.reset} ${f}${h}`)}return console.log(`
|
|
800
806
|
${a.dim}Use /skills enable <name> or /skills disable <name>${a.reset}
|
|
801
|
-
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=
|
|
807
|
+
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=Yn();return n.join(" ").trim()==="clear"?(r(),console.log(`${a.green}Tasks cleared${a.reset}`),!0):(console.log(`
|
|
802
808
|
`+o()+`
|
|
803
|
-
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=
|
|
809
|
+
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=Rt(),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}=Rt(),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}=Rt(),c=o(20);if(c.length===0)return console.log(`${a.dim}No file changes in this session${a.reset}`),!0;console.log(`
|
|
804
810
|
${a.bold}File Change History${a.reset}
|
|
805
811
|
`);for(let l of c){let u=new Date(l.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});console.log(` ${a.dim}${u}${a.reset} ${a.yellow}${l.tool}${a.reset} ${l.filePath}`)}return console.log(`
|
|
806
812
|
${a.dim}${r()} undo / ${i()} redo available${a.reset}
|
|
@@ -812,45 +818,45 @@ ${a.bold}${a.cyan}Kubernetes Overview${a.reset}${l?a.dim+" (remote: "+l+")"+a.re
|
|
|
812
818
|
`).filter(Boolean),h=m.filter($=>$.includes("Running")).length,p=m.filter($=>$.includes("Pending")).length,g=m.filter($=>$.includes("Failed")||$.includes("Error")||$.includes("CrashLoop")).length;console.log(`${a.bold}Pods: ${m.length} total ${a.green}${h} running${a.reset} ${a.yellow}${p} pending${a.reset} ${a.red}${g} unhealthy${a.reset}
|
|
813
819
|
`);let y=m.filter($=>!$.includes("Running")&&!$.includes("<none>"));if(y.length>0){console.log(`${a.bold}${a.red}Unhealthy Pods:${a.reset}`);for(let $ of y)console.log(` ${a.red}${$}${a.reset}`);console.log()}console.log(`${a.dim}Use k8s_pods / k8s_logs / k8s_exec tools for details${a.reset}`),console.log(`${a.dim}Or: /k8s user@host to query a remote cluster${a.reset}
|
|
814
820
|
`)}catch(f){console.log(`${a.dim}Could not list pods: ${f.message}${a.reset}
|
|
815
|
-
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:r,sshExec:i}=
|
|
821
|
+
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:r,sshExec:i}=Nt(),c=o(),l=Object.keys(c);if(l.length===0)return console.log(`
|
|
816
822
|
${a.dim}No servers configured. Create .nex/servers.json:${a.reset}`),console.log(`${a.dim} { "prod": { "host": "1.2.3.4", "user": "jarvis", "os": "almalinux9" } }${a.reset}
|
|
817
823
|
`),!0;if(n[0]==="ping"){let f=n[1]?[n[1]]:l;return console.log(`
|
|
818
|
-
${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(f.map(async m=>{if(!c[m]){console.log(` ${a.red}\u2717${a.reset} ${m} \u2014 unknown profile`);return}try{let h={...c[m],_name:m},{exitCode:p}=await 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}=
|
|
824
|
+
${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}=Nt();console.log(`
|
|
819
825
|
${a.bold}${a.cyan}Configured servers (${l.length}):${a.reset}`);for(let f of l)console.log(` ${a.green}${f}${a.reset} ${a.dim}${d(f,c[f])}${a.reset}`);return console.log(`
|
|
820
826
|
${a.dim}/servers ping \u2014 check SSH connectivity for all servers${a.reset}`),console.log(`${a.dim}/servers ping <name> \u2014 check a specific server${a.reset}
|
|
821
|
-
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=
|
|
827
|
+
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=Nt(),{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(`
|
|
822
828
|
${a.bold}${a.cyan}Docker Containers:${a.reset}`);for(let[m,h]of f){let p=m==="local"?`${a.dim}local${a.reset}`:`${a.cyan}${m}${a.reset}`;try{let g;if(m==="local"){let{stdout:y}=await l(u,{timeout:8e3});g=(y||"").trim()}else{let y=await r(h,u,{timeout:1e4});if(g=[y.stdout,y.stderr].filter(Boolean).join("").trim(),y.exitCode!==0){console.log(` ${p}: ${a.red}SSH error (${y.exitCode})${a.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${p}: ${a.dim}(no containers)${a.reset}`):(console.log(` ${p}:`),g.split(`
|
|
823
|
-
`).forEach(y=>console.log(` ${a.dim}${y}${a.reset}`)))}catch(g){console.log(` ${p}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=
|
|
829
|
+
`).forEach(y=>console.log(` ${a.dim}${y}${a.reset}`)))}catch(g){console.log(` ${p}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=no(),r=o(),i=Object.keys(r),c=n[0];if(c&&i.includes(c)){let l=n.includes("--dry-run")||n.includes("-n"),u=r[c],{executeTool:d}=We();console.log(`
|
|
824
830
|
${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(`
|
|
825
831
|
${a.dim}No deploy configs. Run /init to create .nex/deploy.json${a.reset}
|
|
826
832
|
`),!0;console.log(`
|
|
827
833
|
${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(`
|
|
828
834
|
${a.dim}/deploy <name> \u2014 run a named deploy${a.reset}`),console.log(`${a.dim}/deploy <name> --dry-run \u2014 preview without syncing${a.reset}
|
|
829
|
-
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:i}=
|
|
830
|
-
`).filter(Boolean).slice(-
|
|
831
|
-
`)}catch{}}function
|
|
832
|
-
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:
|
|
835
|
+
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:i}=al();return i(e),n[0]==="deploy"?await r():await o(),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:return Rg(t)||console.log(`${a.red}Unknown command: ${s}. Type /help${a.reset}`),!0}}var cr=1e3;function lr(){return qe.join(process.cwd(),".nex","repl_history")}function kl(){try{let t=lr();if(rt.existsSync(t))return rt.readFileSync(t,"utf-8").split(`
|
|
836
|
+
`).filter(Boolean).slice(-cr)}catch{}return[]}function ys(t){try{let e=lr(),s=qe.dirname(e);rt.existsSync(s)||rt.mkdirSync(s,{recursive:!0}),rt.appendFileSync(e,t+`
|
|
837
|
+
`)}catch{}}function ve(){let{isPlanMode:t,getAutonomyLevel:e}=It(),s=[];t()&&s.push("plan");let n=e();n!=="interactive"&&s.push(n);let o=st(),r=ot(),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 ur="\x1B[200~",dr="\x1B[201~";function Mg(t){return typeof t=="string"&&t.includes(ur)}function Pg(t){return typeof t=="string"&&t.includes(dr)}function bn(t){return typeof t!="string"?t:t.split(ur).join("").split(dr).join("")}async function Lg(){if(!Tg("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"),ml("local:llama3"),!0}catch{return!1}}async function Ig(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=le();t(gl);let o=ir().some(N=>N.configured),r=(async()=>{Cg();let N=ot(),j=st();return{model:N,providerName:j}})(),i=(async()=>o?!0:await Lg()?(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}
|
|
838
|
+
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:N}=ul();return await N()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,i,c]);!u&&!o&&(console.error(`
|
|
833
839
|
${a.red}\u2717 No provider configured and no local Ollama detected.${a.reset}
|
|
834
|
-
`),process.exit(1));let f=
|
|
835
|
-
`),await
|
|
836
|
-
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),g=!1,m.setPrompt(
|
|
840
|
+
`),process.exit(1));let f=kl(),m=kg.createInterface({input:process.stdin,output:process.stdout,prompt:ve(),completer:wl,history:f,historySize:cr});Ag(m);let h=new Ng;h.activate(m);let p=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;vg(p,ws,{yolo:hl()}),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}
|
|
841
|
+
`),await pl(ws);let g=!1,y=0,$=!1,x=null;function A(){fl(),h.deactivate(),dl(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)}process.on("SIGTERM",A),process.on("exit",()=>{fl()}),m.on("SIGINT",()=>{if(dl(),g){if(y++,y>=2){A();return}Je&&Je.abort();let{cancelPendingAskUser:N}=We();N(),console.log(`
|
|
842
|
+
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),g=!1,m.setPrompt(ve()),m.prompt();return}$?A():($=!0,process.stdout.write(`
|
|
837
843
|
${a.dim} (Press Ctrl+C again to exit)${a.reset}
|
|
838
|
-
`),m.setPrompt(
|
|
839
|
-
`).replace(/\r/g,"").trim();if(v=[],k=!1,!
|
|
840
|
-
`).length,
|
|
841
|
-
`)),
|
|
842
|
-
`)),!0}if(
|
|
843
|
-
`)),
|
|
844
|
-
`)),!0}return
|
|
845
|
-
\x1B[2K ${a.cyan}${
|
|
846
|
-
\x1B[2K ${a.dim}\u2026 +${
|
|
847
|
-
`)}return}if(
|
|
848
|
-
`).trim();if(
|
|
849
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${
|
|
850
|
-
`).trim();if(
|
|
851
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${
|
|
852
|
-
`).forEach((
|
|
853
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${
|
|
844
|
+
`),m.setPrompt(ve()),m.prompt(),x&&clearTimeout(x),x=setTimeout(()=>{$=!1,x=null},2e3))}),process.on("SIGINT",()=>{process.stdin.isTTY||A()});let k=!1,v=[],T=0,S={},C=!1;function U(){let N=v.join(`
|
|
845
|
+
`).replace(/\r/g,"").trim();if(v=[],k=!1,!N)return!0;T++,C=!0;let j=T;S[j]=N;let W=N.split(`
|
|
846
|
+
`).length,F=W>1?`[Pasted content #${j} \u2014 ${W} lines]`:`[Pasted content #${j}]`,D=m.line||"",Y=D&&!D.endsWith(" ")?" ":"",H=D+Y+F;return m.setPrompt(ve()),m.prompt(),m.line=H,m.cursor=H.length,m._refreshLine(),!0}function I(N){return N.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(j,W)=>S[Number(W)]||"")}function ee(){T=0,S={},C=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let N=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(j,...W){if(j!=="data")return N.call(process.stdin,j,...W);let F=W[0];if(Buffer.isBuffer(F)&&(F=F.toString("utf8")),typeof F!="string")return N.call(process.stdin,j,...W);let D=F.includes(ur),Y=F.includes(dr);if(D&&Y){let H=bn(F);return H&&v.push(...H.split(`
|
|
847
|
+
`)),U()}if(D){k=!0,v=[];let H=bn(F);return H&&v.push(...H.split(`
|
|
848
|
+
`)),!0}if(Y){let H=bn(F);return H&&v.push(...H.split(`
|
|
849
|
+
`)),U()}if(k){let H=bn(F);return H&&v.push(...H.split(`
|
|
850
|
+
`)),!0}return N.call(process.stdin,j,...W)}}let B=0;function de(){if(B>0){let N="";for(let j=0;j<B;j++)N+="\x1B[1B\x1B[2K";N+=`\x1B[${B}A`,process.stdout.write(N),B=0}}function me(N){let j=[...bs,...ar()].filter(G=>G.cmd.startsWith(N));if(!j.length||j.length===1&&j[0].cmd===N)return;let W=10,F=j.slice(0,W),D=Math.max(...F.map(G=>G.cmd.length)),Y="";for(let{cmd:G,desc:$e}of F){let xt=G.substring(0,N.length),it=G.substring(N.length),at=" ".repeat(Math.max(0,D-G.length+2));Y+=`
|
|
851
|
+
\x1B[2K ${a.cyan}${xt}${a.reset}${a.dim}${it}${at}${$e}${a.reset}`}B=F.length,j.length>W&&(Y+=`
|
|
852
|
+
\x1B[2K ${a.dim}\u2026 +${j.length-W} more${a.reset}`,B++);let H=m._prompt.replace(/\x1b\[[0-9;]*m/g,"").length;Y+=`\x1B[${B}A\x1B[${H+m.cursor+1}G`,process.stdout.write(Y)}process.stdin.isTTY&&process.stdin.on("keypress",(N,j)=>{de(),!(j&&(j.name==="tab"||j.name==="return"))&&setImmediate(()=>{m.line&&m.line.startsWith("/")&&me(m.line)})});let J=null,je=`${a.dim}...${a.reset} `;m.setPrompt(ve()),m.prompt(),m.on("line",async N=>{if(de(),Object.keys(S).length>0&&(N=I(N),ee(),m.setPrompt(ve())),g){let D=N.trim();if(D){let{injectMidRunNote:Y}=le();Y(D),process.stdout.write(`${a.cyan} \u270E Wird im n\xE4chsten Schritt ber\xFCcksichtigt${a.reset}
|
|
853
|
+
`)}return}if(J!==null){if(J._mode==="triple"){if(N.trim()==='"""'){let D=J.join(`
|
|
854
|
+
`).trim();if(J=null,D){ys(D.replace(/\n/g,"\\n")),g=!0,y=0,$=!1,x&&(clearTimeout(x),x=null),Je=new AbortController;try{await s(D)}catch(H){if(!Je?.signal?.aborted){let G=H.message?.split(`
|
|
855
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${G}${a.reset}`)}}g=!1;let Y=W();Y>0&&process.stdout.write(`${a.gray}[${Y} messages] ${a.reset}`)}m.setPrompt(ve()),m.prompt();return}J.push(N),m.setPrompt(je),m.prompt();return}if(N.endsWith("\\"))J.push(N.slice(0,-1));else{J.push(N);let D=J.join(`
|
|
856
|
+
`).trim();if(J=null,D){ys(D.replace(/\n/g,"\\n")),g=!0,y=0,$=!1,x&&(clearTimeout(x),x=null),Je=new AbortController;try{await s(D)}catch(G){if(!Je?.signal?.aborted){let $e=G.message?.split(`
|
|
857
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${$e}${a.reset}`)}}let{getConversationLength:Y}=le();g=!1;let H=Y();H>0&&process.stdout.write(`${a.gray}[${H} messages] ${a.reset}`)}m.setPrompt(ve()),m.prompt();return}m.setPrompt(je),m.prompt();return}if(N.trim()==='"""'||N.trim().startsWith('"""')){let D=N.trim().substring(3);J=D?[D]:[],J._mode="triple",m.setPrompt(je),m.prompt();return}if(N.endsWith("\\")){J=[N.slice(0,-1)],J._mode="backslash",m.setPrompt(je),m.prompt();return}let j=N.trim();if(!j){m.setPrompt(ve()),m.prompt();return}if(ys(j),j==="/"){$l(),m.setPrompt(ve()),m.prompt();return}if(j.startsWith("/")){await _l(j,m),m.setPrompt(ve()),m.prompt();return}{let D="\x1B[48;5;237m",Y=process.stdout.columns||80;j.split(`
|
|
858
|
+
`).forEach((G,$e)=>{let xt=$e===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",it=2+G.length,at=" ".repeat(Math.max(0,Y-it));console.log(`${D}${xt} ${G}${at}\x1B[0m`)})}g=!0,y=0,$=!1,x&&(clearTimeout(x),x=null),Je=new AbortController;try{await s(j)}catch(D){if(!Je?.signal?.aborted){let Y=D.message?.split(`
|
|
859
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${Y}${a.reset}`)}}g=!1;let{getConversationLength:W}=le(),F=W();F>0&&process.stdout.write(`${a.gray}[${F} messages] ${a.reset}`),m.setPrompt(ve()),m.prompt()}),m.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}vl.exports={startREPL:Ig,getPrompt:ve,loadHistory:kl,appendHistory:ys,getHistoryPath:lr,HISTORY_MAX:cr,showCommandList:$l,completer:wl,completeFilePath:yl,handleSlashCommand:_l,showProviders:rr,showHelp:bl,renderBar:xl,hasPasteStart:Mg,hasPasteEnd:Pg,stripPasteSequences:bn,getAbortSignal:gl}});var Cl=require("path");require("dotenv").config({path:Cl.join(__dirname,"..",".env")});require("dotenv").config();var re=process.argv.slice(2);(re.includes("--help")||re.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
854
860
|
|
|
855
861
|
Options:
|
|
856
862
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -863,4 +869,4 @@ Options:
|
|
|
863
869
|
--json Output result as JSON (for CI parsing)
|
|
864
870
|
-h, --help Show this help
|
|
865
871
|
-v, --version Show version
|
|
866
|
-
`),process.exit(0));if(
|
|
872
|
+
`),process.exit(0));if(re.includes("-v")||re.includes("--version")){let t=kn();console.log(t.version),process.exit(0)}var qg=re.includes("--yolo")||re.includes("-yolo");if(qg){let{setAutoConfirm:t}=Ne();t(!0)}var fr=re.indexOf("--model");if(fr!==-1&&re[fr+1]){let{setActiveModel:t}=pe();t(re[fr+1])}var mr=re.indexOf("--max-turns");if(mr!==-1&&re[mr+1]){let t=parseInt(re[mr+1],10);if(t>0){let{setMaxIterations:e}=le();e(t)}}else try{let t=require("fs"),e=Cl.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}=le();o(n)}}}catch{}function pr(){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 El(t){if(re.includes("--auto")){let{setAutoConfirm:o}=Ne();o(!0)}if(!re.includes("--model")){let{setActiveModel:o}=pe(),r=process.env.HEADLESS_MODEL||"devstral-small-2:24b";o(r)}let{processInput:s,getConversationMessages:n}=le();s(t).then(()=>{if(re.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=>{re.includes("--json")?console.log(JSON.stringify({success:!1,error:o.message})):console.error(o.message),process.exit(1)})}var Tl=re.indexOf("--prompt-file");if(Tl!==-1){let t=re[Tl+1];(!t||t.startsWith("--"))&&(console.error("--prompt-file requires a file path"),process.exit(1));let e=require("fs"),s;try{s=e.readFileSync(t,"utf-8").trim()}catch(n){console.error(`--prompt-file: cannot read file: ${n.message}`),process.exit(1)}if(s||(console.error("--prompt-file: file is empty"),process.exit(1)),re.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}pr(),El(s)}else{let t=re.indexOf("--task");if(t!==-1){let e=re[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),pr(),El(e)}else{pr();let{startREPL:e}=Sl();e()}}
|