nex-code 0.3.40 → 0.3.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -19
- package/dist/nex-code.js +440 -405
- package/package.json +1 -1
package/dist/nex-code.js
CHANGED
|
@@ -1,144 +1,143 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var L=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var
|
|
3
|
-
`}this.lineCount>0&&(
|
|
4
|
-
`;this.lineCount>0&&(e+=`\x1B[${this.lineCount}A`),process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),
|
|
5
|
-
`}process.stderr.write(n)}},
|
|
6
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=
|
|
7
|
-
`}
|
|
8
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120),
|
|
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
|
|
10
|
-
`;e+=`\x1B[${this.lineCount}A`,process.stderr.write(e),this._render(),this.interval=setInterval(()=>this._render(),120)}updateTask(e,
|
|
11
|
-
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=
|
|
12
|
-
`}process.stderr.write(
|
|
13
|
-
`),n=
|
|
14
|
-
`);return
|
|
15
|
-
${
|
|
16
|
-
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80),c=
|
|
17
|
-
${
|
|
18
|
-
`).filter(Boolean),c=
|
|
19
|
-
`).length;
|
|
2
|
+
var L=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var In=L((j$,uu)=>{uu.exports={name:"nex-code",version:"0.3.42",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 Xr=L((F$,Vr)=>{var M={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",white:"\x1B[37m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",gray:"\x1B[90m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",brightCyan:"\x1B[96m",brightMagenta:"\x1B[95m",brightBlue:"\x1B[94m"},Ks=5,jn=(()=>{let t=[];for(let e=0;e<Ks;e++)t.push(e);for(let e=Ks-2;e>=1;e--)t.push(e);return t})(),Jr=["\u273D","\u2726","\u2727","\u2726"],Ys=class{constructor(e="Thinking..."){this.text=e,this.frame=0,this.interval=null,this.startTime=null}_render(){if(this._stopped)return;let e=jn[this.frame%jn.length],s="";for(let o=0;o<Ks;o++)s+=o===e?`${M.cyan}\u25CF${M.reset}`:" ";let n="";if(this.startTime){let o=Math.floor((Date.now()-this.startTime)/1e3);if(o>=60){let r=Math.floor(o/60),i=o%60;n=` ${M.dim}${r}m ${String(i).padStart(2,"0")}s${M.reset}`}else o>=1&&(n=` ${M.dim}${o}s${M.reset}`)}process.stderr.write(`\x1B[2K\r${s} ${M.dim}${this.text}${M.reset}${n}`),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(),100))}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}},Js=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=jn[this.frame%jn.length],s=`${M.cyan}\u25CF${M.reset}`,n=`${M.dim}\u25CB${M.reset}`,o=this._formatElapsed(),r=o?` ${M.dim}${o}${M.reset}`:"",i="";for(let c=0;c<this.labels.length;c++){let l,u;switch(this.statuses[c]){case"done":l=`${M.green}\u2713${M.reset}`,u=M.dim;break;case"error":l=`${M.red}\u2717${M.reset}`,u=M.dim;break;default:l=c===e?s:" ",u=""}let d=c===this.labels.length-1?r:"";i+=`\x1B[2K ${l} ${u}${this.labels[c]}${M.reset}${d}
|
|
3
|
+
`}this.lineCount>0&&(i+=`\x1B[${this.lineCount}A`),process.stderr.write(i),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(),100)}update(e,s){e>=0&&e<this.statuses.length&&(this.statuses[e]=s)}stop(){this._stopped=!0,this.interval&&(clearInterval(this.interval),this.interval=null),this._renderFinal(),process.stderr.write("\x1B[?25h")}_renderFinal(){let e=this._formatElapsed(),s=e?` ${M.dim}${e}${M.reset}`:"",n="";for(let o=0;o<this.labels.length;o++){let r;switch(this.statuses[o]){case"done":r=`${M.green}\u2713${M.reset}`;break;case"error":r=`${M.red}\u2717${M.reset}`;break;default:r=`${M.yellow}\u25CB${M.reset}`}let i=o===this.labels.length-1?s:"";n+=`\x1B[2K ${r} ${M.dim}${this.labels[o]}${M.reset}${i}
|
|
5
|
+
`}process.stderr.write(n)}},qn={done:"\u2714",in_progress:"\u25FC",pending:"\u25FB",failed:"\u2717"},Dn={done:M.green,in_progress:M.cyan,pending:M.dim,failed:M.red},ut=null,Vs=class{constructor(e,s){this.name=e,this.tasks=s.map(n=>({id:n.id,description:n.description,status:n.status||"pending"})),this.frame=0,this.interval=null,this.startTime=null,this.tokens=0,this.lineCount=1+this.tasks.length,this._paused=!1}_formatElapsed(){if(!this.startTime)return"";let e=Math.floor((Date.now()-this.startTime)/1e3);if(e<1)return"";let s=Math.floor(e/60),n=e%60;return s>0?`${s}m ${String(n).padStart(2,"0")}s`:`${n}s`}_formatTokens(){return this.tokens<=0?"":this.tokens>=1e3?`${(this.tokens/1e3).toFixed(1)}k`:String(this.tokens)}_render(){if(this._stopped)return;let e=Jr[this.frame%Jr.length],s=this._formatElapsed(),n=this._formatTokens(),o=[s,n?`\u2193 ${n} tokens`:""].filter(Boolean).join(" \xB7 "),r=o?` ${M.dim}(${o})${M.reset}`:"",i=`\x1B[2K${M.cyan}${e}${M.reset} ${this.name}\u2026${r}
|
|
6
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=qn[l.status]||qn.pending,p=Dn[l.status]||Dn.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${M.dim}${u}${M.reset} ${p}${d}${M.reset} ${f}
|
|
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),ut=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,ut===this&&(ut=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
|
+
`;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${M.green}\u2714${M.reset} ${this.name} ${M.dim}(${e} \xB7 ${r})${M.reset}
|
|
11
|
+
`;for(let c=0;c<this.tasks.length;c++){let l=this.tasks[c],u=c===0?"\u23BF":" ",d=qn[l.status]||qn.pending,p=Dn[l.status]||Dn.pending,f=l.description.length>55?l.description.substring(0,52)+"...":l.description;i+=`\x1B[2K ${M.dim}${u}${M.reset} ${p}${d}${M.reset} ${M.dim}${f}${M.reset}
|
|
12
|
+
`}process.stderr.write(i)}};function du(t){ut=t}function fu(){return ut}function pu(){ut&&(ut.stop(),ut=null),process.stderr.write("\x1B[?25h\x1B[2K\r")}Vr.exports={C:M,Spinner:Ys,MultiProgress:Js,TaskProgress:Vs,setActiveTaskProgress:du,getActiveTaskProgress:fu,cleanupTerminal:pu}});var ei=L((U$,Zr)=>{var C={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 Qr(t){if(!t)return"";let e=t.replace(/^\.\//,"").split("/");return e.length>1?e.slice(-2).join("/"):e[0]}var mu={read_file:"\x1B[36m",list_directory:"\x1B[36m",write_file:"\x1B[33m",edit_file:"\x1B[33m",patch_file:"\x1B[33m",bash:"\x1B[35m",grep:"\x1B[34m",search_files:"\x1B[34m",glob:"\x1B[34m",git_commit:"\x1B[32m",git_push:"\x1B[32m",git_pull:"\x1B[32m",git_status:"\x1B[32m",git_diff:"\x1B[32m",git_log:"\x1B[32m",git_branch:"\x1B[32m",git_stash:"\x1B[32m",web_fetch:"\x1B[96m",web_search:"\x1B[96m"},Xs={read_file:"Read file",write_file:"Write",edit_file:"Update",patch_file:"Update",list_directory:"List directory",bash:"Run command",grep:"Search code",search_files:"Search files",glob:"Find files",web_fetch:"Fetch URL",web_search:"Web search",git_status:"Git status",git_diff:"Git diff",git_log:"Git log",git_commit:"Git commit",git_push:"Git push",git_pull:"Git pull",git_branch:"Git branch",git_stash:"Git stash",task_list:"Task list",spawn_agents:"Spawn agents",ask_user:"Ask user",switch_model:"Switch model",gh_run_list:"GH Actions",gh_run_view:"GH Actions",gh_workflow_trigger:"GH trigger",browser_open:"Browser open",browser_screenshot:"Screenshot",browser_click:"Browser click",browser_fill:"Browser fill",ssh_exec:"SSH exec",ssh_upload:"SSH upload",ssh_download:"SSH download",service_manage:"Service",service_logs:"Service logs",container_list:"Containers",container_logs:"Container logs",container_exec:"Container exec",brain_write:"Brain write",deploy:"Deploy"};function Fn(t,e=!1,s=null){if(e)return`${C.red}\u25CF${C.reset}`;let n=mu[t]||C.green;return s==="blink"?`${n}\x1B[5m\u25CF\x1B[25m${C.reset}`:`${n}${s!==null?s:"\u25CF"}${C.reset}`}function hu(t,e,s=!1,n=null){let o=(t||[]).filter(l=>l&&l.canExecute!==!1);if(o.length===0)return`${Fn("",s,n)} Step ${e}`;if(o.length===1){let l=o[0],u=l.args||{},d=Xs[l.fnName]||l.fnName.replace(/_/g," "),p="";u.path?p=Qr(u.path):u.command?p=String(u.command).substring(0,60):u.query?p=String(u.query).substring(0,50):u.pattern&&(p=String(u.pattern).substring(0,50));let f=p?`${C.dim}(${p})${C.reset}`:"";return`${Fn(l.fnName,s,n)} ${C.bold}${d}${C.reset} ${f}`}let r=o[0].fnName,i=[...new Set(o.map(l=>Xs[l.fnName]||l.fnName.replace(/_/g," ")))],c=i.length<=3?i.join(" \xB7 "):`${o.length} actions`;return`${Fn(r,s,n)} ${c}`}function gu(t,e){let s;switch(t){case"write_file":case"edit_file":case"patch_file":case"read_file":case"list_directory":s=Qr(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=Xs[t]||t.replace(/_/g," "),o=s?` ${C.dim}(${s})${C.reset}`:"";return`${Fn(t)} ${C.bold}${n}${C.reset}${o}`}function $u(t,e=8){let s=t.split(`
|
|
13
|
+
`),n=s.slice(0,e),o=s.length-e,r=`${C.dim} \u2514 ${C.reset}`,i=" ",c=n.map((l,u)=>`${u===0?r:i}${C.green}${l}${C.reset}`).join(`
|
|
14
|
+
`);return o>0&&(c+=`
|
|
15
|
+
${C.gray} \u2026 +${o} lines${C.reset}`),c}function yu(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 wu(t,e,s,n){let o=String(s||"");if(n){let i=o.split(`
|
|
16
|
+
`)[0].replace(/^ERROR:\s*/i,"").substring(0,80),c=o.match(/\nHINT: (.+)/),l=c?`
|
|
17
|
+
${C.dim}${c[1].substring(0,100)}${C.reset}`:"";return` ${C.red}\u2514 ${i}${C.reset}${l}`}let r;switch(t){case"read_file":{let i=o.split(`
|
|
18
|
+
`).filter(Boolean),c=i.length,l=i[i.length-1],u=l?parseInt(l.match(/^(\d+):/)?.[1]||"0"):0,d=e.line_start||e.line_end,p=(i[0]||"").replace(/^\d+:\s*/,"").trim(),f=p?` ${C.dim}\u2014 ${p.substring(0,60)}${p.length>60?"\u2026":""}${C.reset}`:"";d&&u>c?r=`Read lines ${e.line_start||1}\u2013${u}${f}`:r=`Read ${c} line${c!==1?"s":""}${f}`;break}case"write_file":{let i=(e.content||"").split(`
|
|
19
|
+
`).length;r=`Wrote ${i} line${i!==1?"s":""}`;break}case"edit_file":{let i=(e.old_text||"").split(`
|
|
20
20
|
`),c=(e.new_text||"").split(`
|
|
21
|
-
`),l=
|
|
21
|
+
`),l=i.length,u=c.length,d=3,p=i.slice(0,d).filter(m=>m.trim()),f=c.slice(0,d).filter(m=>m.trim()),h=[];for(let m of p)h.push(`${C.red} - ${C.reset}${C.dim}${m.trimEnd().substring(0,72)}${C.reset}`);i.length>d&&h.push(`${C.dim} \u2026 +${i.length-d}${C.reset}`);for(let m of f)h.push(`${C.green} + ${C.reset}${C.dim}${m.trimEnd().substring(0,72)}${C.reset}`);c.length>d&&h.push(`${C.dim} \u2026 +${c.length-d}${C.reset}`),r=`${C.reset}${C.red}\u2212${l}${C.reset} ${C.green}+${u}${C.reset}`+(h.length>0?`
|
|
22
22
|
`+h.join(`
|
|
23
|
-
`):"");break}case"patch_file":{let
|
|
24
|
-
`).length,0),l=
|
|
25
|
-
`).length,0);
|
|
26
|
-
`).filter(h=>h&&!h.startsWith("EXIT ")&&h.trim()),d=u[0]?` ${
|
|
27
|
-
`).filter(Boolean);
|
|
28
|
-
`).filter(Boolean),c=
|
|
29
|
-
`).filter(Boolean).length;
|
|
30
|
-
`).filter(Boolean).length;
|
|
31
|
-
`).filter(l=>/^\s*[MADRCU?!]/.test(l)).length;i
|
|
32
|
-
`).filter(c=>/^commit\s+[0-9a-f]{7}/.test(c)).length;i
|
|
33
|
-
|
|
34
|
-
`).filter(Boolean).length;
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
`)}
|
|
40
|
-
`);
|
|
41
|
-
`)}},
|
|
42
|
-
`);
|
|
43
|
-
`)
|
|
44
|
-
`)};return s.length>0&&(i.images=s),i}return o})}async chat(e,o,n={}){await this.discoverModels();let s=n.model||this.defaultModel,i=this.getModel(s),r=n.maxTokens||i?.maxTokens||16384,c=await Pn.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:o&&o.length>0?o:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict:r}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),httpAgent:Ln,httpsAgent:In});return this.normalizeResponse(c.data)}async stream(e,o,n={}){await this.discoverModels();let s=n.model||this.defaultModel,i=this.getModel(s),r=n.maxTokens||i?.maxTokens||16384,c=n.onToken||(()=>{}),l=n.onThinkingToken||(()=>{}),u;try{u=await Pn.post(`${this.baseUrl}/api/chat`,{model:s,messages:this._formatMessages(e),tools:o&&o.length>0?o:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict:r}},{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal,httpAgent:Ln,httpsAgent:In})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let f=d.response?.data?.error||d.message;throw new Error(`API Error: ${f}`)}return new Promise((d,f)=>{let m="",h=[],p="";n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),f(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{p+=g.toString();let $=p.split(`
|
|
45
|
-
`);p=$.pop()||"";for(let y of $){if(!y.trim())continue;let x;try{x=JSON.parse(y)}catch{continue}if(x.message?.thinking&&l(x.message.thinking),x.message?.content&&(c(x.message.content),m+=x.message.content),x.message?.tool_calls&&(h=h.concat(x.message.tool_calls)),x.done){d({content:m,tool_calls:this._normalizeToolCalls(h)});return}}}),u.data.on("error",g=>{n.signal?.aborted||f(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{if(p.trim())try{let g=JSON.parse(p);g.message?.thinking&&l(g.message.thinking),g.message?.content&&(c(g.message.content),m+=g.message.content),g.message?.tool_calls&&(h=h.concat(g.message.tool_calls))}catch{}d({content:m,tool_calls:this._normalizeToolCalls(h)})})})}normalizeResponse(e){let o=e.message||{};return{content:o.content||"",tool_calls:this._normalizeToolCalls(o.tool_calls||[])}}_normalizeToolCalls(e){return e.map((o,n)=>({id:o.id||`ollama-${Date.now()}-${n}`,function:{name:o.function?.name||o.name||"unknown",arguments:o.function?.arguments||o.arguments||{}}}))}};Yr.exports={OllamaProvider:Bs,OLLAMA_MODELS:Kr}});var ti=L((c$,ei)=>{var{callChat:Eu}=ge(),{estimateTokens:Hs}=Pe(),Xr=process.env.NEX_COMPACTION!=="false",Vr=6,Qr=500,Tu=`Summarize this conversation history concisely. Focus on:
|
|
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=`${C.reset}${i.length} patch${i.length!==1?"es":""} ${C.red}\u2212${c}${C.reset} ${C.green}+${l}${C.reset}`;break}case"bash":{let i=o.match(/^EXIT (\d+)/);if(i){let c=i[1],l=o.match(/\nHINT: (.+)/);if(l)r=`${c==="0"?`${C.green}\u2713${C.reset}`:`${C.red}\u2717 Exit ${c}${C.reset}`} ${C.dim}\u2014 ${l[1].substring(0,60)}${C.reset}`;else{let u=o.split(`
|
|
26
|
+
`).filter(h=>h&&!h.startsWith("EXIT ")&&h.trim()),d=u[0]?` ${C.dim}\xB7 ${u[0].substring(0,70)}${C.reset}`:"",p=u.length>1?` ${C.dim}+${u.length-1}${C.reset}`:"";r=`${c==="0"?`${C.green}\u2713${C.reset}`:`${C.red}\u2717 Exit ${c}${C.reset}`}${d}${p}`}}else{let c=o.split(`
|
|
27
|
+
`).filter(Boolean);r=c.length>1?`${c[0].substring(0,60)} ${C.dim}+${c.length-1} more${C.reset}`:(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(`
|
|
28
|
+
`).filter(Boolean),c=i.length,u=new Set(i.map(d=>d.split(":")[0]).filter(Boolean)).size;r=u>1?`${c} match${c!==1?"es":""} in ${u} files`:`${c} match${c!==1?"es":""}`}break}case"glob":{if(o==="(no matches)")r="No files found";else{let i=o.split(`
|
|
29
|
+
`).filter(Boolean).length;r=`${i} file${i!==1?"s":""} found`}break}case"list_directory":{let i=o==="(empty)"?0:o.split(`
|
|
30
|
+
`).filter(Boolean).length;r=`${i} entr${i!==1?"ies":"y"}`;break}case"git_status":{let i=o.match(/Branch:\s*(\S+)/),c=o.split(`
|
|
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(`
|
|
32
|
+
`).filter(c=>/^commit\s+[0-9a-f]{7}/.test(c)).length;r=i>0?`${i} commit${i!==1?"s":""}`:"Log retrieved";break}case"git_commit":{let i=o.match(/\[[\w./\-]+ ([0-9a-f]{7,})\]/),c=o.match(/\[[\w./\-]+ [0-9a-f]+\]\s+(.+)/);r=i?`${i[1]}${c?` \u2014 ${c[1].substring(0,55)}`:""}`:"Committed";break}case"git_push":{let i=o.match(/(?:->|→)\s*(\S+)/);r=i?`\u2192 ${i[1]}`:"Pushed";break}case"git_pull":{if(/Already up.to.date/i.test(o))r="Already up to date";else{let i=(o.match(/^\+/gm)||[]).length;r=i>0?`Pulled \xB7 +${i} lines`:"Pulled"}break}case"web_fetch":r="Fetched";break;case"web_search":{let i=o.split(`
|
|
33
|
+
|
|
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` ${C.dim}\u2514 ${r}${C.reset}`}Zr.exports={C,formatToolCall:gu,formatResult:$u,getToolSpinnerText:yu,formatToolSummary:wu,formatSectionHeader:hu}});var de=L((W$,ni)=>{var nn={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"},ti=["01100110","01111110","01111110","01011010","01111110","00111100"];function bu(t){let e="\x1B[38;2;80;200;255m",s=[];for(let n=0;n<t.length;n+=2){let o="";for(let r=0;r<t[0].length;r++){let i=t[n][r]==="1",c=n+1<t.length&&t[n+1][r]==="1";i&&c?o+=`${e}\u2588\x1B[0m`:i&&!c?o+=`${e}\u2580\x1B[0m`:!i&&c?o+=`${e}\u2584\x1B[0m`:o+=" "}s.push(o)}return s}function xu(t,e,s={}){let n=nn.bold,o=nn.dim,r=nn.reset,i="\x1B[38;2;80;200;255m",c=bu(ti),l=s.yolo?` ${n}${nn.yellow}\u26A1 YOLO${r}`:"",u=In().version,d=[` ${i}${n}nex-code${r} ${o}v${u}${r}`,` ${o}${t} \xB7 /help${r}${l}`,""],p=Math.max(c.length,d.length),f=Math.floor((p-c.length)/2),h=Math.floor((p-d.length)/2),m=ti[0].length,g=[];for(let y=0;y<p;y++){let $=c[y-f]??" ".repeat(m),x=d[y-h]??"";g.push($+x)}console.log(`
|
|
35
|
+
`+g.join(`
|
|
36
|
+
`)+`
|
|
37
|
+
`)}var{Spinner:_u,MultiProgress:ku,TaskProgress:vu,setActiveTaskProgress:Su,getActiveTaskProgress:Eu,cleanupTerminal:Tu}=Xr(),{formatToolCall:Ru,formatResult:Cu,getToolSpinnerText:Au,formatToolSummary:Ou,formatSectionHeader:Nu}=ei();ni.exports={C:nn,banner:xu,Spinner:_u,MultiProgress:ku,TaskProgress:vu,setActiveTaskProgress:Su,getActiveTaskProgress:Eu,cleanupTerminal:Tu,formatToolCall:Ru,formatResult:Cu,getToolSpinnerText:Au,formatToolSummary:Ou,formatSectionHeader:Nu}});var We=L((B$,ai)=>{var Mu=require("readline"),{C:Ue}=de(),si=[/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/],Qs=[/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 oi(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)):Qs.some(l=>l.test(r))}return/^\w+=\$?\(/.test(i)||/^\w+=["']/.test(i)||/^\w+=\S/.test(i)?!0:Qs.some(c=>c.test(i))};return n.every(o)}var Zs=[/rm\s+-rf\s/,/docker\s+system\s+prune/,/kubectl\s+delete/,/sudo\s/],ri=[/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/],ii=[...Zs,...ri],eo=!1,xt=null;function Pu(t){eo=t}function Lu(){return eo}function Iu(t){xt=t}function qu(t){for(let e of si)if(e.test(t))return e;return null}function Du(t){if(/ssh\s/.test(t)&&oi(t))return!1;for(let e of ii)if(e.test(t))return!0;return!1}function ju(t){for(let e of Zs)if(e.test(t))return!0;return!1}function Fu(t,e={}){if(eo)return Promise.resolve(!0);if(!process.stdout.isTTY||!process.stdin.isTTY)return Uu(t,e);let s=e.toolName?["Yes","No","Always allow"]:["Yes","No"];return new Promise(n=>{let o=0,r=!1;xt&&xt.pause();let i=()=>{r&&process.stdout.write(`\x1B[${s.length+1}A`),r=!0,process.stdout.write(`\r\x1B[K${Ue.yellow}${t}${Ue.reset}
|
|
38
|
+
`);for(let d=0;d<s.length;d++){let p=d===o,f=p?`${Ue.yellow}\u276F${Ue.reset}`:" ",h=p?`${Ue.yellow}${s[d]}${Ue.reset}`:s[d];process.stdout.write(`\r\x1B[K ${f} ${h}
|
|
39
|
+
`)}},c=d=>{process.stdin.setRawMode(!1),process.stdin.pause(),process.stdin.removeListener("data",u),process.stdout.write(`\x1B[${s.length+1}A`);for(let p=0;p<s.length+1;p++)process.stdout.write(`\r\x1B[K
|
|
40
|
+
`);process.stdout.write(`\x1B[${s.length+1}A`),xt&&xt.resume(),n(d)},l=d=>{if(d===1){c(!1);return}d===2&&e.toolName&&Un(e.toolName),c(!0)},u=d=>{if(d[0]===3){c(!1);return}let p=d.toString();if(p==="\r"||p===`
|
|
41
|
+
`){l(o);return}if(p==="\x1B[A"){o=(o-1+s.length)%s.length,i();return}if(p==="\x1B[B"){o=(o+1)%s.length,i();return}let f=p.toLowerCase().trim();if(f==="y"){c(!0);return}if(f==="n"){c(!1);return}if(f==="a"&&e.toolName){Un(e.toolName),c(!0);return}};i(),process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on("data",u)})}function Uu(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?(Un(e.toolName),n(!0)):n(i!=="n")};if(xt)xt.question(`${Ue.yellow}${t} ${s}${Ue.reset}`,o);else{let r=Mu.createInterface({input:process.stdin,output:process.stdout});r.question(`${Ue.yellow}${t} ${s}${Ue.reset}`,i=>{r.close(),o(i)})}})}var Un=()=>{};function Wu(t){Un=t}ai.exports={FORBIDDEN_PATTERNS:si,SSH_SAFE_PATTERNS:Qs,isSSHReadOnly:oi,DANGEROUS_BASH:ii,CRITICAL_BASH:Zs,NOTABLE_BASH:ri,isForbidden:qu,isDangerous:Du,isCritical:ju,confirm:Fu,setAutoConfirm:Pu,getAutoConfirm:Lu,setReadlineInterface:Iu,setAllowAlwaysHandler:Wu}});var Dt=L((H$,ci)=>{var to=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`)}};ci.exports={BaseProvider:to}});var di=L((G$,ui)=>{var Wn=require("axios"),Bu=require("http"),Hu=require("https"),{BaseProvider:Gu}=Dt(),Bn=new Bu.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),Hn=new Hu.Agent({keepAlive:!0,maxSockets:6,timeout:6e4}),li={"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}},no=class extends Gu{constructor(e={}){super({name:"ollama",baseUrl:e.baseUrl||"https://ollama.com",models:e.models||li,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){Wn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Bn,httpsAgent:Hn}).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 Wn.get(`${this.baseUrl}/api/tags`,{timeout:5e3,headers:this._getHeaders(),httpAgent:Bn,httpsAgent:Hn})).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(`
|
|
42
|
+
`)};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 Wn.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:Bn,httpsAgent:Hn});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=n.onThinkingToken||(()=>{}),u;try{u=await Wn.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:Bn,httpsAgent:Hn})}catch(d){if(d.name==="CanceledError"||d.name==="AbortError"||d.code==="ERR_CANCELED")throw d;let p=d.response?.data?.error||d.message;throw new Error(`API Error: ${p}`)}return new Promise((d,p)=>{let f="",h=[],m="";n.signal&&n.signal.addEventListener("abort",()=>{u.data.destroy(),p(new DOMException("The operation was aborted","AbortError"))},{once:!0}),u.data.on("data",g=>{m+=g.toString();let y=m.split(`
|
|
43
|
+
`);m=y.pop()||"";for(let $ of y){if(!$.trim())continue;let x;try{x=JSON.parse($)}catch{continue}if(x.message?.thinking&&l(x.message.thinking),x.message?.content&&(c(x.message.content),f+=x.message.content),x.message?.tool_calls&&(h=h.concat(x.message.tool_calls)),x.done){d({content:f,tool_calls:this._normalizeToolCalls(h)});return}}}),u.data.on("error",g=>{n.signal?.aborted||p(new Error(`Stream error: ${g.message}`))}),u.data.on("end",()=>{if(m.trim())try{let g=JSON.parse(m);g.message?.thinking&&l(g.message.thinking),g.message?.content&&(c(g.message.content),f+=g.message.content),g.message?.tool_calls&&(h=h.concat(g.message.tool_calls))}catch{}d({content:f,tool_calls:this._normalizeToolCalls(h)})})})}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||{}}}))}};ui.exports={OllamaProvider:no,OLLAMA_MODELS:li}});var $i=L((z$,gi)=>{var{callChat:zu}=ge(),{estimateTokens:so}=De(),fi=process.env.NEX_COMPACTION!=="false",pi=6,mi=500,Ku=`Summarize this conversation history concisely. Focus on:
|
|
46
44
|
- What files were read, created, or modified
|
|
47
45
|
- Key decisions made and their rationale
|
|
48
46
|
- Current state of the task (what's done, what's pending)
|
|
49
47
|
- Any errors encountered and how they were resolved
|
|
50
|
-
Be factual and brief. Use bullet points. Max 300 words.`;async function
|
|
51
|
-
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:
|
|
52
|
-
tools: ${
|
|
48
|
+
Be factual and brief. Use bullet points. Max 300 words.`;async function Yu(t){if(!fi||t.length<pi)return null;let e=[{role:"system",content:Ku},{role:"user",content:hi(t)}];try{let n=((await zu(e,[],{temperature:0,maxTokens:mi})).content||"").trim();if(!n)return null;let o=t.reduce((i,c)=>i+so(c.content||"")+(c.tool_calls?so(JSON.stringify(c.tool_calls)):0),0),r=so(n);return r>=o*.8?null:{message:{role:"system",content:`[Conversation Summary \u2014 ${t.length} messages compacted]
|
|
49
|
+
${n}`,_compacted:!0,_originalCount:t.length},tokensRemoved:o-r}}catch{return null}}function hi(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}
|
|
50
|
+
tools: ${o}`}return`[${s}] ${n}`}).join(`
|
|
53
51
|
|
|
54
|
-
`)}
|
|
55
|
-
`);if(
|
|
52
|
+
`)}gi.exports={compactMessages:Yu,formatMessagesForSummary:hi,COMPACTION_ENABLED:fi,COMPACTION_MIN_MESSAGES:pi,COMPACTION_SUMMARY_BUDGET:mi}});var De=L((K$,vi)=>{function wi(){return ge().getActiveModel()}var Ju={anthropic:3.5,openai:4,gemini:4,ollama:4,local:4},sn=new Map,yi=1e3,oo=new WeakMap,on=null;function Vu(){if(on!==null)return on;try{let e=wi()?.provider||"ollama";return on=Ju[e]||4,on}catch{return 4}}function Xu(){on=null}function kt(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=sn.get(e);if(s!==void 0)return s;let n=Math.ceil(t.length/Vu());if(sn.size>=yi){let o=yi>>1,r=sn.keys();for(let i=0;i<o;i++)sn.delete(r.next().value)}return sn.set(e,n),n}function Qu(t){if(oo.has(t))return oo.get(t);let e=JSON.stringify(t);return oo.set(t,e),e}function jt(t){let s=4;if(t.content&&(s+=kt(t.content)),t.tool_calls)for(let n of t.tool_calls){s+=4,s+=kt(n.function?.name||"");let o=n.function?.arguments;typeof o=="string"?s+=kt(o):o&&(s+=kt(JSON.stringify(o)))}return s}function je(t){let e=0;for(let s of t)e+=jt(s);return e}function Zu(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+=jt(e[r]);return o}function Gn(t){return!t||t.length===0?0:kt(JSON.stringify(t))}function zn(){return wi()?.contextWindow||32768}function ed(t,e){let s=je(t),n=Gn(e),o=s+n,r=zn(),i=r>0?o/r*100:0,c=0,l=0,u=0;for(let d of t){let p=jt(d);d.role==="system"?c+=p:d.role==="tool"?u+=p:l+=p}return{used:o,limit:r,percentage:Math.round(i*10)/10,breakdown:{system:c,conversation:l,toolResults:u,toolDefinitions:n},messageCount:t.length}}var bi=.75,xi=.1,_i=10,td=200,nd=500;function ki(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(`
|
|
53
|
+
`);if(o.length<=10){let m=Math.floor(n*.6),g=Math.floor(n*.4),y=t.substring(0,m),$=t.substring(t.length-g);return y+`
|
|
56
54
|
...(${t.length} chars total)...
|
|
57
|
-
|
|
55
|
+
`+$}let r=Math.floor(o.length*.4),i=Math.floor(o.length*.4),c=[],l=0,u=Math.floor(n*.4);for(let m=0;m<r&&l<u;m++)if(l+o[m].length+1>u&&o[m].trim().startsWith("```")){c.push(o[m]),l+=o[m].length+1;let g=m+1;for(;g<o.length&&l<u*1.5&&!o[g].trim().startsWith("```");)c.push(o[g]),l+=o[g].length+1,g++;g<o.length&&o[g].trim().startsWith("```")&&(c.push(o[g]),l+=o[g].length+1),m=g}else c.push(o[m]),l+=o[m].length+1;let d=[],p=0,f=Math.floor(n*.4);for(let m=o.length-1;m>=o.length-i&&p<f;m--)if(p+o[m].length+1>f&&o[m].trim().startsWith("```")){d.push(o[m]),p+=o[m].length+1;let g=m-1;for(;g>=0&&p<f*1.5&&!o[g].trim().startsWith("```");)d.push(o[g]),p+=o[g].length+1,g--;g>=0&&o[g].trim().startsWith("```")&&(d.push(o[g]),p+=o[g].length+1),m=g}else d.push(o[m]),p+=o[m].length+1;d.reverse();let h=o.length-c.length-d.length;return c.join(`
|
|
58
56
|
`)+`
|
|
59
|
-
...(${h} lines omitted, ${
|
|
57
|
+
...(${h} lines omitted, ${o.length} total)...
|
|
60
58
|
`+d.join(`
|
|
61
|
-
`)}function
|
|
62
|
-
...(truncated)`),
|
|
63
|
-
`),
|
|
64
|
-
`:"")+h,l++}let u="",d=0;for(let h=
|
|
65
|
-
`:"")+u;if(
|
|
66
|
-
|
|
67
|
-
... (${
|
|
68
|
-
|
|
69
|
-
`;return c+
|
|
70
|
-
`);g
|
|
71
|
-
|
|
72
|
-
`:"")+
|
|
73
|
-
`);
|
|
74
|
-
`);g
|
|
75
|
-
`)};return
|
|
76
|
-
`);
|
|
77
|
-
`)}}function
|
|
78
|
-
`)}function
|
|
79
|
-
`),c}catch(c){throw
|
|
59
|
+
`)}function rn(t,e="light"){let s=e==="aggressive"?100:e==="medium"?200:nd,n=e==="aggressive"?50:e==="medium"?100:td;if(t.role==="tool"){let o=typeof t.content=="string"?t.content:JSON.stringify(t.content);return o.length>n?{...t,content:ki(o,n)}:t}if(t.role==="assistant"){let o={...t};return o.content&&o.content.length>s&&(o.content=o.content.substring(0,s)+`
|
|
60
|
+
...(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 sd(t,e,s={}){let n=s.threshold??bi,o=s.safetyMargin??xi,r=s.keepRecent??_i,i=zn(),c=Gn(e),l=Math.floor(i*(n-o)),u=l-c,d=je(t),p=d+c;if(p<=l)return{messages:t,compressed:!1,compacted:!1,tokensRemoved:0};let f=d,h=null,m=0;t.length>0&&t[0].role==="system"&&(h=t[0],m=1);let g=Math.max(m,t.length-r),y=t.slice(m,g),$=t.slice(g),x=y.filter(A=>!A._compacted);if(x.length>=6)try{let{compactMessages:A}=$i(),E=await A(x);if(E){let j=[...y.filter(te=>te._compacted),E.message],Z=_t(h,j,$),G=je(Z);if(G+c<=l)return{messages:Z,compressed:!0,compacted:!0,tokensRemoved:f-G};y=j}}catch(A){process.env.NEX_DEBUG&&console.error("[context-engine] LLM compacting failed:",A.message)}let S=(p-l)/l,k=y.map(A=>rn(A,"light")),v=_t(h,k,$),T=je(v);if(T+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:f-T};if(k=y.map(A=>rn(A,"medium")),v=_t(h,k,$),T=je(v),T+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:f-T};if(k=y.map(A=>rn(A,"aggressive")),v=_t(h,k,$),T=je(v),T+c<=l)return{messages:v,compressed:!0,compacted:!1,tokensRemoved:f-T};for(;k.length>0&&T>u;){let A=k.shift();T-=jt(A)}return v=_t(h,k,$),T=je(v),{messages:v,compressed:!0,compacted:!1,tokensRemoved:f-T}}function _t(t,e,s){let n=[];return t&&n.push(t),n.push(...e,...s),n}function od(t,e){if(!t)return"";if(kt(t)<=e)return t;let n=e*4,o=t.split(`
|
|
61
|
+
`),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?`
|
|
62
|
+
`:"")+h,l++}let u="",d=0;for(let h=o.length-1;h>=l;h--){let m=o[h]+(u?`
|
|
63
|
+
`:"")+u;if(m.length>i)break;u=m,d++}let f=`
|
|
64
|
+
|
|
65
|
+
... (${o.length-l-d} lines omitted, ${o.length} total) ...
|
|
66
|
+
|
|
67
|
+
`;return c+f+u}var rd=6;function id(t,e){let s=zn(),n=Gn(e),o=Math.floor(s*.5)-n,r=je(t),i=null,c=0;t.length>0&&t[0].role==="system"&&(i=t[0],c=1);let l=Math.max(c,t.length-rd),u=t.slice(c,l),d=t.slice(l),p=u.map(m=>rn(m,"aggressive")),f=_t(i,p,d),h=je(f);for(;p.length>0&&h>o;){let m=p.shift();h-=jt(m)}return f=_t(i,p,d),h=je(f),{messages:f,tokensRemoved:r-h}}vi.exports={estimateTokens:kt,estimateMessageTokens:jt,estimateMessagesTokens:je,estimateDeltaTokens:Zu,estimateToolsTokens:Gn,serializeMessage:Qu,getContextWindow:zn,getUsage:ed,compressMessage:rn,compressToolResult:ki,fitToContext:sd,forceCompress:id,truncateFileContent:od,invalidateTokenRatioCache:Xu,COMPRESSION_THRESHOLD:bi,SAFETY_MARGIN:xi,KEEP_RECENT:_i}});var Ri=L((J$,Ti)=>{var Si=require("axios"),{BaseProvider:ad}=Dt(),{serializeMessage:Y$}=De(),Ei={"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}},ro=class extends ad{constructor(e={}){super({name:"openai",baseUrl:e.baseUrl||"https://api.openai.com/v1",models:e.models||Ei,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 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||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 Si.post(`${this.baseUrl}/chat/completions`,u,{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 f=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${f}`)}return new Promise((p,f)=>{let h="",m={},g="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),f(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let $=g.split(`
|
|
68
|
+
`);g=$.pop()||"";for(let x of $){let S=x.trim();if(!S||!S.startsWith("data: "))continue;let k=S.slice(6);if(k==="[DONE]"){p({content:h,tool_calls:this._buildToolCalls(m)});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 A of T.tool_calls){let E=A.index??0;m[E]||(m[E]={id:A.id||"",name:"",arguments:""}),A.id&&(m[E].id=A.id),A.function?.name&&(m[E].name+=A.function.name),A.function?.arguments&&(m[E].arguments+=A.function.arguments)}}}),d.data.on("error",y=>{n.signal?.aborted||f(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{p({content:h,tool_calls:this._buildToolCalls(m)})})})}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}}))}};Ti.exports={OpenAIProvider:ro,OPENAI_MODELS:Ei}});var Ni=L((X$,Oi)=>{var Ci=require("axios"),{BaseProvider:cd}=Dt(),{serializeMessage:V$}=De(),Ai={"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}},ld="2023-06-01",io=class extends cd{constructor(e={}){super({name:"anthropic",baseUrl:e.baseUrl||"https://api.anthropic.com/v1",models:e.models||Ai,defaultModel:e.defaultModel||"claude-sonnet",...e}),this.timeout=e.timeout||18e4,this.temperature=e.temperature??.2,this.apiVersion=e.apiVersion||ld}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?`
|
|
69
|
+
|
|
70
|
+
`:"")+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 p=this.formatTools(s);p.length>0&&(d.tools=p);let f=await Ci.post(`${this.baseUrl}/messages`,d,{timeout:n.timeout||this.timeout,headers:this._getHeaders()});return this.normalizeResponse(f.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),p={model:r,messages:u,max_tokens:c,temperature:n.temperature??this.temperature,stream:!0};d&&(p.system=d);let f=this.formatTools(s);f.length>0&&(p.tools=f);let h;try{h=await Ci.post(`${this.baseUrl}/messages`,p,{timeout:n.timeout||this.timeout,headers:this._getHeaders(),responseType:"stream",signal:n.signal})}catch(m){if(m.name==="CanceledError"||m.name==="AbortError"||m.code==="ERR_CANCELED")throw m;let g=m.response?.data?.error?.message||m.message;throw new Error(`API Error: ${g}`)}return new Promise((m,g)=>{let y="",$=[],x=-1,S="";n.signal&&n.signal.addEventListener("abort",()=>{h.data.destroy(),g(new DOMException("The operation was aborted","AbortError"))},{once:!0}),h.data.on("data",k=>{S+=k.toString();let v=S.split(`
|
|
71
|
+
`);S=v.pop()||"";for(let T of v){let A=T.trim();if(A.startsWith("data: ")){let E=A.slice(6),F;try{F=JSON.parse(E)}catch{continue}switch(F.type){case"content_block_start":{let j=F.content_block;j?.type==="tool_use"&&(x=$.length,$.push({id:j.id,name:j.name,inputJson:""}));break}case"content_block_delta":{let j=F.delta;j?.type==="text_delta"&&j.text&&(l(j.text),y+=j.text),j?.type==="input_json_delta"&&j.partial_json!==void 0&&x>=0&&($[x].inputJson+=j.partial_json);break}case"content_block_stop":x=-1;break;case"message_stop":m({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",()=>{m({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}}})}};Oi.exports={AnthropicProvider:io,ANTHROPIC_MODELS:Ai}});var Ii=L((Z$,Li)=>{var Mi=require("axios"),{BaseProvider:ud}=Dt(),{serializeMessage:Q$}=De(),Pi={"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}},ao=class extends ud{constructor(e={}){super({name:"gemini",baseUrl:e.baseUrl||"https://generativelanguage.googleapis.com/v1beta/openai",models:e.models||Pi,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 Mi.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 Mi.post(`${this.baseUrl}/chat/completions`,u,{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 f=p.response?.data?.error?.message||p.message;throw new Error(`API Error: ${f}`)}return new Promise((p,f)=>{let h="",m={},g="";n.signal&&n.signal.addEventListener("abort",()=>{d.data.destroy(),f(new DOMException("The operation was aborted","AbortError"))},{once:!0}),d.data.on("data",y=>{g+=y.toString();let $=g.split(`
|
|
72
|
+
`);g=$.pop()||"";for(let x of $){let S=x.trim();if(!S||!S.startsWith("data: "))continue;let k=S.slice(6);if(k==="[DONE]"){p({content:h,tool_calls:this._buildToolCalls(m)});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 A of T.tool_calls){let E=A.index??0;m[E]||(m[E]={id:A.id||"",name:"",arguments:""}),A.id&&(m[E].id=A.id),A.function?.name&&(m[E].name+=A.function.name),A.function?.arguments&&(m[E].arguments+=A.function.arguments)}}}),d.data.on("error",y=>{n.signal?.aborted||f(new Error(`Stream error: ${y.message}`))}),d.data.on("end",()=>{p({content:h,tool_calls:this._buildToolCalls(m)})})})}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}}))}};Li.exports={GeminiProvider:ao,GEMINI_MODELS:Pi}});var ji=L((ey,Di)=>{var Kn=require("axios"),{BaseProvider:dd}=Dt(),qi="http://localhost:11434",co=class extends dd{constructor(e={}){super({name:"local",baseUrl:e.baseUrl||process.env.OLLAMA_HOST||process.env.OLLAMA_LOCAL_URL||qi,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 Kn.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 Kn.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(`
|
|
73
|
+
`)};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 Kn.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!1,options:{temperature:n.temperature??this.temperature,num_predict: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 Kn.post(`${this.baseUrl}/api/chat`,{model:o,messages:this._formatMessages(e),tools:s&&s.length>0?s:void 0,stream:!0,options:{temperature:n.temperature??this.temperature,num_predict: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=[],p="";n.signal&&n.signal.addEventListener("abort",()=>{i.data.destroy(),l(new DOMException("The operation was aborted","AbortError"))},{once:!0}),i.data.on("data",f=>{p+=f.toString();let h=p.split(`
|
|
74
|
+
`);p=h.pop()||"";for(let m of h){if(!m.trim())continue;let g;try{g=JSON.parse(m)}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",f=>{n.signal?.aborted||l(new Error(`Stream error: ${f.message}`))}),i.data.on("end",()=>{if(p.trim())try{let f=JSON.parse(p);f.message?.content&&(r(f.message.content),u+=f.message.content),f.message?.tool_calls&&(d=d.concat(f.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||{}}}))}};Di.exports={LocalProvider:co,DEFAULT_LOCAL_URL:qi}});var Ft=L((ty,zi)=>{var vt=require("fs"),lo=require("path"),Fi={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:{}},Yn=[],dt={};function fd(t,e,s,n){if(Yn.push({provider:t,model:e,input:s,output:n}),dt[t]!==void 0){let o=Hi(t);o.allowed||process.stderr.write(`\x1B[33m\u26A0 Budget limit reached for ${t}: $${o.spent.toFixed(2)} / $${o.limit.toFixed(2)}\x1B[0m
|
|
75
|
+
`)}}function uo(t,e){let s=Fi[t];return s?s[e]||{input:0,output:0}:{input:0,output:0}}function Ui(t){let e=uo(t.provider,t.model);return(t.input*e.input+t.output*e.output)/1e6}function Wi(){let t={};for(let r of Yn){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:Ui(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 pd(){let{totalCost:t,totalInput:e,totalOutput:s,breakdown:n}=Wi();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(`
|
|
76
|
+
`)}function md(t,e,s,n){let o=uo(t,e),r=(s*o.input+n*o.output)/1e6;return r<=0?"":`[~$${r.toFixed(4)}]`}function hd(){Yn=[]}function gd(t,e){dt[t]=e}function $d(t){delete dt[t]}function yd(){return{...dt}}function Bi(t){let e=0;for(let s of Yn)s.provider===t&&(e+=Ui(s));return e}function Hi(t){let e=Bi(t),s=dt[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 Gi(){let t=lo.join(process.cwd(),".nex","config.json");if(vt.existsSync(t))try{let e=JSON.parse(vt.readFileSync(t,"utf-8"));e.costLimits&&typeof e.costLimits=="object"&&(dt={...e.costLimits})}catch{}}function wd(){let t=lo.join(process.cwd(),".nex"),e=lo.join(t,"config.json"),s={};if(vt.existsSync(e))try{s=JSON.parse(vt.readFileSync(e,"utf-8"))}catch{s={}}s.costLimits=dt,vt.existsSync(t)||vt.mkdirSync(t,{recursive:!0}),vt.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function bd(){dt={}}Gi();zi.exports={PRICING:Fi,trackUsage:fd,getSessionCosts:Wi,formatCosts:pd,formatCostHint:md,resetCosts:hd,getPricing:uo,setCostLimit:gd,removeCostLimit:$d,getCostLimits:yd,getProviderSpend:Bi,checkBudget:Hi,loadCostLimits:Gi,saveCostLimits:wd,resetCostLimits:bd}});var Jn=L((ny,Ki)=>{var an=ge(),xd={"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 _d(){return an.getActiveModel()}function kd(t){return an.setActiveModel(t)}function vd(){return an.getModelNames()}function Sd(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 Ed(t,e){let{C:s}=de(),{Spinner:n}=de(),o=new n("Thinking...");o.start();let r=!0,i="";try{let c=await an.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}
|
|
77
|
+
`),c}catch(c){throw o.stop(),c}}async function Td(t,e){return an.callChat(t,e)}Ki.exports={MODELS:xd,getActiveModel:_d,setActiveModel:kd,getModelNames:vd,callOllamaStream:Ed,callOllama:Td,parseToolArgs:Sd}});var Vi=L((sy,Ji)=>{var Vn=require("path"),{C:_}=de(),{confirm:Rd,getAutoConfirm:Cd}=We(),Yi=2e3;function cn(t,e){let s=t.split(`
|
|
80
78
|
`),n=e.split(`
|
|
81
|
-
`),
|
|
82
|
-
${_.bold}${_.cyan} Diff: ${t}${_.reset}`);let
|
|
83
|
-
${_.bold}${_.cyan} File exists \u2014 showing changes: ${t}${_.reset}`);let n=
|
|
84
|
-
${_.bold}${_.cyan} New file: ${t}${_.reset}`);let
|
|
85
|
-
`),n=
|
|
86
|
-
${_.bold}${_.cyan} Side-by-side: ${t}${_.reset}`),console.log(` ${_.dim}${"\u2500".repeat(
|
|
87
|
-
`)}function
|
|
88
|
-
${_.cyan}\u23FA${_.reset} ${_.bold}${
|
|
89
|
-
`);return}let h=[];if(
|
|
90
|
-
`),
|
|
91
|
-
${_.cyan}\u23FA${_.reset} ${_.bold}Create(${n})${_.reset}`);let
|
|
92
|
-
`).filter(Boolean).map(e=>{let
|
|
93
|
-
`);for(let
|
|
94
|
-
${
|
|
95
|
-
${
|
|
96
|
-
${
|
|
79
|
+
`),o=[],r=s.length,i=n.length;if(r>Yi||i>Yi){for(let p of s)o.push({type:"remove",line:p});for(let p of n)o.push({type:"add",line:p});return o}let c=Array.from({length:r+1},()=>new Array(i+1).fill(0));for(let p=1;p<=r;p++)for(let f=1;f<=i;f++)s[p-1]===n[f-1]?c[p][f]=c[p-1][f-1]+1:c[p][f]=Math.max(c[p-1][f],c[p][f-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 Ad(t,e,s,n=3){console.log(`
|
|
80
|
+
${_.bold}${_.cyan} Diff: ${t}${_.reset}`);let o=cn(e,s),r=[];if(o.forEach((l,u)=>{l.type!=="same"&&r.push(u)}),r.length===0){console.log(`${_.gray} (no changes)${_.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(`${_.gray} ...${_.reset}`);for(let l=i;l<c;l++){let u=o[l];switch(u.type){case"remove":console.log(`${_.red} - ${u.line}${_.reset}`);break;case"add":console.log(`${_.green} + ${u.line}${_.reset}`);break;default:console.log(`${_.gray} ${u.line}${_.reset}`)}}c<o.length&&console.log(`${_.gray} ...${_.reset}`),console.log()}function Od(t,e,s){console.log(`
|
|
81
|
+
${_.bold}${_.cyan} File exists \u2014 showing changes: ${t}${_.reset}`);let n=cn(e,s),o=0;for(let i of n)i.type!=="same"&&o++;if(o===0){console.log(`${_.gray} (identical content)${_.reset}`);return}let r=0;for(let i of n){if(r>=30){console.log(`${_.gray} ...(${o-r} more changes)${_.reset}`);break}switch(i.type){case"remove":console.log(`${_.red} - ${i.line}${_.reset}`),r++;break;case"add":console.log(`${_.green} + ${i.line}${_.reset}`),r++;break;default:r>0&&console.log(`${_.gray} ${i.line}${_.reset}`)}}console.log()}function Nd(t,e){console.log(`
|
|
82
|
+
${_.bold}${_.cyan} New file: ${t}${_.reset}`);let s=e.split(`
|
|
83
|
+
`),n=s.slice(0,20);for(let o of n)console.log(`${_.green} + ${o}${_.reset}`);s.length>20&&console.log(`${_.gray} ...+${s.length-20} more lines${_.reset}`),console.log()}async function Md(t){return Cd()?!0:Rd(` ${t}?`)}function Pd(t,e,s,n){let o=n||process.stdout.columns||80,r=Math.floor((o-3)/2);console.log(`
|
|
84
|
+
${_.bold}${_.cyan} Side-by-side: ${t}${_.reset}`),console.log(` ${_.dim}${"\u2500".repeat(r)}\u252C${"\u2500".repeat(r)}${_.reset}`);let i=cn(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 m=[];for(;l<i.length&&i[l].type==="add";)m.push(i[l].line),l++;let g=Math.max(h.length,m.length);for(let y=0;y<g;y++)c.push({left:y<h.length?h[y]:"",right:y<m.length?m[y]:"",type:"changed"})}else i[l].type==="add"&&(c.push({left:"",right:i[l].line,type:"changed"}),l++);let u=c.map((h,m)=>h.type!=="same"?m:-1).filter(h=>h>=0);if(u.length===0){console.log(` ${_.gray}(no changes)${_.reset}`);return}let d=Math.max(0,u[0]-2),p=Math.min(c.length,u[u.length-1]+3),f=(h,m)=>{let g=h.replace(/\x1b\[[0-9;]*m/g,"");return g.length>=m?h.substring(0,m):h+" ".repeat(m-g.length)};d>0&&console.log(` ${_.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${_.reset}`);for(let h=d;h<p;h++){let m=c[h];if(m.type==="same")console.log(` ${_.gray}${f(m.left,r)}${_.reset}\u2502${_.gray}${f(m.right,r)}${_.reset}`);else{let g=m.left?`${_.red}${f(m.left,r)}${_.reset}`:`${f("",r)}`,y=m.right?`${_.green}${f(m.right,r)}${_.reset}`:`${f("",r)}`;console.log(` ${g}\u2502${y}`)}}p<c.length&&console.log(` ${_.dim}${"\xB7".repeat(r)}\u250A${"\xB7".repeat(r)}${_.reset}`),console.log(` ${_.dim}${"\u2500".repeat(r)}\u2534${"\u2500".repeat(r)}${_.reset}
|
|
85
|
+
`)}function Ld(t,e,s,n={}){let o=n.label||"Update",r=n.context||3,i=n.annotations||[],c=Vn.isAbsolute(t)?Vn.relative(process.cwd(),t):t,l=cn(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 p=0,f=0;for(let k of l)k.type==="add"?p++:k.type==="remove"&&f++;if(console.log(`
|
|
86
|
+
${_.cyan}\u23FA${_.reset} ${_.bold}${o}(${c})${_.reset}`),p===0&&f===0){console.log(` ${_.dim}\u23BF (no changes)${_.reset}
|
|
87
|
+
`);return}let h=[];if(p>0&&h.push(`Added ${p} line${p!==1?"s":""}`),f>0&&h.push(`removed ${f} line${f!==1?"s":""}`),i.length>0){let k=i.filter(E=>E.severity==="error").length,v=i.filter(E=>E.severity==="warn").length,T=i.filter(E=>E.severity==="info").length,A=[];k>0&&A.push(`${_.red}${k} error${k!==1?"s":""}${_.dim}`),v>0&&A.push(`${_.yellow}${v} warning${v!==1?"s":""}${_.dim}`),T>0&&A.push(`${_.cyan}${T} info${T!==1?"s":""}${_.dim}`),h.push(`found ${A.join(", ")}`)}console.log(` ${_.dim}\u23BF ${h.join(", ")}${_.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 S=" ";for(let k=0;k<y.length;k++){k>0&&console.log(`${S}${_.dim}\xB7\xB7\xB7${_.reset}`);let[v,T]=y[k];for(let A=v;A<=T;A++){let E=l[A],F=E.newLine!=null?E.newLine:E.oldLine,j=String(F).padStart(4),Z=E.type!=="remove"?i.filter(G=>G.line===E.newLine):[];E.type==="remove"?console.log(`${S}${_.red}${j} -${E.line}${_.reset}`):E.type==="add"?console.log(`${S}${_.green}${j} +${E.line}${_.reset}`):console.log(`${S}${_.dim}${j}${_.reset} ${E.line}`);for(let G of Z){let te=_.cyan,me="\u2139";G.severity==="error"?(te=_.red,me="\u2716"):G.severity==="warn"&&(te=_.yellow,me="\u26A0"),console.log(`${S} ${te}${me} ${G.message}${_.reset}`)}}}console.log()}function Id(t,e,s={}){let n=Vn.isAbsolute(t)?Vn.relative(process.cwd(),t):t,o=e.split(`
|
|
88
|
+
`),r=s.annotations||[];console.log(`
|
|
89
|
+
${_.cyan}\u23FA${_.reset} ${_.bold}Create(${n})${_.reset}`);let i=[`${o.length} line${o.length!==1?"s":""}`];if(r.length>0){let d=r.filter(m=>m.severity==="error").length,p=r.filter(m=>m.severity==="warn").length,f=r.filter(m=>m.severity==="info").length,h=[];d>0&&h.push(`${_.red}${d} error${d!==1?"s":""}${_.dim}`),p>0&&h.push(`${_.yellow}${p} warning${p!==1?"s":""}${_.dim}`),f>0&&h.push(`${_.cyan}${f} info${f!==1?"s":""}${_.dim}`),i.push(`found ${h.join(", ")}`)}console.log(` ${_.dim}\u23BF ${i.join(", ")}${_.reset}`);let l=" ",u=Math.min(o.length,20);for(let d=0;d<u;d++){let p=String(d+1).padStart(4),f=d+1,h=r.filter(m=>m.line===f);console.log(`${l}${_.green}${p} +${o[d]}${_.reset}`);for(let m of h){let g=_.cyan,y="\u2139";m.severity==="error"?(g=_.red,y="\u2716"):m.severity==="warn"&&(g=_.yellow,y="\u26A0"),console.log(`${l} ${g}${y} ${m.message}${_.reset}`)}}o.length>20&&console.log(`${l}${_.dim} ...+${o.length-20} more lines${_.reset}`),console.log()}Ji.exports={diffLines:cn,showEditDiff:Ad,showWriteDiff:Od,showNewFilePreview:Nd,confirmFileChange:Md,showSideBySideDiff:Pd,showClaudeDiff:Ld,showClaudeNewFile:Id}});var St=L((oy,Zi)=>{var Xi=require("util").promisify(require("child_process").exec),qd=require("util").promisify(require("child_process").execFile),{C:ie}=de();async function fo(t){try{let{stdout:e}=await Xi(t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Xn(...t){try{let{stdout:e}=await qd("git",t,{cwd:process.cwd(),timeout:3e4});return e.trim()}catch{return null}}async function Dd(){return await fo("git rev-parse --is-inside-work-tree")==="true"}async function jd(){return await fo("git branch --show-current")}async function po(){try{let{stdout:t}=await Xi("git status --porcelain",{cwd:process.cwd(),timeout:3e4});return!t||!t.trim()?[]:t.split(`
|
|
90
|
+
`).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 fo(`git diff ${t?"--cached":""}`)||""}async function mo(){return(await po()).map(e=>e.file)}async function Qi(){let t=await mo();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(`
|
|
91
|
+
`);for(let p of d)p.startsWith("+")&&!p.startsWith("+++")&&o++,p.startsWith("-")&&!p.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 Fd(t){let s=`feat/${t.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").substring(0,50)}`;return await Xn("checkout","-b",s)!==null?s:null}async function Ud(t){return await Xn("add","-A"),await Xn("commit","-m",t)?await Xn("rev-parse","--short","HEAD"):null}async function Wd(){let t=await Qi();if(!t)return`${ie.dim}No changes${ie.reset}`;let e=[];e.push(`
|
|
92
|
+
${ie.bold}${ie.cyan}Git Diff Summary:${ie.reset}`),e.push(` ${ie.green}+${t.stats.additions}${ie.reset} ${ie.red}-${t.stats.deletions}${ie.reset} in ${t.files.length} file(s)`),e.push(`
|
|
93
|
+
${ie.bold}${ie.cyan}Files:${ie.reset}`);for(let s of t.files.slice(0,20))e.push(` ${ie.dim}${s}${ie.reset}`);return t.files.length>20&&e.push(` ${ie.dim}...+${t.files.length-20} more${ie.reset}`),e.push(`
|
|
94
|
+
${ie.bold}${ie.cyan}Suggested message:${ie.reset}`),e.push(` ${ie.cyan}${t.summary}${ie.reset}
|
|
97
95
|
`),e.join(`
|
|
98
|
-
`)}async function
|
|
99
|
-
...(truncated)`:
|
|
96
|
+
`)}async function Bd(){return(await po()).filter(e=>e.status==="UU"||e.status==="AA"||e.status==="DD")}async function Hd(){let t=await mo();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)+`
|
|
97
|
+
...(truncated)`:s;e.push(`
|
|
100
98
|
DIFF:
|
|
101
99
|
${n}`)}return e.join(`
|
|
102
|
-
`)}
|
|
100
|
+
`)}Zi.exports={isGitRepo:Dd,getCurrentBranch:jd,getStatus:po,getDiff:Qn,getChangedFiles:mo,analyzeDiff:Qi,createBranch:Fd,commit:Ud,formatDiffSummary:Wd,getDiffContext:Hd,getMergeConflicts:Bd}});var ft=L((ry,ta)=>{var ho=require("fs").promises,{execSync:ln}=require("child_process"),Gd=50,Ze=[],Ut=[];function zd(t,e,s,n){for(Ze.push({tool:t,filePath:e,oldContent:s,newContent:n,timestamp:Date.now()});Ze.length>Gd;)Ze.shift();Ut.length=0}async function Kd(){if(Ze.length===0)return null;let t=Ze.pop();if(t.oldContent===null)try{await ho.unlink(t.filePath)}catch{}else await ho.writeFile(t.filePath,t.oldContent,"utf-8");return Ut.push(t),{tool:t.tool,filePath:t.filePath,wasCreated:t.oldContent===null}}async function Yd(){if(Ut.length===0)return null;let t=Ut.pop();return await ho.writeFile(t.filePath,t.newContent,"utf-8"),Ze.push(t),{tool:t.tool,filePath:t.filePath}}function Jd(t=10){return Ze.slice(-t).reverse().map(e=>({tool:e.tool,filePath:e.filePath,timestamp:e.timestamp}))}function Vd(){return Ze.length}function Xd(){return Ut.length}function Qd(){Ze.length=0,Ut.length=0}var Zn="nex-snapshot";function Zd(t,e=process.cwd()){let s=t?`${Zn}-${t.replace(/[^a-zA-Z0-9_-]/g,"-")}`:`${Zn}-${Date.now()}`;try{return ln("git status --porcelain",{cwd:e,timeout:1e4}).toString().trim()?(ln(`git stash push -u -m "${s}"`,{cwd:e,timeout:15e3}),ln("git stash pop",{cwd:e,timeout:1e4}),{name:s,label:s,ok:!0}):{name:s,label:s,ok:!1,error:"No changes to snapshot (working tree clean)"}}catch(n){return{name:s,label:s,ok:!1,error:n.message}}}function ea(t=process.cwd()){try{let e=ln("git stash list",{cwd:t,timeout:1e4}).toString().trim();return e?e.split(`
|
|
101
|
+
`).map(s=>{let n=s.match(/^stash@\{(\d+)\}:\s+(?:WIP on [^:]+:\s+\S+\s+|On \S+:\s+)(.*)/);if(!n)return null;let o=n[2].trim();return o.startsWith(Zn)?{index:parseInt(n[1],10),label:o,shortName:o.replace(`${Zn}-`,""),date:s}:null}).filter(Boolean):[]}catch{return[]}}function ef(t,e=process.cwd()){try{let s=ea(e);if(s.length===0)return{ok:!1,error:"No snapshots found"};let n;return t===void 0||t==="last"?n=s[0]:typeof t=="number"?n=s.find(o=>o.index===t):n=s.find(o=>o.label===t||o.shortName===t||o.shortName.includes(String(t))),n?(ln(`git stash apply stash@{${n.index}}`,{cwd:e,timeout:15e3}),{ok:!0,label:n.label}):{ok:!1,error:`Snapshot not found: ${t}`}}catch(s){return{ok:!1,error:s.message}}}ta.exports={recordChange:zd,undo:Kd,redo:Yd,getHistory:Jd,getUndoCount:Vd,getRedoCount:Xd,clearHistory:Qd,createSnapshot:Zd,listSnapshots:ea,restoreSnapshot:ef}});var un=L((iy,aa)=>{var Ce=require("fs"),Wt=require("path"),ve=[];function go(){return Wt.join(process.cwd(),".nex","skills")}function na(){return Wt.join(process.cwd(),".nex","config.json")}function tf(){let t=go();return Ce.existsSync(t)||Ce.mkdirSync(t,{recursive:!0}),t}function $o(){let t=na();if(!Ce.existsSync(t))return[];try{let e=JSON.parse(Ce.readFileSync(t,"utf-8"));return e.skills&&Array.isArray(e.skills.disabled)?e.skills.disabled:[]}catch{return[]}}function sa(t){let e=na(),s={};if(Ce.existsSync(e))try{s=JSON.parse(Ce.readFileSync(e,"utf-8"))}catch{s={}}s.skills||(s.skills={}),s.skills.disabled=t;let n=Wt.dirname(e);Ce.existsSync(n)||Ce.mkdirSync(n,{recursive:!0}),Ce.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function oa(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 ra(t){try{let e=Ce.readFileSync(t,"utf-8").trim();return e?{name:Wt.basename(t,".md"),type:"prompt",filePath:t,instructions:e,commands:[],tools:[]}:null}catch{return null}}function ia(t){try{let e=require(t),{valid:s,errors:n}=oa(e,t);return s?{name:e.name||Wt.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}
|
|
103
102
|
${n.join(`
|
|
104
|
-
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function
|
|
103
|
+
`)}`),null)}catch(e){return console.error(`Failed to load skill: ${t}: ${e.message}`),null}}function nf(){ve=[];let t=go();if(!Ce.existsSync(t))return ve;let e=$o(),s;try{s=Ce.readdirSync(t)}catch{return ve}for(let n of s){let o=Wt.join(t,n),r;try{r=Ce.statSync(o)}catch{continue}if(!r.isFile())continue;let i=null;n.endsWith(".md")?i=ra(o):n.endsWith(".js")&&(i=ia(o)),i&&(i.enabled=!e.includes(i.name),ve.push(i))}return ve}function sf(){let t=[];for(let e of ve)!e.enabled||!e.instructions||t.push(`[Skill: ${e.name}]
|
|
105
104
|
${e.instructions}`);return t.length===0?"":`SKILL INSTRUCTIONS:
|
|
106
105
|
${t.join(`
|
|
107
106
|
|
|
108
|
-
`)}`}function
|
|
109
|
-
`,l="",u=setTimeout(()=>{
|
|
110
|
-
`);for(let
|
|
111
|
-
`):JSON.stringify(
|
|
112
|
-
Available tools: ${d.join(", ")}`}}if(!
|
|
113
|
-
`+
|
|
107
|
+
`)}`}function of(){let t=[];for(let e of ve)if(e.enabled)for(let s of e.commands)t.push({cmd:s.cmd,desc:s.desc||`[skill: ${e.name}]`});return t}function rf(){let t=[];for(let e of ve)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 af(t,e){if(!t.startsWith("skill_"))return null;let s=t.substring(6);for(let n of ve)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 cf(t){let[e,...s]=t.split(/\s+/),n=s.join(" ").trim();for(let o of ve)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 lf(){return ve.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 uf(t){let e=ve.find(n=>n.name===t);if(!e)return!1;e.enabled=!0;let s=$o().filter(n=>n!==t);return sa(s),!0}function df(t){let e=ve.find(n=>n.name===t);if(!e)return!1;e.enabled=!1;let s=$o();return s.includes(t)||(s.push(t),sa(s)),!0}function ff(){return ve}aa.exports={initSkillsDir:tf,loadAllSkills:nf,getSkillInstructions:sf,getSkillCommands:of,getSkillToolDefinitions:rf,routeSkillCall:af,handleSkillCommand:cf,listSkills:lf,enableSkill:uf,disableSkill:df,getLoadedSkills:ff,_getSkillsDir:go,_validateScriptSkill:oa,_loadMarkdownSkill:ra,_loadScriptSkill:ia}});var ts=L((ay,pa)=>{var{spawn:pf}=require("child_process"),mf=require("path"),ca=require("fs"),et=new Map;function hf(){return mf.join(process.cwd(),".nex","config.json")}function yo(){let t=hf();if(!ca.existsSync(t))return{};try{return JSON.parse(ca.readFileSync(t,"utf-8")).mcpServers||{}}catch{return{}}}function es(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})+`
|
|
108
|
+
`,l="",u=setTimeout(()=>{p(),r(new Error(`MCP request timeout: ${e}`))},n);function d(f){l+=f.toString();let h=l.split(`
|
|
109
|
+
`);for(let m of h)if(m.trim())try{let g=JSON.parse(m);if(g.id===i){p(),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 p(){clearTimeout(u),t.stdout.removeListener("data",d)}t.stdout.on("data",d);try{t.stdin.write(c)}catch(f){p(),r(new Error(`MCP write failed: ${f.message}`))}})}async function la(t,e){if(et.has(t))return et.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=pf(e.command,e.args||[],{stdio:["pipe","pipe","pipe"],env:{...n,...e.env||{}}}),r={name:t,proc:o,tools:[],config:e};try{await es(o,"initialize",{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"nex-code",version:"0.2.0"}});let i=await es(o,"tools/list",{});return r.tools=i&&i.tools||[],et.set(t,r),r}catch(i){throw o.kill(),new Error(`Failed to connect MCP server '${t}': ${i.message}`)}}function ua(t){let e=et.get(t);if(!e)return!1;try{e.proc.kill()}catch{}return et.delete(t),!0}function gf(){for(let[t]of et)ua(t)}async function da(t,e,s={}){let n=et.get(t);if(!n)throw new Error(`MCP server not connected: ${t}`);let o=await es(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(`
|
|
110
|
+
`):JSON.stringify(o)}function fa(){let t=[];for(let[e,s]of et)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 $f(){return fa().map(t=>({type:"function",function:{name:`mcp_${t.server}_${t.name}`,description:`[MCP:${t.server}] ${t.description}`,parameters:t.inputSchema}}))}async function yf(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 da(n,o,e)}function wf(){let t=yo();return Object.entries(t).map(([e,s])=>{let n=et.get(e);return{name:e,command:s.command,connected:!!n,toolCount:n?n.tools.length:0}})}async function bf(){let t=yo(),e=[];for(let[s,n]of Object.entries(t))try{let o=await la(s,n);e.push({name:s,tools:o.tools.length})}catch(o){e.push({name:s,tools:0,error:o.message})}return e}pa.exports={loadMCPConfig:yo,sendRequest:es,connectServer:la,disconnectServer:ua,disconnectAll:gf,callTool:da,getAllTools:fa,getMCPToolDefinitions:$f,routeMCPCall:yf,listServers:wf,connectAll:bf}});var wo=L((cy,$a)=>{var{getSkillToolDefinitions:xf}=un(),{getMCPToolDefinitions:_f}=ts(),ns=new Map;function ma(){let{TOOL_DEFINITIONS:t}=Be();return[...t,...xf(),..._f()]}function ha(t){if(ns.has(t))return ns.get(t);let s=ma().find(o=>o.function.name===t);if(!s)return null;let n=s.function.parameters;return ns.set(t,n),n}function kf(){ns.clear()}function ss(t,e){if(!t||e.length===0)return null;let s=null,n=1/0;for(let o of e){let r=ga(t.toLowerCase(),o.toLowerCase());r<n&&(n=r,s=o)}return n<=Math.ceil(t.length/2)?s:null}function ga(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 vf(t,e){let s=ha(t);if(s===null){let d=ma().map(f=>f.function.name),p=ss(t,d);return{valid:!1,error:`Unknown tool "${t}".${p?` Did you mean "${p}"?`:""}
|
|
111
|
+
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=ss(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=ss(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,p=typeof c[u];d==="string"&&p==="number"?(c[u]=String(c[u]),l=!0):d==="number"&&p==="string"&&!isNaN(c[u])?(c[u]=Number(c[u]),l=!0):d==="boolean"&&p==="string"&&(c[u]=c[u]==="true",l=!0)}return i.length>0&&!l?{valid:!1,error:`Tool "${t}" argument errors:
|
|
112
|
+
`+i.map(u=>` - ${u}`).join(`
|
|
114
113
|
`)+`
|
|
115
114
|
|
|
116
|
-
Expected parameters: ${JSON.stringify(
|
|
115
|
+
Expected parameters: ${JSON.stringify(s.properties,null,2)}`}:{valid:!0,corrected:l?c:null}}$a.exports={validateToolArgs:vf,closestMatch:ss,levenshtein:ga,getCachedSchema:ha,clearSchemaCache:kf}});var xa=L((ly,ba)=>{var{levenshtein:os}=wo(),Sf=200,Ef=.3,Tf=2;function bo(t){return t.replace(/\r\n/g,`
|
|
117
116
|
`).replace(/\r/g,`
|
|
118
|
-
`).replace(/\t/g," ".repeat(
|
|
119
|
-
`).map(e=>{let
|
|
120
|
-
`)}function
|
|
121
|
-
`),
|
|
122
|
-
`),
|
|
123
|
-
`),c=
|
|
124
|
-
`)}if(
|
|
125
|
-
`),
|
|
126
|
-
`).length;return
|
|
127
|
-
`),u=
|
|
128
|
-
`),h=
|
|
129
|
-
`),n=[],
|
|
130
|
-
`).filter(Boolean),
|
|
131
|
-
HINT: Connection refused on ${e.host}:${
|
|
132
|
-
HINT: Auth failed using ${
|
|
117
|
+
`).replace(/\t/g," ".repeat(Tf)).split(`
|
|
118
|
+
`).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(`
|
|
119
|
+
`)}function Rf(t,e){if(t.includes(e))return e;if(e.length<10)return null;let s=bo(t),n=bo(e);if(!s.includes(n))return null;let o=t.split(`
|
|
120
|
+
`),r=s.split(`
|
|
121
|
+
`),i=n.split(`
|
|
122
|
+
`),c=i[0],l=i[i.length-1];for(let u=0;u<=r.length-i.length;u++){let d=!0;for(let p=0;p<i.length;p++)if(r[u+p]!==i[p]){d=!1;break}if(d)return o.slice(u,u+i.length).join(`
|
|
123
|
+
`)}if(i.length===1){for(let u=0;u<r.length;u++)if(r[u].indexOf(n)!==-1)return o[u]}return null}function Cf(t,e){if(!t||!e)return null;let s=t.split(`
|
|
124
|
+
`),o=e.split(`
|
|
125
|
+
`).length;return s.length===0||o===0?null:o===1?Af(s,e):Nf(s,e,o)}function ya(t){return Math.max(1,Math.floor(t/Sf))}function wa(t,e){return t<=Math.ceil(e*Ef)}function Af(t,e){let s=e.trim(),n=ya(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=os(c.trim(),s);l<r&&(r=l,o={text:c,distance:l,line:i+1})}return o&&n>1&&(o=Of(t,s,o,n)||o,r=o.distance),wa(r,e.length)?o:null}function Of(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 p=os(d.trim(),e);p<c&&(c=p,l={text:d,distance:p,line:u+1})}return l}function Nf(t,e,s){let n=t.length-s+1;if(n<=0)return null;let o=ya(n),r=null,i=1/0;for(let c=0;c<n;c+=o){let l=t.slice(c,c+s).join(`
|
|
126
|
+
`),u=os(l,e);u<i&&(i=u,r={text:l,distance:u,line:c+1})}return r&&o>1&&(r=Mf(t,e,r,o,s,n)||r,i=r.distance),wa(i,e.length)?r:null}function Mf(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 p=c;p<=l;p++){let f=t.slice(p,p+o).join(`
|
|
127
|
+
`),h=os(f,e);h<u&&(u=h,d={text:f,distance:h,line:p+1})}return d}ba.exports={normalizeWhitespace:bo,fuzzyFindText:Rf,findMostSimilar:Cf}});var ka=L((dy,_a)=>{var{C:uy}=de(),Pf=[{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}],Lf=[{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 If(t,e){let s=e.split(`
|
|
128
|
+
`),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 Pf)l.regex.test(i)&&n.push({line:c,message:`Potential secret detected: ${l.name}`,severity:"error"});for(let l of Lf)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}_a.exports={runDiagnostics:If}});var ko=L((fy,Ea)=>{var qf=require("fs").promises,va=require("path"),{exec:Df}=require("util").promisify(require("child_process").exec),Bt=[],_o=null,rs=!1,xo=0,jf=6e4;function Sa(t){return!(Bt.length===0||_o!==t||Date.now()-xo>jf)}async function Ff(t){if(!rs&&!Sa(t)){rs=!0,_o=t;try{try{let{stdout:n}=await Df("rg --files",{cwd:t,timeout:5e3});Bt=n.split(`
|
|
129
|
+
`).filter(Boolean),xo=Date.now(),rs=!1;return}catch{}let e=[],s=async(n,o)=>{let r;try{r=await qf.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(va.join(n,i.name),c):e.push(c)}};await s(t,""),Bt=e,xo=Date.now()}catch(e){console.error(`Index error: ${e.message}`)}finally{rs=!1}}}function Uf(){return Bt}function Wf(){return _o}function Bf(t){return Bt.filter(e=>va.basename(e)===t)}function Hf(t){let e=t.toLowerCase();return Bt.filter(s=>s.toLowerCase().includes(e)).slice(0,20)}Ea.exports={refreshIndex:Ff,getFileIndex:Uf,getIndexedCwd:Wf,findFileInIndex:Bf,searchIndex:Hf,isIndexValid:Sa}});var Ht=L((py,Aa)=>{var is=require("fs"),cs=require("path"),vo=require("os"),{execFile:Gf}=require("child_process"),{promisify:zf}=require("util"),So=zf(Gf),Kf=cs.join(".nex","servers.json"),as=cs.join(vo.tmpdir(),"nex-ssh-sockets");function Yf(){return cs.join(process.cwd(),Kf)}function Ta(){let t=Yf();if(!is.existsSync(t))return{};try{return JSON.parse(is.readFileSync(t,"utf-8"))}catch{return{}}}function Jf(t){let e=Ta();if(e[t])return{...e[t],_name:t};if(/^[\w.-]+@[\w.-]+$/.test(t)||/[\w-]+\.[\w.-]+/.test(t)||t==="localhost"){let[o,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 Vf(){is.existsSync(as)||is.mkdirSync(as,{recursive:!0})}function Ra(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-o","ServerAliveInterval=30"];t.key&&e.push("-i",t.key.replace(/^~/,vo.homedir())),t.port&&Number(t.port)!==22&&e.push("-p",String(t.port)),Vf();let s=t.user?`${t.user}@${t.host}`:t.host,n=cs.join(as,s.replace(/[@.:]/g,"_"));return e.push("-o","ControlMaster=auto","-o",`ControlPath=${n}`,"-o","ControlPersist=120"),e.push(s),{args:e,target:s}}function Ca(t){let e=["-o","BatchMode=yes","-o","ConnectTimeout=15","-o","StrictHostKeyChecking=accept-new","-r"];return t.key&&e.push("-i",t.key.replace(/^~/,vo.homedir())),t.port&&Number(t.port)!==22&&e.push("-P",String(t.port)),e}async function Xf(t,e,{timeout:s=3e4,sudo:n=!1}={}){let{args:o}=Ra(t),r=n&&t.sudo?`sudo sh -c ${JSON.stringify(e)}`:e;try{let{stdout:i,stderr:c}=await So("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:ls(l,t)}}}async function Qf(t,e,s,{timeout:n=12e4}={}){let o=Ca(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(e,`${r}:${s}`);try{let{stdout:i,stderr:c}=await So("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(ls(c,t)||c)}}async function Zf(t,e,s,{timeout:n=12e4}={}){let o=Ca(t),r=t.user?`${t.user}@${t.host}`:t.host;o.push(`${r}:${e}`,s);try{let{stdout:i,stderr:c}=await So("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(ls(c,t)||c)}}function ls(t,e){if(!t)return"";if(/connection refused/i.test(t)){let s=e.port||22;return`${t}
|
|
130
|
+
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}
|
|
131
|
+
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}
|
|
133
132
|
HINT: Cannot reach ${e.host}. Check: network connection, correct hostname/IP, DNS resolution.`:/host key verification failed/i.test(t)?`${t}
|
|
134
133
|
HINT: Host key changed for ${e.host}. To reset: ssh-keygen -R ${e.host}`:/timed out/i.test(t)?`${t}
|
|
135
134
|
HINT: Connection timed out to ${e.host}. Check firewall rules and network connectivity.`:/too many authentication failures/i.test(t)?`${t}
|
|
136
|
-
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function
|
|
137
|
-
`,"utf-8")}
|
|
135
|
+
HINT: Too many auth attempts. Add "-o IdentitiesOnly=yes -i ${e.key||"~/.ssh/id_rsa"}" or clear your SSH agent keys.`:t}function ep(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}`}Aa.exports={loadServerProfiles:Ta,resolveProfile:Jf,buildSSHArgs:Ra,sshExec:Xf,scpUpload:Qf,scpDownload:Zf,enrichSSHError:ls,formatProfile:ep,SSH_SOCKET_DIR:as}});var Ro=L((my,Na)=>{var dn=require("fs"),Eo=require("path"),tp=Eo.join(".nex","deploy.json");function To(){return Eo.join(process.cwd(),tp)}function Oa(){let t=To();if(!dn.existsSync(t))return{};try{return JSON.parse(dn.readFileSync(t,"utf-8"))}catch{return{}}}function np(t){let e=Oa();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 sp(t){let e=Eo.join(process.cwd(),".nex");dn.existsSync(e)||dn.mkdirSync(e,{recursive:!0}),dn.writeFileSync(To(),JSON.stringify(t,null,2)+`
|
|
136
|
+
`,"utf-8")}Na.exports={loadDeployConfigs:Oa,resolveDeployConfig:np,saveDeployConfigs:sp,getDeployConfigPath:To}});var pn=L((hy,La)=>{var Co=null,tt=null,fn=null,Ma=`Playwright is not installed. Install with:
|
|
138
137
|
npm install playwright && npx playwright install chromium
|
|
139
|
-
Then restart nex-code.`;function
|
|
140
|
-
...(truncated)`:""),links:c.slice(0,20)}}finally{await
|
|
141
|
-
`)}function
|
|
138
|
+
Then restart nex-code.`;function Pa(){if(fn!==null)return fn;try{require("playwright"),fn=!0}catch{fn=!1}return fn}async function us(){if(!Pa())throw new Error(Ma);return Co||(Co=require("playwright")),(!tt||!tt.isConnected())&&(tt=await Co.chromium.launch({headless:!0})),tt}async function op(){if(tt){try{await tt.close()}catch{}tt=null}}process.on("exit",()=>{if(tt)try{tt.close()}catch{}});async function rp(t,{timeout:e=3e4,waitFor:s="domcontentloaded"}={}){let o=await(await us()).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?`
|
|
139
|
+
...(truncated)`:""),links:c.slice(0,20)}}finally{await o.close()}}async function ip(t,{width:e=1280,height:s=800,fullPage:n=!1,timeout:o=3e4}={}){let i=await(await us()).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"),p=u.join(l.tmpdir(),`nex-screenshot-${Date.now()}.png`);return d.writeFileSync(p,c),{path:p,base64:c.toString("base64"),media_type:"image/png",title:await i.title(),url:i.url()}}finally{await i.close()}}async function ap(t,{selector:e,text:s,timeout:n=3e4}={}){if(!e&&!s)throw new Error("selector or text is required");let r=await(await us()).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 cp(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 us()).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()}}La.exports={isPlaywrightAvailable:Pa,browserNavigate:rp,browserScreenshot:ip,browserClick:ap,browserFill:cp,closeBrowser:op,INSTALL_MSG:Ma}});var ds=L((gy,Ia)=>{var{C:ne}=de(),hn="",xe=[],mn=0,Et=null;function lp(t){Et=t}function up(t,e){hn=t,xe=[],mn=0;for(let n of e){mn++;let o=`t${mn}`;xe.push({id:o,description:n.description||n.title||n.name||n.task||`Task ${mn}`,status:"pending",dependsOn:n.depends_on||[],result:null})}let s=xe.map(n=>({...n}));return Et&&Et("create",{name:t,tasks:s}),s}function dp(t,e,s){let n=xe.find(o=>o.id===t);return n?(n.status=e,s!==void 0&&(n.result=s),Et&&Et("update",{id:t,status:e,result:s}),{...n}):null}function fp(){return{name:hn,tasks:xe.map(t=>({...t}))}}function pp(){hn="",xe=[],mn=0,Et&&Et("clear",{})}function mp(){return xe.filter(t=>t.status!=="pending"?!1:t.dependsOn.length===0?!0:t.dependsOn.every(e=>{let s=xe.find(n=>n.id===e);return s&&s.status==="done"}))}function hp(){if(xe.length===0)return`${ne.dim}No active tasks${ne.reset}`;let t=[];hn&&(t.push(` ${ne.bold}${ne.cyan}Tasks: ${hn}${ne.reset}`),t.push(` ${ne.dim}${"\u2500".repeat(40)}${ne.reset}`));for(let o of xe){let r,i;switch(o.status){case"done":r="\u2713",i=ne.green;break;case"in_progress":r="\u2192",i=ne.cyan;break;case"failed":r="\u2717",i=ne.red;break;default:r="\xB7",i=ne.dim}let c=o.dependsOn.length>0?` ${ne.dim}(after: ${o.dependsOn.join(", ")})${ne.reset}`:"",l=`[${o.status}]`,u=o.description.length>50?o.description.substring(0,47)+"...":o.description;if(t.push(` ${i}${r}${ne.reset} ${ne.bold}${o.id}${ne.reset} ${u.padEnd(40)} ${i}${l}${ne.reset}${c}`),o.result&&o.status==="done"){let d=o.result.length>60?o.result.substring(0,57)+"...":o.result;t.push(` ${ne.dim}\u2192 ${d}${ne.reset}`)}}let e=xe.filter(o=>o.status==="done").length,s=xe.filter(o=>o.status==="failed").length,n=xe.length;return t.push(` ${ne.dim}${"\u2500".repeat(40)}${ne.reset}`),t.push(` ${ne.dim}${e}/${n} done${s>0?`, ${s} failed`:""}${ne.reset}`),t.join(`
|
|
140
|
+
`)}function gp(){return xe.length>0&&xe.some(t=>t.status==="pending"||t.status==="in_progress")}Ia.exports={createTasks:up,updateTask:dp,getTaskList:fp,clearTasks:pp,getReadyTasks:mp,renderTaskList:hp,setOnChange:lp,hasActiveTasks:gp}});var Oo=L(($y,Da)=>{var{getActiveModel:$p,getActiveProviderName:yp}=ge(),gn={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},$n={"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"},yn={ollama:"full",openai:"full",anthropic:"full",gemini:"full",local:"essential"},He={};function qa(){try{let t=require("fs"),s=require("path").join(process.cwd(),".nex","config.json");t.existsSync(s)&&(He=JSON.parse(t.readFileSync(s,"utf-8")).toolTiers||{})}catch{He={}}}qa();function Ao(){let e=$p()?.id,s=yp();return e&&He[e]?He[e]:s&&He[`${s}:*`]?He[`${s}:*`]:e&&$n[e]?$n[e]:s&&yn[s]?yn[s]:"full"}function wp(t,e){return t&&He[t]?He[t]:e&&He[`${e}:*`]?He[`${e}:*`]:t&&$n[t]?$n[t]:e&&yn[e]?yn[e]:"full"}function bp(t,e){let s=e||Ao();if(s==="full"||!gn[s])return t;let n=new Set(gn[s]);return t.filter(o=>n.has(o.function.name))}function xp(){let t=Ao(),e=gn[t]?gn[t].length:"all";return{tier:t,toolCount:e}}Da.exports={filterToolsForModel:bp,getActiveTier:Ao,getModelTier:wp,getTierInfo:xp,TIERS:gn,MODEL_TIERS:$n,PROVIDER_DEFAULT_TIER:yn,loadConfigOverrides:qa}});var Va=L((wy,Ja)=>{var{callStream:_p,getActiveProviderName:ps,getActiveModelId:kp,getConfiguredProviders:vp,getProvider:ja,getActiveProvider:Fa,parseModelSpec:Ua}=ge(),{parseToolArgs:Sp}=Jn(),{filterToolsForModel:Ep,getModelTier:fs}=Oo(),{trackUsage:Tp}=Ft(),{MultiProgress:Rp,C:yy}=de(),Cp=15,Wa=5,Ba=3,ms=new Map;function Ap(t,e){let s=ms.get(t);return s&&s!==e?!1:(ms.set(t,e),!0)}function wn(t){ms.delete(t)}function No(){ms.clear()}function Ha(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 Ga(t,e,s){let n;for(let o=0;o<=Ba;o++)try{return await _p(t,e,s)}catch(r){if(n=r,o<Ba&&Ha(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 Op=new Set(["ask_user","task_list","spawn_agents"]),Np=new Set(["write_file","edit_file","patch_file"]),Mp=/\b(read|summarize|search|find|list|check|count|inspect|scan)\b/i,Pp=/\b(refactor|rewrite|implement|create|architect|design|generate|migrate)\b/i;function za(t){return Pp.test(t)?"full":Mp.test(t)?"essential":"standard"}function Ka(t){let e=vp(),s=ps(),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(fs(r.id,o.name)===t)return{provider:o.name,model:r.id};return null}var Lp={essential:process.env.NEX_FAST_MODEL||null,standard:process.env.NEX_STANDARD_MODEL||null,full:process.env.NEX_HEAVY_MODEL||null};function Mo(t){if(t.model){let{provider:o,model:r}=Ua(t.model),i=o?ja(o):Fa(),c=o||ps();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=fs(r,c);return{provider:c,model:r,tier:l}}}let e=za(t.task),s=Lp[e];if(s){let{provider:o,model:r}=Ua(s),i=o?ja(o):Fa(),c=o||ps();if(i&&i.isConfigured()&&(i.getModel(r)||c==="local")){let l=fs(r,c);return{provider:c,model:r,tier:l}}}let n=Ka(e);if(n){let o=fs(n.model,n.provider);return{provider:n.provider,model:n.model,tier:o}}return{provider:null,model:null,tier:null}}async function Ya(t,e={}){let s=Math.min(t.max_iterations||10,Cp),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.
|
|
142
141
|
|
|
143
142
|
TASK: ${t.task}
|
|
144
143
|
${t.context?`
|
|
@@ -160,153 +159,155 @@ TOOL STRATEGY:
|
|
|
160
159
|
ERROR RECOVERY:
|
|
161
160
|
- If edit_file fails with "old_text not found": read the file again, compare, and retry with exact text.
|
|
162
161
|
- If bash fails: read the error, fix the root cause, then retry.
|
|
163
|
-
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=
|
|
164
|
-
`)}let
|
|
165
|
-
...(truncated)`:me,tool_call_id:
|
|
166
|
-
`)}catch(
|
|
167
|
-
`);for(let
|
|
168
|
-
`);for(let
|
|
169
|
-
...(truncated)`}let
|
|
170
|
-
${u}`),c+=
|
|
171
|
-
|
|
172
|
-
${
|
|
173
|
-
|
|
174
|
-
`)}`}
|
|
175
|
-
${
|
|
176
|
-
`)}`}}catch{}return{fixedPath:null,message:""}}function
|
|
177
|
-
|
|
178
|
-
`+
|
|
179
|
-
`)}function nc(t,e,o){let n=Oo(t,e);if(!n)return null;let s=Math.max(3,Math.ceil(e.length*.05));return n.distance>s?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(o),distance:n.distance,line:n.line}}var Qa=!1,bt=null;function jm(){bt&&(bt(),bt=null)}var No=null;function Dm(t){No=t}async function Ao(){if(!Qa){Qa=!0;try{let{stdout:t}=await ie("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await ie('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await ie("git stash pop",{cwd:process.cwd(),timeout:1e4}),await ie("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var Fm=[/\.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 ke(t){let e=ve.isAbsolute(t)?ve.resolve(t):ve.resolve(process.cwd(),t);for(let o of Fm)if(o.test(e))return null;return e}var Um=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail. Files are read with UTF-8 encoding. For binary files, use bash with appropriate flags. Alternative: use util.promisify(fs.readFile) for programmatic access.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Use this to find where functions/variables/classes are defined or used. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"deploy",description:'Deploy files to a remote server via rsync + optional remote script. Can use a named config from .nex/deploy.json (e.g. deploy("prod")) or explicit params. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},local_path:{type:"string",description:'Local directory or file to sync (e.g. "dist/", "./build"). Required if no config.'},remote_path:{type:"string",description:'Remote destination path (e.g. "/var/www/app"). Required if no config.'},deploy_script:{type:"string",description:"Shell command to run on the remote after sync. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from sync. Optional."},dry_run:{type:"boolean",description:"Show what would be synced without actually syncing. Default: false."}},required:[]}}}];function gn(t,{server:e,context:o}={}){let n=e?e.replace(/[^a-zA-Z0-9@._-]/g,""):null,s=o?o.replace(/[^a-zA-Z0-9._/-]/g,""):null,i="kubectl";if(s&&(i+=` --context ${s}`),i+=` ${t}`,n){let r=i.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`ssh -o ConnectTimeout=10 -o BatchMode=yes ${n} "${r}"`}return i}async function Za(t,e,o={}){switch(t){case"bash":{let n=e.command,s=vm(n);if(s){let u=qm(n);return`BLOCKED: Command matches forbidden pattern: ${s}${u?`
|
|
180
|
-
HINT: ${u}`:""}`}if(
|
|
181
|
-
${I.yellow}${u}: ${n}${I.reset}`),!await
|
|
182
|
-
${
|
|
183
|
-
`+
|
|
184
|
-
`),d=(e.line_start||1)-1,
|
|
185
|
-
`)}case"write_file":{await
|
|
186
|
-
`+d.message:""}`}let
|
|
187
|
-
Most similar text (line ${
|
|
188
|
-
${
|
|
189
|
-
`)||"(empty)"}case"search_files":{let n=
|
|
190
|
-
`).filter(
|
|
191
|
-
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let
|
|
192
|
-
`);return x?`${
|
|
193
|
-
|
|
194
|
-
\u26A0 Results truncated at 200. Use a more specific pattern.`:
|
|
195
|
-
`).filter(
|
|
196
|
-
`).trim()||"(no matches)"}catch(
|
|
197
|
-
`+
|
|
198
|
-
Most similar text (line ${
|
|
199
|
-
${
|
|
200
|
-
|
|
201
|
-
${
|
|
162
|
+
- After 2 failed attempts at the same operation, summarize the issue and stop.`}];l.push({role:"user",content:t.task});let u=Mo(t),d=u.provider,p=u.model,f=u.tier,{TOOL_DEFINITIONS:h,executeTool:m}=Be(),g=Ep(h.filter($=>!Op.has($.function.name)),f);if(p&&!t._skipLog){let $=f?` (${f})`:"";process.stderr.write(` [sub-agent: ${d}:${p}${$}]
|
|
163
|
+
`)}let y={};d&&(y.provider=d),p&&(y.model=p);try{for(let $=0;$<s;$++){let x=await Ga(l,g,y);if(!x||typeof x!="object")throw new Error("Empty or invalid response from provider");if(x.usage){let E=x.usage.prompt_tokens||0,F=x.usage.completion_tokens||0;r.input+=E,r.output+=F;let j=d||ps(),Z=p||kp();Tp(j,Z,E,F)}let S=x.content||"",k=x.tool_calls,v={role:"assistant",content:S||""};if(k&&k.length>0&&(v.tool_calls=k),l.push(v),!k||k.length===0){for(let E of i)wn(E);return{task:t.task,status:"done",result:S||"(no response)",toolsUsed:o,tokensUsed:r,modelSpec:d&&p?`${d}:${p}`:null}}let T=k.map(E=>{let F=E.function.name,j=Sp(E.function.arguments),Z=E.id||`sub-${Date.now()}-${Math.random().toString(36).slice(2,6)}`;if(!j)return Promise.resolve({role:"tool",content:`ERROR: Malformed tool arguments for ${F}`,tool_call_id:Z});let G=null;if(Np.has(F)&&j.path){let te=require("path"),me=te.isAbsolute(j.path)?j.path:te.resolve(process.cwd(),j.path);if(i.has(me)||!Ap(me,n))return Promise.resolve({role:"tool",content:`ERROR: File '${j.path}' is locked by another operation. Try a different approach or skip this file.`,tool_call_id:Z});i.add(me),G=me}return o.push(F),m(F,j,{autoConfirm:!0,silent:!0}).then(te=>{G&&(wn(G),i.delete(G));let me=String(te??"");return{role:"tool",content:me.length>2e4?me.substring(0,2e4)+`
|
|
164
|
+
...(truncated)`:me,tool_call_id:Z}}).catch(te=>(G&&(wn(G),i.delete(G)),{role:"tool",content:`ERROR: ${te.message}`,tool_call_id:Z}))}),A=await Promise.all(T);l.push(...A),e.onUpdate&&e.onUpdate(`step ${$+1}/${s}`)}for(let $ of i)wn($);return{task:t.task,status:"truncated",abortReason:"iteration_limit",result:l[l.length-1]?.content||"(max iterations reached)",toolsUsed:o,tokensUsed:r,modelSpec:d&&p?`${d}:${p}`:null}}catch($){for(let x of i)wn(x);return{task:t.task,status:"failed",result:`Error: ${$.message}`,toolsUsed:o,tokensUsed:r,modelSpec:d&&p?`${d}:${p}`:null}}}async function Ip(t){let e=t.agents||[];if(e.length===0)return"ERROR: No agents specified";if(e.length>Wa)return`ERROR: Max ${Wa} parallel agents allowed, got ${e.length}`;let s=e.map(r=>Mo(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 Rp(n);o.start();try{let r=e.map((d,p)=>{let f=s[p],h=f.model?{...d,model:`${f.provider}:${f.model}`,_skipLog:!0}:{...d,_skipLog:!0};return Ya(h,{onUpdate:()=>{}}).then(m=>(o.update(p,m.status==="failed"?"error":"done"),m)).catch(m=>(o.update(p,"error"),{task:d.task,status:"failed",result:`Error: ${m.message}`,toolsUsed:[],tokensUsed:{input:0,output:0}}))}),i=await Promise.all(r);o.stop(),No();let c=["Sub-agent results:",""],l=0,u=0;for(let d=0;d<i.length;d++){let p=i[d],f=p.status==="done"?"\u2713":p.status==="truncated"?"\u26A0":"\u2717",h=p.modelSpec?` [${p.modelSpec}]`:"";c.push(`${f} Agent ${d+1}${h}: ${p.task}`),c.push(` Status: ${p.status}`),c.push(` Tools used: ${p.toolsUsed.length>0?p.toolsUsed.join(", "):"none"}`),c.push(` Result: ${p.result}`),c.push(""),l+=p.tokensUsed.input,u+=p.tokensUsed.output}return c.push(`Total sub-agent tokens: ${l} input + ${u} output`),c.join(`
|
|
165
|
+
`)}catch(r){return o.stop(),No(),`ERROR: Sub-agent execution failed: ${r.message}`}}Ja.exports={runSubAgent:Ya,executeSpawnAgents:Ip,clearAllLocks:No,classifyTask:za,pickModelForTier:Ka,resolveSubAgentModel:Mo,isRetryableError:Ha,callWithRetry:Ga}});var _n=L((by,lc)=>{var oe=require("fs"),nt=require("path"),qp=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 Gt(){let t=nt.join(process.cwd(),".nex","brain");return oe.existsSync(t)||oe.mkdirSync(t,{recursive:!0}),t}function Xa(){return nt.join(Gt(),".brain-index.json")}function Io(){return nt.join(Gt(),".embeddings.json")}function bn(){let t=nt.join(process.cwd(),".nex","brain");if(!oe.existsSync(t))return[];try{return oe.readdirSync(t).filter(e=>e.endsWith(".md")&&!e.startsWith(".")).map(e=>{let s=nt.join(t,e),n=oe.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 xn(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(`
|
|
166
|
+
`);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 Qa(t){let e=nt.join(Gt(),`${t}.md`);if(!oe.existsSync(e))return{name:t,content:"",body:"",frontmatter:{}};let s=oe.readFileSync(e,"utf-8"),{frontmatter:n,body:o}=xn(s);return{name:t,content:s,body:o,frontmatter:n}}function Dp(t,e){let s=nt.join(Gt(),`${t}.md`);oe.writeFileSync(s,e,"utf-8"),Up(t,e),jp()}function jp(){if(process.env.NEX_BRAIN_EMBEDDINGS==="false")return;let t=Io();oe.existsSync(t)&&setImmediate(async()=>{try{await rc()}catch{}})}function Fp(t){let e=nt.join(Gt(),`${t}.md`);return oe.existsSync(e)?(oe.unlinkSync(e),Wp(t),!0):!1}function hs(t){return t.toLowerCase().replace(/[^a-z0-9äöüß\s-]/g," ").split(/[\s-]+/).filter(e=>e.length>2&&!qp.has(e))}function qo(t){let e={},{frontmatter:s,body:n}=xn(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(`
|
|
167
|
+
`);for(let i of r)if(i.startsWith("#")){let c=i.replace(/^#+\s*/,"");for(let l of hs(c))e[l]=(e[l]||0)+3}for(let i of hs(n||t))e[i]=(e[i]||0)+1;return e}function Do(){let t=Xa();if(!oe.existsSync(t))return{documents:{}};try{return JSON.parse(oe.readFileSync(t,"utf-8"))}catch{return{documents:{}}}}function jo(t){oe.writeFileSync(Xa(),JSON.stringify(t,null,2),"utf-8")}function Up(t,e){let s=Do(),{frontmatter:n}=xn(e),o=Array.isArray(n.tags)?n.tags:[];s.documents[t]={keywords:qo(e),tags:o,modified:new Date().toISOString()},jo(s)}function Wp(t){let e=Do();delete e.documents[t],jo(e)}function Lo(){let t=bn(),e={documents:{}};for(let s of t){let n=oe.readFileSync(s.path,"utf-8"),{frontmatter:o}=xn(n),r=Array.isArray(o.tags)?o.tags:[];e.documents[s.name]={keywords:qo(n),tags:r,modified:s.modified.toISOString()}}return jo(e),e}function Za(){let t=Do(),e=bn();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 ec(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=hs(t);if(o.length===0)return[];let r=Za(),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[p,f]of Object.entries(l.keywords))p!==d&&p.length>3&&d.length>3&&(p.includes(d)||d.includes(p))&&(u+=f*.3)}u>=n&&i.push({name:c,score:u})}return i.sort((c,l)=>l.score-c.score),i.slice(0,s)}var tc=process.env.NEX_EMBED_MODEL||"nomic-embed-text",Po=400,Bp=50;async function nc(){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 p="";d.on("data",f=>p+=f),d.on("end",()=>{try{c(JSON.parse(p))}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(tc.split(":")[0]))}catch{return!1}}async function Fo(t){let e=process.env.OLLAMA_HOST||"http://localhost:11434",s=require("http"),n=require("https"),o=new URL(`${e}/api/embeddings`),r=o.protocol==="https:"?n:s,i=JSON.stringify({model:tc,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 p="";d.on("data",f=>p+=f),d.on("end",()=>{try{c(JSON.parse(p).embedding||[])}catch(f){l(f)}})});u.on("error",l),u.on("timeout",()=>{u.destroy(),l(new Error("embedding timeout"))}),u.write(i),u.end()})}function sc(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 oc(t){let e=t.split(/\s+/),s=[],n=0;for(;n<e.length;){let o=e.slice(n,n+Po).join(" ");if(s.push({text:o,offset:n}),n+Po>=e.length)break;n+=Po-Bp}return s}async function rc(){let t=bn(),e={documents:{}},s=Io();if(oe.existsSync(s))try{e=JSON.parse(oe.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=oe.readFileSync(n.path,"utf-8"),i=oc(r),c=[];for(let l of i){let u=await Fo(l.text);c.push({text:l.text,embedding:u,offset:l.offset})}e.documents[n.name]={chunks:c,modified:n.modified.toISOString()}}for(let n of Object.keys(e.documents))t.some(o=>o.name===n)||delete e.documents[n];return oe.writeFileSync(s,JSON.stringify(e),"utf-8"),e}async function ic(t,e={}){let{topK:s=3,minSimilarity:n=.3}=e,o=Io();if(!oe.existsSync(o))return[];let r;try{r=JSON.parse(oe.readFileSync(o,"utf-8"))}catch{return[]}let i=await Fo(t),c=[];for(let[l,u]of Object.entries(r.documents||{})){let d=0,p="";for(let f of u.chunks||[]){let h=sc(i,f.embedding);h>d&&(d=h,p=f.text)}d>=n&&c.push({name:l,score:d,bestChunk:p})}return c.sort((l,u)=>u.score-l.score),c.slice(0,s)}function ac(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 cc(t,e={}){let{topK:s=3,minScore:n=.1}=e,o=ec(t,{topK:s,minScore:n}),r=o;if(process.env.NEX_BRAIN_EMBEDDINGS!=="false")try{if(await nc()){let c=await ic(t,{topK:s});r=ac(o,c,{topK:s})}}catch{}return r.map(i=>{let c=Qa(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 Hp(t){if(!t||!t.trim())return"";let e=nt.join(process.cwd(),".nex","brain");if(!oe.existsSync(e)||bn().length===0)return"";let n;try{n=await cc(t,{topK:3})}catch{return""}if(!n||n.length===0)return"";let o;try{o=De().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 f=r-c;if(f<100)break;let h=f/d;u=u.slice(0,Math.floor(u.length*h))+`
|
|
168
|
+
...(truncated)`}let p=typeof l.score=="number"?l.score.toFixed(2):String(l.score);if(i.push(`--- ${l.name} (relevance: ${p}) ---
|
|
169
|
+
${u}`),c+=o(u),c>=r)break}return i.length===0?"":`KNOWLEDGE BASE (auto-selected):
|
|
170
|
+
|
|
171
|
+
${i.join(`
|
|
172
|
+
|
|
173
|
+
`)}`}lc.exports={getBrainDir:Gt,listDocuments:bn,readDocument:Qa,writeDocument:Dp,removeDocument:Fp,buildIndex:Lo,getIndex:Za,query:cc,getBrainContext:Hp,isEmbeddingAvailable:nc,generateEmbedding:Fo,buildEmbeddingIndex:rc,semanticQuery:ic,cosineSimilarity:sc,_keywordQuery:ec,_extractKeywords:qo,_chunkText:oc,parseFrontmatter:xn,tokenize:hs,_fuseResults:ac}});var Be=L((vy,bc)=>{var re=require("fs").promises,uc=require("fs"),Ee=require("path"),ae=require("util").promisify(require("child_process").exec),dc=require("util").promisify(require("child_process").execFile),{spawnSync:Gp}=require("child_process"),Uo=require("axios"),{isForbidden:zp,isDangerous:Kp,isCritical:fc,confirm:Ge}=We(),{showClaudeDiff:gs,showClaudeNewFile:Yp,showEditDiff:xy,confirmFileChange:kn}=Vi(),{C:I,Spinner:$c,getToolSpinnerText:Jp}=de(),{isGitRepo:Wo,getCurrentBranch:pc,getStatus:Vp,getDiff:Xp}=St(),{recordChange:$s}=ft(),{fuzzyFindText:mc,findMostSimilar:Ho}=xa(),{runDiagnostics:vn}=ka(),{findFileInIndex:Qp,getFileIndex:_y}=ko(),{resolveProfile:ze,sshExec:pt,scpUpload:Zp,scpDownload:em}=Ht(),{resolveDeployConfig:tm,loadDeployConfigs:ky}=Ro(),nm=/^(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/,sm=/^ssh\s/,om=/^ssh(?:\s+-\S+)*\s+\S+@?\S+\s+["']?[^-]/;async function ys(t){if(!t)return{fixedPath:null,message:""};let e=t.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),s=Se(e);if(s&&await re.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=Ee.extname(t);if(!o)for(let i of n){let c=Se(t+i);if(c&&await re.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=Se(i+c);if(l&&await re.access(l).then(()=>!0).catch(()=>!1))return{fixedPath:l,message:`(auto-fixed: ${o} \u2192 ${c})`}}}let r=Ee.basename(t);if(r&&r.length>2)try{let i=Qp(r).map(c=>Se(c));if(i.length===1)return{fixedPath:i[0],message:`(auto-fixed: found ${r} at ${Ee.relative(process.cwd(),i[0])})`};if(i.length>1&&i.length<=5)return{fixedPath:null,message:`File not found. Did you mean one of:
|
|
174
|
+
${i.map(l=>Ee.relative(process.cwd(),l)).map(l=>` - ${l}`).join(`
|
|
175
|
+
`)}`}}catch{}return{fixedPath:null,message:""}}function rm(t){return/\bprintenv\b/.test(t)?"printenv exposes all secrets. Use `echo $VAR_NAME` for a single variable, or `env | grep PATTERN` for filtered output.":/cat\s+.*\.env\b/.test(t)?'Reading .env directly is blocked. Use `grep -v "KEY=" .env` to inspect non-secret entries, or ask the user to share specific values.':/cat\s+.*credentials/i.test(t)?"Credentials files are blocked. Reference the variable name from the application config instead.":/python3?\s+-c\s/.test(t)?"Inline python -c is blocked. Write a temporary script file and run it with `python3 script.py` instead.":/node\s+-e\s/.test(t)?"Inline node -e is blocked. Write a temporary script file and run it with `node script.js` instead.":/curl.*-X\s*POST|curl.*--data/.test(t)?"curl POST is blocked to prevent data exfiltration. Use the application's own API client or ask the user to run the request.":/base64.*\|.*bash/.test(t)?"Piping base64-decoded content to bash is blocked. Decode the content first, inspect it, then run explicitly.":/\beval\s*\(/.test(t)?"eval is blocked. Execute the command directly without eval.":/(?:^|[;&|]\s*)history(?:\s|$)/.test(t)?"Shell history is blocked. Look at git log or project files for context instead.":""}function yc(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"),/cp.*\$f.*\$f\.bak.*sed.*-i\.bak|sed.*-i\.bak.*cp.*\$f.*\$f\.bak/i.test(e)&&s.push('HINT: Using both cp with .bak and sed -i.bak creates double backups (.bak.bak). Choose one method: either cp "$f" "$f.bak" OR sed -i.bak, not both.'),s.length===0?t:t+`
|
|
176
|
+
|
|
177
|
+
`+s.join(`
|
|
178
|
+
`)}function wc(t,e,s){let n=Ho(t,e);if(!n)return null;let o=Math.max(2,Math.ceil(e.length*.03));return n.distance>o?null:{autoFixed:!0,matchText:n.text,content:t.split(n.text).join(s),distance:n.distance,line:n.line}}var hc=!1,Tt=null;function im(){Tt&&(Tt(),Tt=null)}var Go=null;function am(t){Go=t}async function Bo(){if(!hc){hc=!0;try{let{stdout:t}=await ae("git rev-parse --is-inside-work-tree",{cwd:process.cwd(),timeout:5e3});if(!(t.trim()==="true"))return;await ae('git stash push -m "nex-code-checkpoint" --include-untracked',{cwd:process.cwd(),timeout:1e4}),await ae("git stash pop",{cwd:process.cwd(),timeout:1e4}),await ae("git tag -f nex-checkpoint",{cwd:process.cwd(),timeout:5e3})}catch{}}}var cm=[/\.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 Se(t){let e=Ee.isAbsolute(t)?Ee.resolve(t):Ee.resolve(process.cwd(),t);for(let s of cm)if(s.test(e))return null;return e}var lm=[{type:"function",function:{name:"bash",description:"Execute a bash command in the project directory. Timeout: 90s. Use for: running tests, installing packages, git commands, build tools, starting servers. Do NOT use bash for file operations when a dedicated tool exists \u2014 use read_file instead of cat, edit_file instead of sed, glob instead of find, grep instead of grep/rg. Always quote paths with spaces. Prefer specific commands over rm -rf. Destructive or dangerous commands require user confirmation.",parameters:{type:"object",properties:{command:{type:"string",description:"The bash command to execute"}},required:["command"]}}},{type:"function",function:{name:"read_file",description:"Read a file's contents with line numbers. Always read a file BEFORE editing it to see exact content. Use line_start/line_end for large files to read specific sections. Prefer this over bash cat/head/tail. Files are read with UTF-8 encoding. For binary files, use bash with appropriate flags. Alternative: use util.promisify(fs.readFile) for programmatic access.",parameters:{type:"object",properties:{path:{type:"string",description:"File path (relative or absolute)"},line_start:{type:"number",description:"Start line (1-based, optional)"},line_end:{type:"number",description:"End line (1-based, optional)"}},required:["path"]}}},{type:"function",function:{name:"write_file",description:"Create a new file or completely overwrite an existing file. For targeted changes to existing files, prefer edit_file or patch_file instead \u2014 they only send the diff and are safer. Only use write_file when creating new files or when the entire content needs to be replaced.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},content:{type:"string",description:"Full file content"}},required:["path","content"]}}},{type:"function",function:{name:"edit_file",description:"Replace specific text in a file. IMPORTANT: old_text must match the file content EXACTLY \u2014 including all whitespace, indentation (tabs vs spaces), and newlines. Always read_file first to see the exact content before editing. If old_text is not found, the edit fails. For multiple changes to the same file, prefer patch_file instead.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},old_text:{type:"string",description:"Exact text to find (must match file content precisely)"},new_text:{type:"string",description:"Replacement text"}},required:["path","old_text","new_text"]}}},{type:"function",function:{name:"list_directory",description:"List files and directories in a tree view. Use this to understand project structure. For finding specific files by pattern, prefer glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path"},max_depth:{type:"number",description:"Max depth (default: 2)"},pattern:{type:"string",description:"File filter glob (e.g. '*.js')"}},required:["path"]}}},{type:"function",function:{name:"search_files",description:"Search for a text pattern across files (regex). Returns matching lines with file paths. For simple content search, grep is equivalent. For finding files by name, use glob instead.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory to search"},pattern:{type:"string",description:"Search pattern (regex)"},file_pattern:{type:"string",description:"File filter (e.g. '*.js')"}},required:["path","pattern"]}}},{type:"function",function:{name:"glob",description:"Find files matching a glob pattern. Fast file search by name/extension. Use this to find files before reading them. Examples: '**/*.test.js' (all test files), 'src/**/*.ts' (all TypeScript in src). Prefer this over bash find/ls.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern (e.g. '**/*.ts', 'src/**/*.test.js')"},path:{type:"string",description:"Base directory (default: project root)"}},required:["pattern"]}}},{type:"function",function:{name:"grep",description:"Search file contents with regex. Returns matching lines with file paths and line numbers. Use this to find where functions/variables/classes are defined or used. Prefer this over bash grep/rg.",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory or file to search (default: project root)"},include:{type:"string",description:"File filter (e.g. '*.js', '*.ts')"},ignore_case:{type:"boolean",description:"Case-insensitive search"}},required:["pattern"]}}},{type:"function",function:{name:"patch_file",description:"Apply multiple text replacements to a file atomically. All patches are validated before any are applied \u2014 if one fails, none are written. Prefer this over multiple edit_file calls when making several changes to the same file. Like edit_file, all old_text values must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path"},patches:{type:"array",description:"Array of { old_text, new_text } replacements to apply in order",items:{type:"object",properties:{old_text:{type:"string",description:"Text to find"},new_text:{type:"string",description:"Replacement text"}},required:["old_text","new_text"]}}},required:["path","patches"]}}},{type:"function",function:{name:"web_fetch",description:"Fetch content from a URL and return text. HTML tags are stripped. Use for reading documentation, API responses, or web pages. Will not work with authenticated/private URLs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},max_length:{type:"number",description:"Max response length in chars (default: 10000)"}},required:["url"]}}},{type:"function",function:{name:"web_search",description:"Search the web. Uses Perplexity (grounded, AI-summarized) if PERPLEXITY_API_KEY is set, otherwise DuckDuckGo. Returns titles, URLs, and summaries. Use to find documentation, solutions, or current information beyond your knowledge cutoff.",parameters:{type:"object",properties:{query:{type:"string",description:"Search query"},max_results:{type:"number",description:"Max results (default: 5)"}},required:["query"]}}},{type:"function",function:{name:"browser_open",description:"Open a URL in a headless browser and return the page title, text content, and links. More reliable than web_fetch for JavaScript-heavy pages. Requires playwright (npm install playwright && npx playwright install chromium).",parameters:{type:"object",properties:{url:{type:"string",description:"URL to open"},wait_for:{type:"string",enum:["domcontentloaded","networkidle","load"],description:"When to consider page loaded (default: domcontentloaded)"}},required:["url"]}}},{type:"function",function:{name:"browser_screenshot",description:"Take a screenshot of a URL in a headless browser. Returns the screenshot file path. The path can be pasted into the next message for visual analysis. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to screenshot"},full_page:{type:"boolean",description:"Capture full page (default: false \u2014 viewport only)"},width:{type:"number",description:"Viewport width in px (default: 1280)"},height:{type:"number",description:"Viewport height in px (default: 800)"}},required:["url"]}}},{type:"function",function:{name:"browser_click",description:"Click an element on a web page (by CSS selector or visible text). Returns the new URL after navigation. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of element to click (mutually exclusive with text)"},text:{type:"string",description:"Visible text of element to click (mutually exclusive with selector)"}},required:["url"]}}},{type:"function",function:{name:"browser_fill",description:"Fill a form field on a web page and optionally submit. Requires playwright.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to navigate to first"},selector:{type:"string",description:"CSS selector of the input field"},value:{type:"string",description:"Value to fill in"},submit:{type:"boolean",description:"Press Enter to submit after filling (default: false)"}},required:["url","selector","value"]}}},{type:"function",function:{name:"ask_user",description:"Ask the user a clarifying question with 2-3 specific options. Use when the user's intent is ambiguous. Always provide concrete, actionable options. The user can select an option or type a custom answer.",parameters:{type:"object",properties:{question:{type:"string",description:"The clarifying question to ask"},options:{type:"array",items:{type:"string"},description:"2-3 specific, actionable answer options for the user to choose from",minItems:1,maxItems:3}},required:["question","options"]}}},{type:"function",function:{name:"git_status",description:"Get git status: current branch, changed files, staged/unstaged state. Use before git operations to understand the current state.",parameters:{type:"object",properties:{},required:[]}}},{type:"function",function:{name:"git_diff",description:"Get git diff for changed files. Shows additions and deletions.",parameters:{type:"object",properties:{staged:{type:"boolean",description:"Show only staged changes (default: false)"},file:{type:"string",description:"Diff specific file only (optional)"}},required:[]}}},{type:"function",function:{name:"git_log",description:"Show recent git commits (short format).",parameters:{type:"object",properties:{count:{type:"number",description:"Number of commits to show (default: 10)"},file:{type:"string",description:"Show commits for specific file (optional)"}},required:[]}}},{type:"function",function:{name:"task_list",description:"Create and manage a task list for complex multi-step tasks. Use for tasks with 3+ steps to track progress. Actions: create (new list with tasks), update (mark task in_progress/done/failed), get (view current list). Always update task status as you work.",parameters:{type:"object",properties:{action:{type:"string",enum:["create","update","get"],description:"Action to perform"},name:{type:"string",description:"Task list name (for create)"},tasks:{type:"array",description:"Array of tasks to create (for create)",items:{type:"object",properties:{description:{type:"string",description:"Task description"},depends_on:{type:"array",items:{type:"string"},description:"IDs of prerequisite tasks"}},required:["description"]}},task_id:{type:"string",description:"Task ID to update (for update)"},status:{type:"string",enum:["in_progress","done","failed"],description:"New status (for update)"},result:{type:"string",description:"Result summary (for update, optional)"}},required:["action"]}}},{type:"function",function:{name:"gh_run_list",description:"List recent GitHub Actions workflow runs for this repository. Shows run status, conclusion, branch, and timing. Use to check CI/CD status or find a run ID.",parameters:{type:"object",properties:{limit:{type:"number",description:"Number of runs to show (default: 10, max: 30)"},workflow:{type:"string",description:"Filter by workflow name or filename (optional)"},branch:{type:"string",description:"Filter by branch name (optional)"},status:{type:"string",enum:["completed","in_progress","queued","failure","success"],description:"Filter by status (optional)"}},required:[]}}},{type:"function",function:{name:"gh_run_view",description:"View details of a specific GitHub Actions workflow run: steps, logs, errors. Use gh_run_list first to get the run ID.",parameters:{type:"object",properties:{run_id:{type:"string",description:"The run ID (from gh_run_list)"},log:{type:"boolean",description:"Include full log output (default: false \u2014 shows step summary only)"}},required:["run_id"]}}},{type:"function",function:{name:"gh_workflow_trigger",description:"Trigger a GitHub Actions workflow dispatch event. Only works for workflows with workflow_dispatch trigger. Requires user confirmation.",parameters:{type:"object",properties:{workflow:{type:"string",description:"Workflow filename (e.g. ci.yml) or name"},branch:{type:"string",description:"Branch to run on (default: current branch)"},inputs:{type:"object",description:"Workflow input parameters as key-value pairs (optional)"}},required:["workflow"]}}},{type:"function",function:{name:"spawn_agents",description:"Run multiple independent sub-agents in parallel (max 5). Each agent has its own conversation context. Use when 2+ tasks can run simultaneously \u2014 e.g. reading multiple files, analyzing separate modules, independent research. Do NOT use for tasks that depend on each other or modify the same file. Keep task descriptions specific and self-contained.",parameters:{type:"object",properties:{agents:{type:"array",description:"Array of agent definitions to run in parallel (max 5)",items:{type:"object",properties:{task:{type:"string",description:"Task description for the agent"},context:{type:"string",description:"Additional context (optional)"},max_iterations:{type:"number",description:"Max iterations (default: 10, max: 15)"},model:{type:"string",description:'Override model for this agent (provider:model, e.g. "anthropic:claude-haiku"). Auto-selected if omitted.'}},required:["task"]}}},required:["agents"]}}},{type:"function",function:{name:"switch_model",description:"Switch the active AI model mid-conversation. Use when a different model is better for the next steps \u2014 e.g. switch to a fast model for simple lookups, or a more capable model for complex refactoring. The switch persists for all subsequent turns.",parameters:{type:"object",properties:{model:{type:"string",description:'Model spec: "provider:model" (e.g. "ollama:devstral-small-2:24b") or just model name'}},required:["model"]}}},{type:"function",function:{name:"k8s_pods",description:"List Kubernetes pods. Shows pod name, status, restarts, and age. Runs kubectl locally or via SSH on a remote server. Use namespace to filter, or omit for all namespaces.",parameters:{type:"object",properties:{namespace:{type:"string",description:"Namespace to list pods in (default: all namespaces)"},label:{type:"string",description:'Label selector filter (e.g. "app=nginx")'},context:{type:"string",description:"kubectl context to use (optional)"},server:{type:"string",description:"Remote server as user@host to run kubectl via SSH (optional, local kubectl if omitted)"}},required:[]}}},{type:"function",function:{name:"k8s_logs",description:'Fetch logs from a Kubernetes pod. Use tail to limit output, since for time-based filtering (e.g. "1h", "30m").',parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (required if pod has multiple containers)"},tail:{type:"number",description:"Number of recent lines to show (default: 100)"},since:{type:"string",description:'Show logs since duration (e.g. "1h", "30m", "5s")'},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod"]}}},{type:"function",function:{name:"k8s_exec",description:"Execute a command inside a running Kubernetes pod (kubectl exec). Requires user confirmation. Use for inspecting container state, reading configs, or debugging.",parameters:{type:"object",properties:{pod:{type:"string",description:"Pod name"},command:{type:"string",description:'Command to run in the pod (e.g. "env", "ls /app", "cat /etc/config.yaml")'},namespace:{type:"string",description:"Namespace (default: default)"},container:{type:"string",description:"Container name (optional)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["pod","command"]}}},{type:"function",function:{name:"k8s_apply",description:"Apply a Kubernetes manifest file (kubectl apply -f). Requires confirmation before applying to the cluster. Use dry_run=true to validate without applying.",parameters:{type:"object",properties:{file:{type:"string",description:"Path to manifest YAML file (relative or absolute)"},namespace:{type:"string",description:"Override namespace (optional)"},dry_run:{type:"boolean",description:"Validate only without applying (default: false)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["file"]}}},{type:"function",function:{name:"k8s_rollout",description:"Manage Kubernetes deployment rollouts: check status, restart (rolling update), view history, or undo (rollback). Restart and undo require confirmation.",parameters:{type:"object",properties:{action:{type:"string",enum:["status","restart","history","undo"],description:"Action: status (check rollout progress), restart (rolling restart), history (show revision history), undo (rollback to previous revision)"},deployment:{type:"string",description:"Deployment name"},namespace:{type:"string",description:"Namespace (default: default)"},context:{type:"string",description:"kubectl context (optional)"},server:{type:"string",description:"Remote server user@host (optional)"}},required:["action","deployment"]}}},{type:"function",function:{name:"brain_write",description:"Write or update a knowledge document in the project brain (.nex/brain/). Use this to persist important findings, architecture decisions, debugging insights, or conventions discovered during the session. The user can review changes via /brain review or git diff.",parameters:{type:"object",properties:{name:{type:"string",description:'Document name (without .md extension). Use kebab-case. Examples: "api-auth-flow", "db-schema-notes", "deployment-checklist"'},content:{type:"string",description:"Full Markdown content. Use headings (#), lists (-), and code blocks. Include optional YAML frontmatter with tags."},mode:{type:"string",enum:["create","update","append"],description:"create: new document (fails if exists). update: overwrite existing. append: add to end of existing document."}},required:["name","content","mode"]}}},{type:"function",function:{name:"ssh_exec",description:'Execute a command on a remote server via SSH. Server is a profile name from .nex/servers.json (e.g. "prod") or "user@host". Use for: checking status, reading logs, running deployments. Destructive commands (restart, delete, modify config) require confirmation. For service management prefer service_manage; for logs prefer service_logs.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name (from .nex/servers.json) or "user@host"'},command:{type:"string",description:"Shell command to run on the remote server"},sudo:{type:"boolean",description:"Run command with sudo (only if profile has sudo:true). Default: false"},timeout:{type:"number",description:"Timeout in seconds. Default: 30"}},required:["server","command"]}}},{type:"function",function:{name:"ssh_upload",description:"Upload a local file or directory to a remote server via SCP. Recursive for directories. Requires confirmation before upload.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},local_path:{type:"string",description:"Local path to upload (file or directory)"},remote_path:{type:"string",description:"Destination path on the remote server (absolute preferred)"}},required:["server","local_path","remote_path"]}}},{type:"function",function:{name:"ssh_download",description:"Download a file or directory from a remote server via SCP. Recursive for directories.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host"'},remote_path:{type:"string",description:"Path on the remote server to download"},local_path:{type:"string",description:"Local destination path"}},required:["server","remote_path","local_path"]}}},{type:"function",function:{name:"service_manage",description:"Manage a systemd service on a remote (or local) server. Uses systemctl. Status is read-only; start/stop/restart/reload/enable/disable require confirmation. For AlmaLinux 9: runs via SSH with sudo if configured.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn", "postgresql")'},action:{type:"string",enum:["status","start","stop","restart","reload","enable","disable"],description:"systemctl action to perform"}},required:["service","action"]}}},{type:"function",function:{name:"service_logs",description:"Fetch systemd service logs via journalctl. Works on AlmaLinux 9 and any systemd Linux. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},service:{type:"string",description:'Service name (e.g. "nginx", "gunicorn")'},lines:{type:"number",description:"Number of recent log lines to fetch. Default: 50"},since:{type:"string",description:'Time filter, e.g. "1 hour ago", "today", "2024-01-01 12:00". Optional.'},follow:{type:"boolean",description:"Tail logs in real-time (follow mode). Default: false"}},required:["service"]}}},{type:"function",function:{name:"container_list",description:"List Docker containers on a server (or locally). Shows container ID, name, image, status, and ports. Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},all:{type:"boolean",description:"Show all containers including stopped ones. Default: false (running only)."}},required:[]}}},{type:"function",function:{name:"container_logs",description:"Fetch logs from a Docker container on a server (or locally). Read-only, no confirmation needed.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},lines:{type:"number",description:"Number of recent log lines. Default: 50."},since:{type:"string",description:'Time filter, e.g. "1h", "30m", "2024-01-01T12:00:00". Optional.'}},required:["container"]}}},{type:"function",function:{name:"container_exec",description:"Execute a command inside a running Docker container. Destructive or state-changing commands require confirmation.",parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},command:{type:"string",description:'Command to run inside the container (e.g. "cat /etc/nginx/nginx.conf").'}},required:["container","command"]}}},{type:"function",function:{name:"container_manage",description:'Start, stop, restart, or remove a Docker container. All actions except "inspect" require confirmation.',parameters:{type:"object",properties:{server:{type:"string",description:'Profile name or "user@host". Omit or use "local" for local machine.'},container:{type:"string",description:"Container name or ID."},action:{type:"string",enum:["start","stop","restart","remove","inspect"],description:"Action to perform on the container."}},required:["container","action"]}}},{type:"function",function:{name:"deploy",description:'Deploy files to a remote server via rsync + optional remote script. Can use a named config from .nex/deploy.json (e.g. deploy("prod")) or explicit params. Requires confirmation before executing.',parameters:{type:"object",properties:{config:{type:"string",description:'Named deploy config from .nex/deploy.json (e.g. "prod"). Overrides all other params if provided.'},server:{type:"string",description:'Profile name or "user@host". Required if no config.'},local_path:{type:"string",description:'Local directory or file to sync (e.g. "dist/", "./build"). Required if no config.'},remote_path:{type:"string",description:'Remote destination path (e.g. "/var/www/app"). Required if no config.'},deploy_script:{type:"string",description:"Shell command to run on the remote after sync. Optional."},exclude:{type:"array",items:{type:"string"},description:"Paths to exclude from sync. Optional."},dry_run:{type:"boolean",description:"Show what would be synced without actually syncing. Default: false."}},required:[]}}}];function Sn(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 gc(t,e,s={}){switch(t){case"bash":{let n=e.command,o=zp(n);if(o){let u=rm(n);return`BLOCKED: Command matches forbidden pattern: ${o}${u?`
|
|
179
|
+
HINT: ${u}`:""}`}if(s.autoConfirm?fc(n):Kp(n)){let u=fc(n)?" \u26D4 Critical command":" \u26A0 Dangerous command";if(console.log(`
|
|
180
|
+
${I.yellow}${u}: ${n}${I.reset}`),!await Ge(" Execute?"))return"CANCELLED: User declined to execute this command."}let i=process.cwd();try{uc.accessSync(i)}catch{i=require("os").homedir(),s.silent||console.log(`${I.yellow} \u26A0 Working directory no longer exists \u2014 running in ${i}${I.reset}`)}let c=sm.test(n.trim())&&!om.test(n.trim());if(nm.test(n.trim())||c){s.silent||console.log(`${I.dim} \u25B6 interactive: ${n}${I.reset}`);let u=Gp("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 $c(`Running: ${n.substring(0,60)}${n.length>60?"...":""}`);l&&l.start();try{let{stdout:u,stderr:d}=await ae(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),p=yc(d,n);return`EXIT ${u.code||1}
|
|
181
|
+
${p}`}}case"read_file":{let n=Se(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await re.access(n).then(()=>!0).catch(()=>!1)){let f=await ys(e.path);if(f.fixedPath)n=f.fixedPath,console.log(`${I.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ee.relative(process.cwd(),n)}${I.reset}`);else return`ERROR: File not found: ${e.path}${f.message?`
|
|
182
|
+
`+f.message:""}`}let r=Buffer.alloc(8192),i=await uc.promises.open(n,"r"),{bytesRead:c}=await i.read(r,0,8192,0);await i.close();for(let f=0;f<c;f++)if(r[f]===0)return`ERROR: ${n} is a binary file (not readable as text)`;let l=await re.readFile(n,"utf-8");if(!l&&(await re.stat(n)).size>0)return`WARNING: ${n} is empty or unreadable`;let u=l.split(`
|
|
183
|
+
`),d=(e.line_start||1)-1,p=e.line_end||u.length;return u.slice(d,p).map((f,h)=>`${d+h+1}: ${f}`).join(`
|
|
184
|
+
`)}case"write_file":{await Bo();let n=Se(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=await re.access(n).then(()=>!0).catch(()=>!1),r=null;if(s.autoConfirm)o&&(r=await re.readFile(n,"utf-8"));else if(o){r=await re.readFile(n,"utf-8");let l=await vn(n,e.content);if(gs(n,r,e.content,{annotations:l}),!await kn("Overwrite"))return"CANCELLED: User declined to overwrite file."}else{let l=await vn(n,e.content);if(Yp(n,e.content,{annotations:l}),!await kn("Create"))return"CANCELLED: User declined to create file."}let i=Ee.dirname(n);return await re.access(i).then(()=>!0).catch(()=>!1)||await re.mkdir(i,{recursive:!0}),await re.writeFile(n,e.content,"utf-8"),$s("write_file",n,r,e.content),`Written: ${n} (${e.content.length} chars)`}case"edit_file":{await Bo();let n=Se(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await re.access(n).then(()=>!0).catch(()=>!1)){let d=await ys(e.path);if(d.fixedPath)n=d.fixedPath,console.log(`${I.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ee.relative(process.cwd(),n)}${I.reset}`);else return`ERROR: File not found: ${e.path}${d.message?`
|
|
185
|
+
`+d.message:""}`}let r=await re.readFile(n,"utf-8"),i=e.old_text,c=!1,l=!1;if(!r.includes(e.old_text)){let d=mc(r,e.old_text);if(d)i=d,c=!0,console.log(`${I.dim} \u2713 fuzzy whitespace match applied${I.reset}`);else{let p=wc(r,e.old_text,e.new_text);if(p){if(!s.autoConfirm){let m=await vn(n,p.content);if(gs(n,r,p.content,{annotations:m}),!await kn(`Apply (auto-fix, line ${p.line}, distance ${p.distance})`))return"CANCELLED: User declined to apply edit."}await re.writeFile(n,p.content,"utf-8"),$s("edit_file",n,r,p.content);let h=p.matchText.length>80?p.matchText.substring(0,77)+"...":p.matchText;return console.log(`${I.dim} \u2713 auto-fixed edit: line ${p.line}, distance ${p.distance}${I.reset}`),`Edited: ${n} (auto-fixed, line ${p.line}, distance ${p.distance}, matched: "${h}")`}let f=Ho(r,e.old_text);return f?`ERROR: old_text not found in ${n}
|
|
186
|
+
Most similar text (line ${f.line}, distance ${f.distance}):
|
|
187
|
+
${f.text}`:`ERROR: old_text not found in ${n}`}}if(!s.autoConfirm){let d=r.split(i).join(e.new_text),p=await vn(n,d);if(gs(n,r,d,{annotations:p}),!await kn(c?"Apply (fuzzy match)":"Apply"))return"CANCELLED: User declined to apply edit."}let u=r.split(i).join(e.new_text);return await re.writeFile(n,u,"utf-8"),$s("edit_file",n,r,u),c?`Edited: ${n} (fuzzy match)`:`Edited: ${n}`}case"list_directory":{let n=Se(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await re.access(n).then(()=>!0).catch(()=>!1)){let u=e.path.replace(/\/+/g,"/").replace(/^~\//,`${require("os").homedir()}/`),d=Se(u),p=await re.access(d).then(()=>!0).catch(()=>!1);if(d&&p)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,p)=>{if(d>r)return;let f;try{f=await re.readdir(u,{withFileTypes:!0})}catch{return}f=f.filter(h=>!h.name.startsWith(".")&&h.name!=="node_modules");for(let h of f){if(i&&!h.isDirectory()&&!i.test(h.name))continue;let m=h.isDirectory()?"/":"";c.push(`${p}${h.name}${m}`),h.isDirectory()&&await l(Ee.join(u,h.name),d+1,p+" ")}};return await l(n,1,""),c.join(`
|
|
188
|
+
`)||"(empty)"}case"search_files":{let n=Se(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;let o=["-rn","--null","-H"];e.file_pattern&&o.push(`--include=${e.file_pattern}`),o.push(e.pattern,n);try{let{stdout:r}=await dc("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),c=[];for(let l=0;l<i.length;l+=2){let u=i[l],d=i[l+1];if(u&&d){let p=d.split(`
|
|
189
|
+
`).filter(f=>f.trim());for(let f of p)if(c.push(`${u}:${f}`),c.length>=50)break}if(c.length>=50)break}return c.join(`
|
|
190
|
+
`)||"(no matches)"}catch{return"(no matches)"}}case"glob":{let o=process.cwd(),r=e.path?Se(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:p,getIndexedCwd:f,refreshIndex:h,isIndexValid:m}=ko(),g=p(),y=f();m(r)||(await h(r),g=p());let $=g.filter(k=>l.test(k)||d.test(Ee.basename(k))).map(k=>Ee.join(r,k));if($.length===0)return"(no matches)";let x=$.length>200,S=$.slice(0,200).join(`
|
|
191
|
+
`);return x?`${S}
|
|
192
|
+
|
|
193
|
+
\u26A0 Results truncated at 200. Use a more specific pattern.`:S}case"grep":{let n=e.path?Se(e.path):process.cwd(),o=["-rn","-E","--null","-H"];e.ignore_case&&o.push("-i"),e.include&&o.push(`--include=${e.include}`),o.push("--exclude-dir=node_modules","--exclude-dir=.git","--exclude-dir=coverage"),o.push(e.pattern,n);try{let{stdout:r}=await dc("grep",o,{cwd:process.cwd(),timeout:3e4,maxBuffer:2097152}),i=r.split("\0"),c=[];for(let l=0;l<i.length;l+=2){let u=i[l],d=i[l+1];if(u&&d){let p=d.split(`
|
|
194
|
+
`).filter(f=>f.trim());for(let f of p)if(c.push(`${u}:${f}`),c.length>=100)break}if(c.length>=100)break}return c.join(`
|
|
195
|
+
`).trim()||"(no matches)"}catch(r){return r.code===2?`ERROR: Invalid regex pattern: ${e.pattern}`:"(no matches)"}}case"patch_file":{await Bo();let n=Se(e.path);if(!n)return`ERROR: Access denied \u2014 path outside project: ${e.path}`;if(!await re.access(n).then(()=>!0).catch(()=>!1)){let f=await ys(e.path);if(f.fixedPath)n=f.fixedPath,console.log(`${I.dim} \u2713 auto-fixed path: ${e.path} \u2192 ${Ee.relative(process.cwd(),n)}${I.reset}`);else return`ERROR: File not found: ${e.path}${f.message?`
|
|
196
|
+
`+f.message:""}`}let r=e.patches;if(!Array.isArray(r)||r.length===0)return"ERROR: No patches provided";let i=await re.readFile(n,"utf-8"),c=[],l=!1,u=!1;for(let f=0;f<r.length;f++){let{old_text:h,new_text:m}=r[f];if(i.includes(h))c.push({old_text:h,new_text:m});else{let g=mc(i,h);if(g)c.push({old_text:g,new_text:m}),l=!0;else{let y=Ho(i,h);if(y){let $=Math.max(3,Math.ceil(h.length*.05));if(y.distance<=$)c.push({old_text:y.text,new_text:m}),u=!0;else return`ERROR: Patch ${f+1} old_text not found in ${n}
|
|
197
|
+
Most similar text (line ${y.line}, distance ${y.distance}):
|
|
198
|
+
${y.text}`}else return`ERROR: Patch ${f+1} old_text not found in ${n}`}}}let d=i;for(let{old_text:f,new_text:h}of c)d=d.split(f).join(h);if(!s.autoConfirm){let f=await vn(n,d);if(gs(n,i,d,{annotations:f}),!await kn(l?"Apply patches (fuzzy match)":"Apply patches"))return"CANCELLED: User declined to apply patches."}await re.writeFile(n,d,"utf-8"),$s("patch_file",n,i,d);let p=u?" (auto-fixed)":l?" (fuzzy match)":"";return`Patched: ${n} (${r.length} replacements)${p}`}case"web_fetch":{let n=e.url,o=e.max_length||1e4;try{let r=await Uo.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 Uo.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]
|
|
199
|
+
|
|
200
|
+
${r}`;return i.length>0&&(c+=`
|
|
202
201
|
|
|
203
202
|
Sources:
|
|
204
|
-
`+
|
|
205
|
-
`)),c}catch(
|
|
203
|
+
`+i.slice(0,n).map((l,u)=>`${u+1}. ${l}`).join(`
|
|
204
|
+
`)),c}catch(o){console.error(`${I.dim} Perplexity search failed (${o.message}), falling back to DuckDuckGo${I.reset}`)}try{let r=(await Uo.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}
|
|
206
205
|
${u.url}`).join(`
|
|
207
206
|
|
|
208
|
-
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=
|
|
207
|
+
`)}catch{return"ERROR: Web search failed"}}case"browser_open":{let{browserNavigate:n}=pn();try{let o=await n(e.url,{waitFor:e.wait_for}),r=o.links.length>0?`
|
|
209
208
|
|
|
210
209
|
Links:
|
|
211
|
-
`+
|
|
212
|
-
`):"";return`Title: ${
|
|
213
|
-
URL: ${
|
|
210
|
+
`+o.links.map(i=>` ${i.text} \u2192 ${i.href}`).join(`
|
|
211
|
+
`):"";return`Title: ${o.title}
|
|
212
|
+
URL: ${o.url}
|
|
214
213
|
|
|
215
|
-
${
|
|
216
|
-
Title: ${
|
|
217
|
-
URL: ${
|
|
214
|
+
${o.text}${r}`}catch(o){return`ERROR: ${o.message}`}}case"browser_screenshot":{let{browserScreenshot:n}=pn();try{let o=await n(e.url,{width:e.width,height:e.height,fullPage:e.full_page});return`Screenshot saved: ${o.path}
|
|
215
|
+
Title: ${o.title}
|
|
216
|
+
URL: ${o.url}
|
|
218
217
|
|
|
219
|
-
To analyze visually, paste the path into your next message: ${
|
|
220
|
-
${
|
|
218
|
+
To analyze visually, paste the path into your next message: ${o.path}`}catch(o){return`ERROR: ${o.message}`}}case"browser_click":{let{browserClick:n}=pn();try{return await n(e.url,{selector:e.selector,text:e.text})}catch(o){return`ERROR: ${o.message}`}}case"browser_fill":{let{browserFill:n}=pn();try{return await n(e.url,{selector:e.selector,value:e.value,submit:e.submit})}catch(o){return`ERROR: ${o.message}`}}case"ask_user":{let{question:n,options:o=[]}=e;return Go?new Promise(r=>{Tt=()=>r("CANCELLED"),Go(n,o).then(i=>{Tt=null,r(i||"User did not answer")})}):new Promise(r=>{let i=require("readline").createInterface({input:process.stdin,output:process.stdout});Tt=()=>{i.close(),r("CANCELLED")};let c=o.length>0?`
|
|
219
|
+
${o.map((l,u)=>` ${u+1}. ${l}`).join(`
|
|
221
220
|
`)}
|
|
222
221
|
`:"";console.log(`
|
|
223
|
-
${I.cyan}${I.bold} ? ${n}${I.reset}${c}`),
|
|
224
|
-
Clean working tree (no changes)`;let
|
|
225
|
-
`)}case"git_diff":{if(!await
|
|
226
|
-
`+
|
|
227
|
-
`+d.map(
|
|
228
|
-
`)}case"update":return!e.task_id||!e.status?"ERROR: task_list update requires task_id and status":
|
|
229
|
-
`+
|
|
230
|
-
`+
|
|
231
|
-
`)}catch(
|
|
232
|
-
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:
|
|
233
|
-
...(truncated)`:"")}let{stdout:n}=await
|
|
222
|
+
${I.cyan}${I.bold} ? ${n}${I.reset}${c}`),i.question(`${I.cyan} > ${I.reset}`,l=>{Tt=null,i.close(),r(l.trim()||"(no response)")})})}case"git_status":{if(!await Wo())return"ERROR: Not a git repository";let n=await pc()||"(detached)",o=await Vp();if(o.length===0)return`Branch: ${n}
|
|
223
|
+
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(`
|
|
224
|
+
`)}case"git_diff":{if(!await Wo())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 Xp(!!e.staged);return n||"(no diff)"}case"git_log":{if(!await Wo())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}=ds(),{getActiveTaskProgress:l}=de(),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(`
|
|
225
|
+
`+i()),`Created task list "${e.name}" with ${d.length} tasks:
|
|
226
|
+
`+d.map(p=>` ${p.id}: ${p.description}`).join(`
|
|
227
|
+
`)}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(`
|
|
228
|
+
`+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(`
|
|
229
|
+
`+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}=Va();return n(e)}case"switch_model":{let{setActiveModel:n,getActiveProviderName:o,getActiveModelId:r}=ge();return n(e.model)?`Switched to ${o()}:${r()}`:`ERROR: Unknown model: ${e.model}. Use /providers to see available models.`}case"gh_run_list":{let n=Math.min(e.limit||10,30),o=["run","list","--limit",String(n),"--json","databaseId,status,conclusion,name,headBranch,createdAt,updatedAt,event"];e.workflow&&o.push("--workflow",e.workflow),e.branch&&o.push("--branch",e.branch),e.status&&o.push("--status",e.status);try{let{stdout:r}=await ae(`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",p=l.updatedAt?new Date(l.updatedAt).toISOString().slice(0,16).replace("T"," "):"";return`${d} [${l.databaseId}] ${l.name} \xB7 ${l.headBranch} \xB7 ${u} \xB7 ${p}`}).join(`
|
|
230
|
+
`)}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(`
|
|
231
|
+
`)[0]}`}}case"gh_run_view":{if(!e.run_id)return"ERROR: run_id is required";try{if(e.log){let{stdout:i}=await ae(`gh run view ${e.run_id} --log`,{cwd:process.cwd(),timeout:6e4,maxBuffer:5242880});return i.substring(0,8e3)+(i.length>8e3?`
|
|
232
|
+
...(truncated)`:"")}let{stdout:n}=await ae(`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(`
|
|
234
233
|
`)}catch(n){return`ERROR: ${(n.stderr||n.message||"").toString().split(`
|
|
235
|
-
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=
|
|
236
|
-
${I.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${
|
|
237
|
-
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",
|
|
238
|
-
`)[0];return c.includes("command not found")?"ERROR: kubectl not found. Install kubectl or provide a server with kubectl.":`ERROR: ${c}`}}case"k8s_logs":{if(!e.pod)return"ERROR: pod is required";let n=e.namespace||"default",
|
|
234
|
+
`)[0]}`}}case"gh_workflow_trigger":{if(!e.workflow)return"ERROR: workflow is required";let{confirm:n}=We(),o=e.branch||await pc()||"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(`
|
|
235
|
+
${I.yellow} \u26A0 Trigger workflow: ${e.workflow} on ${o}${I.reset}`),!await n(" Trigger?"))return"CANCELLED: User declined to trigger workflow.";try{return await ae(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(`
|
|
236
|
+
`)[0]}`}}case"k8s_pods":{let n=e.namespace?`-n ${e.namespace}`:"-A",o=e.label?`-l ${e.label}`:"",r=Sn(`get pods ${n} ${o} -o wide`.trim(),e);try{let{stdout:i,stderr:c}=await ae(r,{timeout:3e4,maxBuffer:2097152});return(i||c||"(no pods)").trim()}catch(i){let c=(i.stderr||i.message||"").toString().split(`
|
|
237
|
+
`)[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=Sn(r,e);try{let{stdout:c,stderr:l}=await ae(i,{timeout:6e4,maxBuffer:5242880}),u=(c||l||"(no logs)").trim();return u.substring(0,2e4)+(u.length>2e4?`
|
|
239
238
|
...(truncated)`:"")}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
240
239
|
`)[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(`
|
|
241
|
-
${I.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${I.reset}`),console.log(`${I.dim} Command: ${e.command}${I.reset}`),!await
|
|
242
|
-
`)[0]}`}}case"k8s_apply":{if(!e.file)return"ERROR: file is required";let n=!!e.dry_run;if(!n){let
|
|
243
|
-
${I.yellow} \u26A0 kubectl apply: ${
|
|
240
|
+
${I.yellow} \u26A0 kubectl exec into pod: ${e.pod} (ns: ${n})${I.reset}`),console.log(`${I.dim} Command: ${e.command}${I.reset}`),!await Ge(" 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=Sn(r,e);try{let{stdout:c,stderr:l}=await ae(i,{timeout:6e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
241
|
+
`)[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(`
|
|
242
|
+
${I.yellow} \u26A0 kubectl apply: ${i}${e.namespace?` (ns: ${e.namespace})`:""}${I.reset}`),!await Ge(" 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=Sn(o,e);try{let{stdout:i,stderr:c}=await ae(r,{timeout:12e4,maxBuffer:2097152});return(i||c||"(no output)").trim()}catch(i){return`ERROR: ${(i.stderr||i.message||"").toString().split(`
|
|
244
243
|
`)[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(`
|
|
245
|
-
${I.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${n})${I.reset}`),!await
|
|
246
|
-
`)[0]}`}}case"brain_write":{if(!e.name)return"ERROR: name is required";if(!e.content)return"ERROR: content is required";if(!e.mode)return"ERROR: mode is required (create, update, append)";let{writeDocument:n,readDocument:
|
|
244
|
+
${I.yellow} \u26A0 ${c}: deployment/${e.deployment} (ns: ${n})${I.reset}`),!await Ge(` ${c}?`))return"CANCELLED: User declined."}let r=`rollout ${e.action} deployment/${e.deployment} -n ${n}`,i=Sn(r,e);try{let{stdout:c,stderr:l}=await ae(i,{timeout:12e4,maxBuffer:2097152});return(c||l||"(no output)").trim()}catch(c){return`ERROR: ${(c.stderr||c.message||"").toString().split(`
|
|
245
|
+
`)[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}=_n(),{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+`
|
|
247
246
|
|
|
248
|
-
`+
|
|
249
|
-
${I.yellow} \u26A0 Remote command on ${h}: ${
|
|
247
|
+
`+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=ze(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(`
|
|
248
|
+
${I.yellow} \u26A0 Remote command on ${h}: ${o}${I.reset}`),!await Ge(" Execute on remote server?"))return"CANCELLED: User declined to execute remote command."}let{stdout:l,stderr:u,exitCode:d,error:p}=await pt(n,o,{timeout:i,sudo:r}),f=[l,u].filter(Boolean).join(`
|
|
250
249
|
`).trim();return d!==0?`EXIT ${d}
|
|
251
|
-
${f||
|
|
252
|
-
${I.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${
|
|
253
|
-
${I.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${I.reset}`),!await
|
|
254
|
-
${
|
|
255
|
-
`).trim();return d!==0?/not found|loaded.*not-found/i.test(
|
|
256
|
-
${f||
|
|
257
|
-
${(
|
|
258
|
-
`).trim();return
|
|
259
|
-
${
|
|
260
|
-
${(
|
|
250
|
+
${p||f||"(no output)"}`:f||"(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=ze(e.server)}catch(i){return`ERROR: ${i.message}`}let o=n.user?`${n.user}@${n.host}`:n.host;if(console.log(`
|
|
251
|
+
${I.yellow} \u26A0 Upload: ${e.local_path} \u2192 ${o}:${e.remote_path}${I.reset}`),!await Ge(" Upload to remote server?"))return"CANCELLED: User declined upload.";try{return await Zp(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=ze(e.server)}catch(o){return`ERROR: ${o.message}`}try{return await em(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=ze(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(`
|
|
252
|
+
${I.yellow} \u26A0 Service: systemctl ${e.action} ${e.service} on ${l}${I.reset}`),!await Ge(" 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:p}=await ae(u,{timeout:15e3});return(d||p||`systemctl ${e.action} ${e.service}: OK`).trim()}catch(d){let p=(d.stderr||d.message||"").toString().trim();return/not found|loaded.*not-found/i.test(p)?`ERROR: Service "${e.service}" not found. Check: systemctl list-units --type=service`:`EXIT ${d.code||1}
|
|
253
|
+
${p}`}}else{let{stdout:l,stderr:u,exitCode:d,error:p}=await pt(i,c,{timeout:15e3,sudo:!0}),f=[l,u].filter(Boolean).join(`
|
|
254
|
+
`).trim();return d!==0?/not found|loaded.*not-found/i.test(f)?`ERROR: Service "${e.service}" not found on ${i.host}. Check: ssh_exec to run "systemctl list-units --type=service"`:`EXIT ${d}
|
|
255
|
+
${p||f||"(no output)"}`:f||`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:m,stderr:g}=await ae(c,{timeout:15e3});return(m||g||"(no log output)").trim()}catch(m){return`EXIT ${m.code||1}
|
|
256
|
+
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=ze(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:u,stderr:d,exitCode:p,error:f}=await pt(l,c,{timeout:2e4}),h=[u,d].filter(Boolean).join(`
|
|
257
|
+
`).trim();return p!==0?`EXIT ${p}
|
|
258
|
+
${f||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:f,stderr:h}=await ae(r,{timeout:1e4});return(f||h||"(no containers)").trim()}catch(f){return`EXIT ${f.code||1}
|
|
259
|
+
${(f.stderr||f.message||"").toString().trim()}`}let i;try{i=ze(e.server)}catch(f){return`ERROR: ${f.message}`}let{stdout:c,stderr:l,exitCode:u,error:d}=await pt(i,r,{timeout:15e3}),p=[c,l].filter(Boolean).join(`
|
|
261
260
|
`).trim();return u!==0?`EXIT ${u}
|
|
262
|
-
${d||
|
|
263
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=
|
|
261
|
+
${d||p}`:p||"(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:m}=await ae(i,{timeout:15e3});return(h||m||"(no log output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
262
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=ze(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:p}=await pt(c,i,{timeout:2e4}),f=[l,u].filter(Boolean).join(`
|
|
264
263
|
`).trim();return d!==0?`EXIT ${d}
|
|
265
|
-
${f
|
|
266
|
-
${I.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${I.reset}`),!await
|
|
267
|
-
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=
|
|
264
|
+
${p||f}`:f||"(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(`
|
|
265
|
+
${I.yellow} \u26A0 docker exec in ${e.container} on ${h}: ${e.command}${I.reset}`),!await Ge(" Execute?"))return"CANCELLED: User declined."}let i=`docker exec ${e.container} sh -c ${JSON.stringify(e.command)}`;if(n)try{let{stdout:h,stderr:m}=await ae(i,{timeout:3e4});return(h||m||"(no output)").trim()}catch(h){return`EXIT ${h.code||1}
|
|
266
|
+
${(h.stderr||h.message||"").toString().trim()}`}let c;try{c=ze(e.server)}catch(h){return`ERROR: ${h.message}`}let{stdout:l,stderr:u,exitCode:d,error:p}=await pt(c,i,{timeout:35e3}),f=[l,u].filter(Boolean).join(`
|
|
268
267
|
`).trim();return d!==0?`EXIT ${d}
|
|
269
|
-
${f
|
|
270
|
-
${I.yellow} \u26A0 docker ${e.action} ${e.container} on ${
|
|
271
|
-
${(
|
|
272
|
-
`).trim();return
|
|
273
|
-
${
|
|
274
|
-
${I.yellow} \u26A0 Deploy: ${d} \u2192 ${
|
|
275
|
-
${
|
|
276
|
-
`).trim();if(
|
|
277
|
-
|
|
278
|
-
ERROR (deploy_script, exit ${
|
|
279
|
-
${
|
|
268
|
+
${p||f}`:f||"(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 m=o?"local":e.server;if(console.log(`
|
|
269
|
+
${I.yellow} \u26A0 docker ${e.action} ${e.container} on ${m}${I.reset}`),!await Ge(" 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:m,stderr:g}=await ae(c,{timeout:3e4});return(m||g||`docker ${e.action} ${e.container}: OK`).trim()}catch(m){return`EXIT ${m.code||1}
|
|
270
|
+
${(m.stderr||m.message||"").toString().trim()}`}let l;try{l=ze(e.server)}catch(m){return`ERROR: ${m.message}`}let{stdout:u,stderr:d,exitCode:p,error:f}=await pt(l,c,{timeout:35e3}),h=[u,d].filter(Boolean).join(`
|
|
271
|
+
`).trim();return p!==0?`EXIT ${p}
|
|
272
|
+
${f||h}`:h||`docker ${e.action} ${e.container}: OK`}case"deploy":{if(e.config)try{e={...tm(e.config),...e},delete e.config,delete e._name}catch(m){return`ERROR: ${m.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=ze(e.server)}catch(m){return`ERROR: ${m.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(m=>`--exclude="${m}"`).join(" "),u=e.dry_run?"--dry-run":"",d=e.local_path.endsWith("/")?e.local_path:`${e.local_path}/`,p=`rsync -avz --delete ${u} ${l} ${c} ${d} ${o}:${e.remote_path}`.trim().replace(/\s+/g," ");if(!e.dry_run&&!s.autoConfirm&&(console.log(`
|
|
273
|
+
${I.yellow} \u26A0 Deploy: ${d} \u2192 ${o}:${e.remote_path}${I.reset}`),e.deploy_script&&console.log(`${I.yellow} Then run: ${e.deploy_script}${I.reset}`),!await Ge(" Proceed with deployment?")))return"CANCELLED: User declined.";let f="";try{let{stdout:m,stderr:g}=await ae(p,{timeout:12e4});f=(m||g||"").trim()}catch(m){return`ERROR (rsync): ${(m.stderr||m.message||"").toString().trim()}`}if(e.dry_run)return`DRY RUN:
|
|
274
|
+
${f||"(nothing to sync)"}`;let h="";if(e.deploy_script){let{stdout:m,stderr:g,exitCode:y,error:$}=await pt(n,e.deploy_script,{timeout:6e4}),x=[m,g].filter(Boolean).join(`
|
|
275
|
+
`).trim();if(y!==0)return`rsync OK
|
|
276
|
+
|
|
277
|
+
ERROR (deploy_script, exit ${y}):
|
|
278
|
+
${$||x}`;h=`
|
|
280
279
|
|
|
281
280
|
Remote script output:
|
|
282
|
-
${x||"(no output)"}`}return`Deployed ${d} \u2192 ${
|
|
283
|
-
${
|
|
284
|
-
`)}function
|
|
281
|
+
${x||"(no output)"}`}return`Deployed ${d} \u2192 ${o}:${e.remote_path}
|
|
282
|
+
${f}${h}`.trim()}default:return`ERROR: Unknown tool: ${t}`}}async function um(t,e,s={}){let n=s.silent?null:Jp(t,e);if(!n)return gc(t,e,s);let o=new $c(n);o.start();try{let r=await gc(t,e,s);return o.stop(),r}catch(r){throw o.stop(),r}}bc.exports={TOOL_DEFINITIONS:lm,executeTool:um,resolvePath:Se,autoFixPath:ys,autoFixEdit:wc,enrichBashError:yc,cancelPendingAskUser:im,setAskUserHandler:am}});var _c=L((Sy,xc)=>{var{loadServerProfiles:Ko}=Ht(),zo={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 dm(){let t=Ko();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&&zo[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 zo[o])s.push(`- ${i}`)}}return s.join(`
|
|
283
|
+
`)}function fm(t){let e=Ko();return Object.values(e).some(s=>s.os&&s.os.startsWith(t))}function pm(){return Object.keys(Ko())}xc.exports={getServerContext:dm,hasServerOS:fm,getProfileNames:pm,OS_HINTS:zo}});var xs=L((Ey,Sc)=>{var Fe=require("fs").promises,kc=require("fs"),_e=require("path"),ws=require("util").promisify(require("child_process").exec),{C:Ke}=de(),{getMergeConflicts:vc}=St(),{getServerContext:mm}=_c(),hm=new Set(["node_modules",".git",".svn","dist","build","coverage",".nyc_output","__pycache__",".DS_Store",".next",".nuxt",".turbo",".cache","vendor","tmp","temp"]);function gm(t){try{return kc.readFileSync(t,"utf-8").split(`
|
|
284
|
+
`).map(s=>s.trim()).filter(s=>s&&!s.startsWith("#")&&!s.startsWith("!")).map(s=>s.replace(/\/$/,""))}catch{return[]}}function $m(t,e){for(let s of e)if(s===t||s.includes("*")&&new RegExp("^"+s.replace(/\./g,"\\.").replace(/\*/g,".*")+"$").test(t))return!0;return!1}function ym(t,{maxDepth:e=3,maxFiles:s=200,giPatterns:n=[]}={}){let o=_e.join(t,".gitignore"),r=[...n,...gm(o)],i=0,c=[_e.basename(t)+"/"];function l(u,d,p){if(p>e||i>=s)return;let f;try{f=kc.readdirSync(u,{withFileTypes:!0})}catch{return}f.sort((m,g)=>m.isDirectory()!==g.isDirectory()?m.isDirectory()?-1:1:m.name.localeCompare(g.name));let h=f.filter(m=>!(hm.has(m.name)||m.name.startsWith(".")&&m.name!==".env.example"||$m(m.name,r)));for(let m=0;m<h.length;m++){if(i>=s){c.push(`${d}\u2514\u2500\u2500 \u2026 (truncated)`);break}let g=h[m],y=m===h.length-1,$=y?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",x=d+(y?" ":"\u2502 "),S=g.isDirectory()?g.name+"/":g.name;c.push(`${d}${$}${S}`),i++,g.isDirectory()&&l(_e.join(u,g.name),x,p+1)}}return l(t,"",1),c.join(`
|
|
285
|
+
`)}var Yo=new Map,zt=new Map,bs=null,wm=3e4;async function mt(t){try{return await t()}catch{return null}}async function bm(){if(!bs||Date.now()>bs)return!1;let t=[_e.join(process.cwd(),"package.json"),_e.join(process.cwd(),"README.md"),_e.join(process.cwd(),".gitignore")];for(let e of t)try{let s=await Fe.stat(e),n=zt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{if(zt.has(e))return!1}try{let e=_e.join(process.cwd(),".git","HEAD"),s=await Fe.stat(e),n=zt.get(e);if(!n||s.mtimeMs!==n)return!1}catch{}return!0}async function xm(){let t=[_e.join(process.cwd(),"package.json"),_e.join(process.cwd(),"README.md"),_e.join(process.cwd(),".gitignore"),_e.join(process.cwd(),".git","HEAD")];for(let e of t)try{let s=await Fe.stat(e);zt.set(e,s.mtimeMs)}catch{zt.delete(e)}}async function _m(t){let e="fileContext",s=Yo.get(e),n=!1;if(s&&await bm()&&(n=!0),!n){let u=[],d=_e.join(t,"package.json");if(await mt(()=>Fe.access(d).then(()=>!0).catch(()=>!1)))try{let y=await Fe.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 f=_e.join(t,"README.md");if(await mt(()=>Fe.access(f).then(()=>!0).catch(()=>!1))){let $=(await Fe.readFile(f,"utf-8")).split(`
|
|
285
286
|
`).slice(0,50);u.push(`README (first 50 lines):
|
|
286
|
-
${
|
|
287
|
-
`)}`)}let
|
|
288
|
-
${
|
|
287
|
+
${$.join(`
|
|
288
|
+
`)}`)}let m=_e.join(t,".gitignore");if(await mt(()=>Fe.access(m).then(()=>!0).catch(()=>!1))){let y=await Fe.readFile(m,"utf-8");u.push(`GITIGNORE:
|
|
289
|
+
${y.trim()}`)}s=u.join(`
|
|
289
290
|
|
|
290
|
-
`),
|
|
291
|
-
${
|
|
291
|
+
`),Yo.set(e,s),bs=Date.now()+wm,await xm()}let o=[s],[r,i,c,l]=await Promise.all([mt(async()=>{let{stdout:u}=await ws("git branch --show-current",{cwd:t,timeout:5e3});return u.trim()}),mt(async()=>{let{stdout:u}=await ws("git status --short",{cwd:t,timeout:5e3});return u.trim()}),mt(async()=>{let{stdout:u}=await ws("git log --oneline -5",{cwd:t,timeout:5e3});return u.trim()}),vc()]);if(r&&o.push(`GIT BRANCH: ${r}`),i&&o.push(`GIT STATUS:
|
|
292
|
+
${i}`),c&&o.push(`RECENT COMMITS:
|
|
292
293
|
${c}`),l&&l.length>0){let u=l.map(d=>` ${d.file}`).join(`
|
|
293
|
-
`);
|
|
294
|
-
${u}`)}try{let u=
|
|
294
|
+
`);o.push(`MERGE CONFLICTS (resolve before editing these files):
|
|
295
|
+
${u}`)}try{let u=mm();u&&o.push(u)}catch{}return o.join(`
|
|
295
296
|
|
|
296
|
-
`)}async function
|
|
297
|
-
${e}`);let
|
|
298
|
-
${
|
|
297
|
+
`)}async function km(t){let e=_e.join(t,"package.json"),s="";if(await mt(()=>Fe.access(e).then(()=>!0).catch(()=>!1)))try{let i=await Fe.readFile(e,"utf-8"),c=JSON.parse(i);s=`${c.name||"?"} v${c.version||"?"}`}catch{}let[o,r]=await Promise.all([mt(async()=>{let{stdout:i}=await ws("git branch --show-current",{cwd:t,timeout:5e3});return i.trim()}),vc()]);if(s&&console.log(`${Ke.dim} project: ${s}${Ke.reset}`),o&&console.log(`${Ke.dim} branch: ${o}${Ke.reset}`),r&&r.length>0){console.log(`${Ke.red} \u26A0 ${r.length} unresolved merge conflict(s):${Ke.reset}`);for(let i of r)console.log(`${Ke.red} ${i.file}${Ke.reset}`);console.log(`${Ke.yellow} \u2192 Resolve conflicts before starting tasks${Ke.reset}`)}console.log()}Sc.exports={gatherProjectContext:_m,printContext:km,generateFileTree:ym,_clearContextCache:()=>{Yo.clear(),zt.clear(),bs=null}}});var Ct=L((Ty,Cc)=>{var ot=require("fs"),Jo=require("path");function _s(){return Jo.join(process.cwd(),".nex","sessions")}function Ec(){let t=_s();ot.existsSync(t)||ot.mkdirSync(t,{recursive:!0})}function Vo(t){let e=t.replace(/[^a-zA-Z0-9_-]/g,"_").substring(0,100);return Jo.join(_s(),`${e}.json`)}function Xo(t,e,s={}){Ec();let n=Vo(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 ot.writeFileSync(n,JSON.stringify(o,null,2),"utf-8"),{path:n,name:t}}function Tc(t){let e=Vo(t);if(!ot.existsSync(e))return null;try{return JSON.parse(ot.readFileSync(e,"utf-8"))}catch{return null}}function Rc(){Ec();let t=_s(),e=ot.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(ot.readFileSync(Jo.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 vm(t){let e=Vo(t);return ot.existsSync(e)?(ot.unlinkSync(e),!0):!1}function Sm(){let t=Rc();return t.length===0?null:Tc(t[0].name)}var Rt=null,st=null,En=null;function Em(t,e={}){t.length!==0&&(Rt&&clearTimeout(Rt),st=t,En=e||{},Rt=setTimeout(()=>{st&&st.length>0&&Xo("_autosave",st,En),Rt=null,st=null,En=null},5e3))}function Tm(){Rt&&(clearTimeout(Rt),Rt=null),st&&st.length>0&&(Xo("_autosave",st,En),st=null,En=null)}Cc.exports={saveSession:Xo,loadSession:Tc,listSessions:Rc,deleteSession:vm,getLastSession:Sm,autoSave:Em,flushAutoSave:Tm,_getSessionsDir:_s}});var ht=L((Ry,Lc)=>{var rt=require("fs"),ks=require("path"),Rm=require("os");function Qo(){return ks.join(process.cwd(),".nex","memory")}function Zo(){return ks.join(Qo(),"memory.json")}function Cm(){return ks.join(process.cwd(),"NEX.md")}function Ac(){return ks.join(Rm.homedir(),".nex","NEX.md")}function Am(){let t=Qo();rt.existsSync(t)||rt.mkdirSync(t,{recursive:!0})}function vs(){let t=Zo();if(!rt.existsSync(t))return{};try{return JSON.parse(rt.readFileSync(t,"utf-8"))}catch{return{}}}function Oc(t){Am(),rt.writeFileSync(Zo(),JSON.stringify(t,null,2),"utf-8")}function Om(t,e){let s=vs();s[t]={value:e,updatedAt:new Date().toISOString()},Oc(s)}function Nm(t){let e=vs();return e[t]?e[t].value:null}function Mm(t){let e=vs();return t in e?(delete e[t],Oc(e),!0):!1}function Nc(){let t=vs();return Object.entries(t).map(([e,s])=>({key:e,value:s.value,updatedAt:s.updatedAt}))}function Mc(){let t=Ac();if(!rt.existsSync(t))return"";try{return rt.readFileSync(t,"utf-8").trim()}catch{return""}}function Pc(){let t=Cm();if(!rt.existsSync(t))return"";try{return rt.readFileSync(t,"utf-8").trim()}catch{return""}}function Pm(){let t=[],e=Mc();e&&t.push(`GLOBAL INSTRUCTIONS (~/.nex/NEX.md):
|
|
298
|
+
${e}`);let s=Pc();s&&t.push(`PROJECT INSTRUCTIONS (NEX.md):
|
|
299
|
+
${s}`);let n=Nc();if(n.length>0){let o=n.map(r=>` ${r.key}: ${r.value}`).join(`
|
|
299
300
|
`);t.push(`PROJECT MEMORY:
|
|
300
|
-
${
|
|
301
|
+
${o}`)}return t.join(`
|
|
301
302
|
|
|
302
|
-
`)}
|
|
303
|
-
${
|
|
304
|
-
`);for(let n=0;n<t.steps.length;n++){let
|
|
305
|
-
`)}function
|
|
303
|
+
`)}Lc.exports={remember:Om,recall:Nm,forget:Mm,listMemories:Nc,loadGlobalInstructions:Mc,loadProjectInstructions:Pc,getMemoryContext:Pm,_getMemoryDir:Qo,_getMemoryFile:Zo,_getGlobalNexMdPath:Ac}});var Tn=L((Ay,Dc)=>{var At=require("fs"),er=require("path"),{C:Cy}=de(),Ss={bash:"ask",read_file:"allow",write_file:"ask",edit_file:"ask",list_directory:"allow",search_files:"allow",glob:"allow",grep:"allow",patch_file:"ask",web_fetch:"allow",web_search:"allow",ask_user:"allow",task_list:"allow",spawn_agents:"ask"},Kt={...Ss};function Ic(){let t=er.join(process.cwd(),".nex","config.json");if(At.existsSync(t))try{let e=JSON.parse(At.readFileSync(t,"utf-8"));e.permissions&&(Kt={...Ss,...e.permissions})}catch{}}function Lm(){let t=er.join(process.cwd(),".nex"),e=er.join(t,"config.json"),s={};if(At.existsSync(e))try{s=JSON.parse(At.readFileSync(e,"utf-8"))}catch{s={}}s.permissions=Kt,At.existsSync(t)||At.mkdirSync(t,{recursive:!0}),At.writeFileSync(e,JSON.stringify(s,null,2),"utf-8")}function qc(t){return Kt[t]||"ask"}function Im(t,e){return["allow","ask","deny"].includes(e)?(Kt[t]=e,!0):!1}function qm(t){return qc(t)}function Dm(){return Object.entries(Kt).map(([t,e])=>({tool:t,mode:e}))}function jm(){Kt={...Ss}}Ic();Dc.exports={getPermission:qc,setPermission:Im,checkPermission:qm,listPermissions:Dm,loadPermissions:Ic,savePermissions:Lm,resetPermissions:jm,DEFAULT_PERMISSIONS:Ss}});var Mt=L((Ny,Bc)=>{var Nt=require("fs"),Es=require("path"),Oy=require("readline"),{C:X}=de(),K=null,nr=!1,sr=null,jc=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 Ts(){return Es.join(process.cwd(),".nex","plans")}function Fc(){let t=Ts();Nt.existsSync(t)||Nt.mkdirSync(t,{recursive:!0})}function Fm(t,e=[]){return K={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()},K}function Um(){return K}function Wm(t){nr=t}function Bm(){return nr}function Hm(){return!K||K.status!=="draft"?!1:(K.status="approved",K.updatedAt=new Date().toISOString(),!0)}function Gm(){return!K||K.status!=="approved"?!1:(K.status="executing",!0)}function tr(t,e){return!K||t<0||t>=K.steps.length?!1:(K.steps[t].status=e,K.updatedAt=new Date().toISOString(),K.steps.every(s=>s.status==="done"||s.status==="skipped")&&(K.status="completed"),!0)}function zm(t){if(!t)return`${X.dim}No active plan${X.reset}`;let e={draft:`${X.yellow}DRAFT${X.reset}`,approved:`${X.green}APPROVED${X.reset}`,executing:`${X.blue}EXECUTING${X.reset}`,completed:`${X.green}COMPLETED${X.reset}`},s=[];s.push(`
|
|
304
|
+
${X.bold}${X.cyan}Plan: ${t.task}${X.reset}`),s.push(`${X.dim}Status: ${e[t.status]||t.status}${X.reset}
|
|
305
|
+
`);for(let n=0;n<t.steps.length;n++){let o=t.steps[n],r;switch(o.status){case"done":r=`${X.green}\u2713${X.reset}`;break;case"in_progress":r=`${X.blue}\u2192${X.reset}`;break;case"skipped":r=`${X.dim}\u25CB${X.reset}`;break;default:r=`${X.dim} ${X.reset}`}s.push(` ${r} ${X.bold}Step ${n+1}:${X.reset} ${o.description}`),o.files.length>0&&s.push(` ${X.dim}Files: ${o.files.join(", ")}${X.reset}`)}return s.push(""),s.join(`
|
|
306
|
+
`)}function Km(t){if(t||(t=K),!t)return null;Fc();let e=Es.join(Ts(),`${t.name}.json`);return Nt.writeFileSync(e,JSON.stringify(t,null,2),"utf-8"),e}function Ym(t){let e=Es.join(Ts(),`${t}.json`);if(!Nt.existsSync(e))return null;try{let s=JSON.parse(Nt.readFileSync(e,"utf-8"));return K=s,s}catch{return null}}function Jm(){Fc();let t=Ts(),e=Nt.readdirSync(t).filter(n=>n.endsWith(".json")),s=[];for(let n of e)try{let o=JSON.parse(Nt.readFileSync(Es.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 Vm(t){if(!t)return[];let e=[],s=t.match(/##\s+Steps?\s*\n([\s\S]*?)(?:\n##|\s*$)/i),n=s?s[1]:t,o=/^\s*(\d+)[.)]\s+(.+)/gm,r;for(;(r=o.exec(n))!==null;){let c=r[2].trim().replace(/^\*\*What\*\*:\s*/i,"").replace(/^\*\*\d+\.\*\*\s*/,"").replace(/\*\*/g,"").trim();c.length>3&&e.push({description:c,files:[],status:"pending"})}if(e.length===0){let i=/\*\*Step\s+\d+[:.]\*\*\s*(.+)/gi;for(;(r=i.exec(t))!==null;){let c=r[1].replace(/\*\*/g,"").trim();c.length>3&&e.push({description:c,files:[],status:"pending"})}}if(e.length>0){let i=/\*\*(?:Where|Files?)\*\*:\s*(.+)/gi,c=[...t.matchAll(i)];for(let l=0;l<Math.min(e.length,c.length);l++){let u=c[l][1];e[l].files=u.split(/[,\s]+/).filter(d=>/[./]/.test(d)).slice(0,5)}}return e}function Xm(t){sr=t}function Qm(){return sr}function Zm(){K=null,nr=!1,sr=null,sh()}function eh(){return`
|
|
306
307
|
PLAN MODE ACTIVE: You are in analysis-only mode. You MUST NOT execute any changes.
|
|
307
308
|
|
|
308
309
|
# Allowed Tools (read-only)
|
|
309
|
-
You may ONLY use these tools: ${[...
|
|
310
|
+
You may ONLY use these tools: ${[...jc].join(", ")}
|
|
310
311
|
Any other tool call will be blocked and returned with an error.
|
|
311
312
|
|
|
312
313
|
# Analysis Phase
|
|
@@ -337,55 +338,55 @@ Bullet list of potential issues and mitigations.
|
|
|
337
338
|
# Important
|
|
338
339
|
- Order steps by dependency (later steps may depend on earlier ones).
|
|
339
340
|
- After presenting the plan, tell the user to type \`/plan approve\` to proceed.
|
|
340
|
-
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var
|
|
341
|
-
`),
|
|
342
|
-
`)}function
|
|
343
|
-
`)}function
|
|
344
|
-
`))!==-1;){let n=this.buffer.substring(0,
|
|
341
|
+
- Do NOT make any file changes \u2014 your role is analysis and planning only.`}var Ot=0;function th(){!K||K.status!=="executing"||(Ot>0&&tr(Ot-1,"done"),Ot<K.steps.length&&(tr(Ot,"in_progress"),Ot++))}function nh(){if(!K||K.status!=="executing"||K.steps.length===0)return null;let t=Math.min(Ot,K.steps.length),e=K.steps.length,s=Math.max(0,t-1),n=K.steps[s]?.description||"";return{current:t,total:e,description:n}}function sh(){Ot=0}var Uc=["interactive","semi-auto","autonomous"],Wc="interactive";function oh(t){return Uc.includes(t)?(Wc=t,!0):!1}function rh(){return Wc}Bc.exports={createPlan:Fm,getActivePlan:Um,setPlanMode:Wm,isPlanMode:Bm,approvePlan:Hm,startExecution:Gm,updateStep:tr,formatPlan:zm,savePlan:Km,loadPlan:Ym,listPlans:Jm,clearPlan:Zm,getPlanModePrompt:eh,setPlanContent:Xm,getPlanContent:Qm,extractStepsFromText:Vm,advancePlanStep:th,getPlanStepInfo:nh,PLAN_MODE_ALLOWED_TOOLS:jc,setAutonomyLevel:oh,getAutonomyLevel:rh,AUTONOMY_LEVELS:Uc}});var Zc=L((My,Qc)=>{var{C:w}=de();function ih(t){if(!t)return"";let e=t.split(`
|
|
342
|
+
`),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(` ${rr(r,o)}`);continue}if(r.startsWith("### ")){s.push(`${w.bold}${w.cyan} ${Pt(r.substring(4))}${w.reset}`);continue}if(r.startsWith("## ")){s.push(`${w.bold}${w.cyan} ${Pt(r.substring(3))}${w.reset}`);continue}if(r.startsWith("# ")){s.push(`${w.bold}${w.cyan}${Pt(r.substring(2))}${w.reset}`);continue}if(/^\s*[-*]\s/.test(r)){let i=r.match(/^(\s*)/)[1],c=r.replace(/^\s*[-*]\s/,"");s.push(`${i}${w.cyan}\u2022${w.reset} ${Lt(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} ${Lt(i[3])}`);continue}}s.push(Lt(r))}return s.join(`
|
|
343
|
+
`)}function Pt(t){return t.replace(/\*\*([^*]+)\*\*/g,"$1").replace(/\*([^*]+)\*/g,"$1").replace(/__([^_]+)__/g,"$1").replace(/_([^_]+)_/g,"$1").replace(/`([^`]+)`/g,"$1")}function Lt(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 rr(t,e){return t?["js","javascript","ts","typescript","jsx","tsx"].includes(e)||!e?Hc(t):e==="bash"||e==="sh"||e==="shell"||e==="zsh"?Gc(t):e==="json"||e==="jsonc"?zc(t):e==="python"||e==="py"?Kc(t):e==="go"||e==="golang"?Yc(t):e==="rust"||e==="rs"?Jc(t):e==="css"||e==="scss"||e==="less"?Vc(t):e==="html"||e==="xml"||e==="svg"||e==="htm"?Xc(t):t:""}function Hc(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 Gc(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 zc(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 Kc(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 Yc(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 Jc(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 Vc(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 Xc(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 ah(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(`
|
|
344
|
+
`)}function ch(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 or=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(),100))}_renderCursor(){let s=[0,1,2,3,4,3,2,1],n=s[this._cursorFrame%s.length],o="";for(let r=0;r<5;r++)o+=r===n?"\x1B[36m\u25CF\x1B[0m":" ";this._cursorWrite(`\x1B[2K\r${o}`),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(`
|
|
345
|
+
`))!==-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(),100))}flush(){this.stopCursor(),this.buffer&&(this._renderLine(this.buffer),this.buffer=""),this.inCodeBlock&&(this._safeWrite(`${w.dim}${"\u2500".repeat(40)}${w.reset}
|
|
345
346
|
`),this.inCodeBlock=!1,this.codeBlockLang="")}_renderLine(e){if(e.trim().startsWith("```")){if(this.inCodeBlock)this._safeWrite(`${w.dim}${"\u2500".repeat(40)}${w.reset}
|
|
346
|
-
`),this.inCodeBlock=!1,this.codeBlockLang="";else{this.inCodeBlock=!0,this.codeBlockLang=e.trim().substring(3).trim();let
|
|
347
|
-
`)}return}if(this.inCodeBlock){this._safeWrite(` ${
|
|
348
|
-
`);return}if(e.startsWith("### ")){this._safeWrite(`${w.bold}${w.cyan} ${
|
|
349
|
-
`);return}if(e.startsWith("## ")){this._safeWrite(`${w.bold}${w.cyan} ${
|
|
350
|
-
`);return}if(e.startsWith("# ")){this._safeWrite(`${w.bold}${w.cyan}${
|
|
351
|
-
`);return}if(/^\s*[-*]\s/.test(e)){let
|
|
352
|
-
`);return}if(/^\s*\d+\.\s/.test(e)){let
|
|
353
|
-
`);return}}this._safeWrite(`${
|
|
354
|
-
`)}};
|
|
347
|
+
`),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}
|
|
348
|
+
`)}return}if(this.inCodeBlock){this._safeWrite(` ${rr(e,this.codeBlockLang)}
|
|
349
|
+
`);return}if(e.startsWith("### ")){this._safeWrite(`${w.bold}${w.cyan} ${Pt(e.substring(4))}${w.reset}
|
|
350
|
+
`);return}if(e.startsWith("## ")){this._safeWrite(`${w.bold}${w.cyan} ${Pt(e.substring(3))}${w.reset}
|
|
351
|
+
`);return}if(e.startsWith("# ")){this._safeWrite(`${w.bold}${w.cyan}${Pt(e.substring(2))}${w.reset}
|
|
352
|
+
`);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} ${Lt(n)}
|
|
353
|
+
`);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} ${Lt(s[3])}
|
|
354
|
+
`);return}}this._safeWrite(`${Lt(e)}
|
|
355
|
+
`)}};Qc.exports={renderMarkdown:ih,renderInline:Lt,stripHeadingMarkers:Pt,highlightCode:rr,highlightJS:Hc,highlightBash:Gc,highlightJSON:zc,highlightPython:Kc,highlightGo:Yc,highlightRust:Jc,highlightCSS:Vc,highlightHTML:Xc,renderTable:ah,renderProgress:ch,StreamRenderer:or}});var cr=L((Py,sl)=>{var{execSync:lh}=require("child_process"),ir=require("path"),Rn=require("fs"),ar=["pre-tool","post-tool","pre-commit","post-response","session-start","session-end"];function el(){return ir.join(process.cwd(),".nex","hooks")}function uh(){return ir.join(process.cwd(),".nex","config.json")}function tl(){let t=uh();if(!Rn.existsSync(t))return{};try{return JSON.parse(Rn.readFileSync(t,"utf-8")).hooks||{}}catch{return{}}}function Rs(t){if(!ar.includes(t))return[];let e=[],s=el(),n=ir.join(s,t);Rn.existsSync(n)&&e.push(n);let o=tl();if(o[t]){let r=Array.isArray(o[t])?o[t]:[o[t]];e.push(...r)}return e}function nl(t,e={},s=3e4){try{return{success:!0,output:lh(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 dh(t,e={}){let s=Rs(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=nl(r,n);if(o.push({command:r,...i}),!i.success&&t.startsWith("pre-"))break}return o}function fh(t){return Rs(t).length>0}function ph(){let t=[];for(let e of ar){let s=Rs(e);s.length>0&&t.push({event:e,commands:s})}return t}function mh(){let t=el();return Rn.existsSync(t)||Rn.mkdirSync(t,{recursive:!0}),t}sl.exports={HOOK_EVENTS:ar,loadHookConfig:tl,getHooksForEvent:Rs,executeHook:nl,runHooks:dh,hasHooks:fh,listHooks:ph,initHooksDir:mh}});var fe=L((jy,gl)=>{var{C:b,Spinner:Yt,TaskProgress:hh,formatToolCall:gh,formatResult:$h,formatToolSummary:ll,formatSectionHeader:lr,setActiveTaskProgress:Ly}=de(),{callStream:yh}=ge(),{parseToolArgs:wh}=Jn(),{executeTool:bh}=Be(),{gatherProjectContext:xh}=xs(),{fitToContext:_h,forceCompress:ur,getUsage:kh,estimateTokens:vh}=De(),{autoSave:Sh,flushAutoSave:Eh}=Ct();function Ye(t){Sh(t),Eh()}var{getMemoryContext:Th}=ht(),{checkPermission:Rh,setPermission:Ch,savePermissions:Ah}=Tn(),{confirm:ul,setAllowAlwaysHandler:Oh}=We(),{isPlanMode:Ms,getPlanModePrompt:Nh,PLAN_MODE_ALLOWED_TOOLS:dl,setPlanContent:Mh,extractStepsFromText:Ph,createPlan:Lh,getActivePlan:Iy,startExecution:qy,advancePlanStep:Ih,getPlanStepInfo:qh}=Mt(),{StreamRenderer:Dh}=Zc(),{runHooks:ol}=cr(),{routeMCPCall:jh,getMCPToolDefinitions:Fh}=ts(),{getSkillInstructions:Uh,getSkillToolDefinitions:Wh,routeSkillCall:Bh}=un(),{trackUsage:Hh}=Ft(),{validateToolArgs:Gh}=wo(),{filterToolsForModel:rl,getModelTier:zh,PROVIDER_DEFAULT_TIER:Dy}=Oo(),{getConfiguredProviders:Kh,getActiveProviderName:Cn,getActiveModelId:Cs,setActiveModel:il,MODEL_EQUIVALENTS:Ps}=ge(),br=require("fs"),xr=require("path"),al=/(?:^|\s)((?:~|\.{1,2})?(?:\/[\w.\-@() ]+)+\.(?:png|jpe?g|gif|webp|bmp|tiff?))(?:\s|$)/gi;function Yh(t){let e=[],s;for(al.lastIndex=0;(s=al.exec(t))!==null;){let n=s[1].trim(),o=n.startsWith("~")?n.replace("~",process.env.HOME||""):xr.resolve(n);br.existsSync(o)&&e.push({raw:n,abs:o})}return e}function Jh(t){let e=br.readFileSync(t),s=xr.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 fl(t){let e=Yh(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}=Jh(n.abs);s.push({type:"image",media_type:r,data:o})}catch{}return s.length>1?s:t}var dr=null,fr=null,pr=null;function Jt(){if(dr===null){let{TOOL_DEFINITIONS:t}=Be();dr=t}return fr===null&&(fr=Wh()),pr===null&&(pr=Fh()),[...dr,...fr,...pr]}var yr=50;function Vh(t){Number.isFinite(t)&&t>0&&(yr=t)}var As=()=>null;function Xh(t){As=t}var An=null,wr=null,Vt=null,Os=new Map,Qh=1e4,Zh=6e3,eg=/\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 tg(t){return!t||typeof t!="string"?t:t.replace(eg,(e,s)=>`${s}=***REDACTED***`)}function ng(t){let e=tg(t);if(vh(e)>Qh)try{let{compressToolResult:n}=De();return n(e,Zh)}catch{return e}return e}function pl(t){try{let{getActiveModel:e}=ge(),s=e(),n=s?`${s.provider}:${s.id}`:"default";if(Os.has(n))return Os.get(n);let o=rl(t);return Os.set(n,o),o}catch{return rl(t)}}function sg(){Os.clear()}async function ml(){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}=ht(),i=r();i&&o.push(`memory:${i}`)}catch{}try{let r=e.join(process.cwd(),".nex","brain");if(br.existsSync(r)){let i=await t.stat(r);o.push(`brain:${i.mtimeMs}`)}}catch{}return o.join("|")}catch{return`fallback:${Date.now()}`}}function og(){An=null,wr=null,Vt=null}var rg=new Set(["spawn_agents"]),mr=5,hr=3,gr=2,ig=parseInt(process.env.NEX_STALE_WARN_MS||"60000",10),ag=parseInt(process.env.NEX_STALE_ABORT_MS||"120000",10),cg=process.env.NEX_STALE_AUTO_SWITCH!=="0";function lg(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{}}Oh(t=>{Ch(t,"allow"),Ah(),console.log(`${b.green} \u2713 ${t}: always allow${b.reset}`)});async function ug(t){let e=t.function.name,s=wh(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(`${b.yellow} \u26A0 ${e}: malformed arguments, sending schema hint${b.reset}`),{callId:n,fnName:e,args:null,canExecute:!1,errorResult:{role:"tool",content:`ERROR: Malformed tool arguments. Could not parse your arguments as JSON.
|
|
355
356
|
Raw input: ${typeof t.function.arguments=="string"?t.function.arguments.substring(0,200):"N/A"}
|
|
356
357
|
|
|
357
358
|
Expected JSON schema for "${e}":
|
|
358
359
|
${u}
|
|
359
360
|
|
|
360
|
-
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let
|
|
361
|
-
`)[0]}${b.reset}`),{callId:n,fnName:e,args:
|
|
362
|
-
...(truncated ${
|
|
363
|
-
`)[0],
|
|
364
|
-
`)}function
|
|
365
|
-
`];n?
|
|
366
|
-
This is a hard requirement. Do NOT fall back to English or any other language for your responses, even if the user writes in a different language first.`),
|
|
361
|
+
Please retry the tool call with valid JSON arguments matching this schema.`,tool_call_id:n}}}let o=Gh(e,s);if(!o.valid)return console.log(`${b.yellow} \u26A0 ${e}: ${o.error.split(`
|
|
362
|
+
`)[0]}${b.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(`${b.dim} \u2713 ${e}: corrected args (${u.join(", ")})${b.reset}`)}if(Ms()&&!dl.has(e))return console.log(`${b.yellow} \u2717 ${e}: blocked in plan mode${b.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=Rh(e);if(i==="deny")return console.log(`${b.red} \u2717 ${e}: denied by permissions${b.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 ul(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 dg(t,e,s={}){let n=await Bh(t,e);if(n!==null)return n;let o=await jh(t,e);return o!==null?o:bh(t,e,s)}function fg(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 $r(t,e=!1){e||console.log(gh(t.fnName,t.args));let s=ol("pre-tool",{tool_name:t.fnName});if(!e&&s.length>0)for(let f of s)f.success?console.log(`${b.dim} [hook pre-tool] ${f.command} \u2192 ${f.output||"ok"}${b.reset}`):console.log(`${b.yellow} [hook pre-tool] ${f.command} \u2192 ERROR: ${f.error}${b.reset}`);let n=await dg(t.fnName,t.args,{silent:!0,autoConfirm:t.confirmedByUser===!0}),o=String(n??""),r=o.length>5e4?o.substring(0,5e4)+`
|
|
363
|
+
...(truncated ${o.length-5e4} chars)`:o,i=r.split(`
|
|
364
|
+
`)[0],c=i.startsWith("ERROR")||i.includes("CANCELLED")||i.includes("BLOCKED")||t.fnName==="spawn_agents"&&!/✓ Agent/.test(r)&&/✗ Agent/.test(r),l=ll(t.fnName,t.args,r,c);e||(console.log($h(r)),console.log(l));let u=ol("post-tool",{tool_name:t.fnName});if(!e&&u.length>0)for(let f of u)f.success?console.log(`${b.dim} [hook post-tool] ${f.command} \u2192 ${f.output||"ok"}${b.reset}`):console.log(`${b.yellow} [hook post-tool] ${f.command} \u2192 ERROR: ${f.error}${b.reset}`);return{msg:{role:"tool",content:ng(r),tool_call_id:t.callId},summary:l}}async function pg(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],p=fg(d.fnName,d.args);u=`\u25CF ${d.fnName}${p?`(${p})`:""}`}else{let d=l.map(p=>p.fnName).join(", ");u=`\u25CF ${l.length} tools: ${d.length>60?d.substring(0,57)+"\u2026":d}`}i=new Yt(u),i.start()}}async function c(){if(r.length!==0){if(r.length===1){let l=r[0],{msg:u,summary:d}=await $r(t[l],e);n[l]=u,o.push(d)}else{let l=r.map(d=>$r(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(ll(u.fnName,u.args||{},u.errorResult.content,!0));continue}if(rg.has(u.fnName)){await c(),u.fnName==="spawn_agents"&&i&&(i.stop(),i=null);let{msg:d,summary:p}=await $r(u,e);n[l]=d,o.push(p)}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 Y=[],cl=300,Ns=[];function mg(t){Ns.push(t.trim())}function hg(){return Ns.length===0?null:Ns.splice(0,Ns.length).join(`
|
|
365
|
+
`)}function gg(){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)
|
|
366
|
+
`];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, paste the COMPLETE Makefile code DIRECTLY in your text response \u2014 every target, recipe, dependency, and .PHONY line. Writing the Makefile with a tool does NOT count as showing it. The Makefile MUST appear verbatim in your chat text as a code block, even if you also wrote it to a file. Never describe structure without showing the actual code. CRITICAL: use EXACTLY the command specified \u2014 if the task says "runs jest", write "jest" in the recipe, NEVER "npm test". npm test is NOT jest. Recipes need real TAB indentation. ONE .PHONY line listing ALL phony targets.'),o.push(" \u2022 For dataclasses, paste the COMPLETE dataclass code DIRECTLY in your text response \u2014 @dataclass decorator, all fields with types and defaults, full __post_init__ validation. Writing the file with a tool does NOT count as showing the code. The code MUST appear verbatim in your chat text, even if you also wrote it to a file."),o.push(" \u2022 For cron expressions, re-read the exact time boundaries in the task before writing. If asked for 8-18h, the range is 8,9,...,18 \u2014 write exactly what was asked, not an approximation."),o.push(' \u2022 When a task explicitly specifies a tool (e.g., "use tsc"), NEVER mention alternatives (e.g., "swc build") \u2014 use exactly what was requested.'),o.push(' \u2022 In Makefile prerequisites, NEVER use shell glob patterns like src/**/*.ts \u2014 make does not expand these natively. Keep prerequisite lists explicit or omit them. When a Makefile target says "runs jest", call jest directly in the recipe (not npm test).'),o.push(" \u2022 For bash in-place text replacements with backups: use ONLY ONE backup method \u2014 either sed -i.bak (let sed create the backup) OR cp file file.bak followed by sed -i (no extension). Never use both cp and sed -i.bak together \u2014 that produces redundant double backups (file.bak and file.bak.bak)."),o.push(" \u2022 For iterative array-flattening (flattenDeep): use push() and reverse() at the end \u2014 NEVER unshift(). unshift is O(n) per call making the whole function O(n^2). The iterative version MUST use a loop (while/for) and an explicit stack array \u2014 zero recursive calls. If a function calls itself, it is recursive regardless of its name. Never label a recursive function as iterative."),o.push(" \u2022 FORBIDDEN: when refactoring callbacks to async/await, NEVER write try { ... } catch(e) { throw e } \u2014 this is an explicit anti-pattern. WRONG: async function f() { try { const d = await readFile(..); await writeFile(.., d); } catch(e) { throw e; } } \u2014 RIGHT: async function f() { const d = await readFile(..); await writeFile(.., d); } \u2014 omit the try-catch entirely, let rejections propagate."),o.push(' \u2022 Docker HEALTHCHECK: always include --start-period=30s (or appropriate startup time) so the container has time to initialise before failures are counted. Also note that curl may not be available in minimal Node.js images \u2014 offer wget or "node -e" as alternatives.'),o.push(' \u2022 When fixing a bash word-splitting bug like "for f in $(ls *.txt)": replace the entire $(ls *.txt) with a bare glob directly \u2014 "for f in *.txt". The fix is eliminating the ls command and $() subshell entirely. Emphasise this in the explanation: the glob in the for loop prevents word splitting because the shell expands the glob into separate words before the loop \u2014 there is no subshell output to split. CRITICAL: NEVER suggest "ls -N" or any ls variant as a fix \u2014 ls -N outputs filenames one per line, but word splitting still occurs on each line when used in a subshell expansion. The only correct fix is the bare glob pattern.');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(`
|
|
367
|
+
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(`
|
|
367
368
|
`)+`
|
|
368
369
|
|
|
369
|
-
`}function
|
|
370
|
+
`}function $g(){if(Vt!==null)return Vt;try{let e=Kh().flatMap(o=>o.models.map(r=>({spec:`${o.name}:${r.id}`,tier:zh(r.id,o.name),name:r.name})));if(e.length<2)return Vt="","";let s={full:"complex tasks (refactor, implement, generate)",standard:"regular tasks (edit, fix, analyze)",essential:"simple tasks (read, search, list)"},n=`
|
|
370
371
|
# Sub-Agent Model Routing
|
|
371
372
|
|
|
372
373
|
`;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 |
|
|
373
374
|
|---|---|---|
|
|
374
|
-
`;for(let
|
|
375
|
-
`;return
|
|
375
|
+
`;for(let o of e)n+=`| ${o.spec} | ${o.tier} | ${s[o.tier]||o.tier} |
|
|
376
|
+
`;return Vt=n,n}catch(t){return process.env.NEX_DEBUG&&console.error("[agent] model routing guide failed:",t.message),Vt="",""}}async function hl(){let t=await ml();if(An!==null&&t===wr)return An;let e=await xh(process.cwd()),s=Th(),n=Uh(),o=Ms()?Nh():"",r=gg();return An=`You are Nex Code, an expert coding assistant. You help with programming tasks by reading, writing, and editing files, running commands, and answering questions.
|
|
376
377
|
|
|
377
378
|
WORKING DIRECTORY: ${process.cwd()}
|
|
378
379
|
All relative paths resolve from this directory.
|
|
379
380
|
PROJECT CONTEXT:
|
|
380
381
|
${e}
|
|
381
|
-
${
|
|
382
|
-
${
|
|
382
|
+
${s?`
|
|
383
|
+
${s}
|
|
383
384
|
`:""}${n?`
|
|
384
385
|
${n}
|
|
385
|
-
`:""}${
|
|
386
|
-
${
|
|
386
|
+
`:""}${o?`
|
|
387
|
+
${o}
|
|
387
388
|
`:""}
|
|
388
|
-
${
|
|
389
|
+
${r?`${r}
|
|
389
390
|
`:""}# Core Behavior
|
|
390
391
|
|
|
391
392
|
- You can use tools OR respond with text. For simple questions, answer directly.
|
|
@@ -404,9 +405,10 @@ MANDATORY RULE: After ANY tool call that gathers information (bash, read_file, g
|
|
|
404
405
|
CODE DISPLAY RULE: Always show actual code examples, not just descriptions. When explaining code:
|
|
405
406
|
\u2022 Show the complete code snippet, not just describe it
|
|
406
407
|
\u2022 Include file paths and line numbers (e.g., "src/app.js:42")
|
|
407
|
-
\u2022 For regex patterns, show both the pattern and example matches.
|
|
408
|
-
\u2022 For Makefiles
|
|
409
|
-
\u2022 For dataclasses, show the
|
|
408
|
+
\u2022 For regex patterns, show both the pattern and example matches. Be precise \u2014 test the pattern mentally. When rewriting for readability, use named constants or a commented breakdown (e.g. const OCTET = ...), NOT named capture groups \u2014 named group syntax varies by engine and is a frequent source of errors. NEVER claim functional equivalence without verifying edge cases (e.g. leading zeros, boundary values).
|
|
409
|
+
\u2022 For Makefiles: (1) Output the COMPLETE Makefile in a fenced \`\`\`makefile code block IN YOUR TEXT first \u2014 before any tool calls. (2) Then optionally write it to disk. FORBIDDEN: using write_file for a Makefile and then only describing it in text \u2014 the code block in text is mandatory. The user CANNOT see write_file output. (3) Use EXACTLY the command from the description: "runs jest" \u2192 recipe is "jest" (NOT "npm test", NOT "npx jest"); "runs tsc" \u2192 recipe is "tsc". (4) Never suggest alternatives to the specified tool \u2014 if the task says tsc, only tsc appears in the Makefile.
|
|
410
|
+
\u2022 For dataclasses, show the COMPLETE implementation \u2014 all fields with types, __post_init__ validation, and any defaults. Never describe without showing the code.
|
|
411
|
+
\u2022 For cron expressions, quote the exact time constraint from the task verbatim, then write the expression. Verify boundary values (e.g., "8-18h" \u2192 hours 8 through 18 inclusive).
|
|
410
412
|
|
|
411
413
|
- Use markdown formatting: **bold** for key points, headers for sections, bullet lists for multiple items, \`code\` for identifiers. The terminal renders markdown with syntax highlighting.
|
|
412
414
|
- Structure longer responses with headers (## Section) so the user can scan quickly.
|
|
@@ -417,13 +419,16 @@ Response patterns by request type:
|
|
|
417
419
|
- **Simple questions ("what does X do?")**: Answer directly without tools when you have enough context.
|
|
418
420
|
- **Ambiguous requests**: When a request is vague AND lacks sufficient detail to act (e.g. just "optimize this" or "improve performance" with no further context), ask clarifying questions using ask_user. However, if the user's message already contains specific details \u2014 file names, concrete steps, exercises, numbers, examples \u2014 proceed directly without asking. Only block when you genuinely cannot determine what to do without more information. When the user's request is ambiguous or could be interpreted in multiple ways, call the ask_user tool BEFORE starting work. Provide 2-3 specific, actionable options that cover the most likely intents. Do NOT ask open-ended questions in chat \u2014 always use ask_user with concrete options.
|
|
419
421
|
- **Server/SSH commands**: After running remote commands, ALWAYS present the results: service status, log errors, findings.
|
|
420
|
-
- **Regex explanations**:
|
|
422
|
+
- **Regex explanations**: Show the original pattern, test it with concrete examples, then provide BOTH: (1) a named-constant rewrite (e.g. const OCTET = '...'; const IP_RE = new RegExp(...)) AND (2) a step-by-step validation function that replaces the regex entirely using split/conditions \u2014 this is often the most readable alternative. Named groups are engine-specific \u2014 prefer named constants or the validation function. Verify the rewrite matches all edge cases of the original before claiming equivalence.
|
|
421
423
|
- **Encoding/buffer handling**: When discussing file operations, mention utf8 encoding or buffer considerations. Use correct flags like --zero instead of -0 for null-delimited output.
|
|
422
|
-
- **Hook implementations**:
|
|
423
|
-
- **Memory leak explanations**:
|
|
424
|
-
- **Makefile tasks**:
|
|
425
|
-
- **Dataclass definitions**:
|
|
424
|
+
- **Hook implementations (Git, bash scripts)**: Answer ENTIRELY in text \u2014 do NOT use any tools. Write the complete, correct script in your first and only response. Think through ALL edge cases (e.g. console.log in comments or strings vs real calls) before writing \u2014 handle them in the initial script, never iterate. Show the full file content and how to install it (chmod +x, correct .git/hooks/ path). For pre-commit hooks that check staged content: always use 'git diff --cached' to get only staged changes \u2014 never grep full file content, which would catch unstaged lines. Use '--diff-filter=ACM' to target added/copied/modified files \u2014 NEVER use '--diff-filter=D' (that shows ONLY deleted files, opposite of intent). NEVER use 'set -e' in pre-commit hooks \u2014 grep exits 1 on no match, which kills the entire script under set -e. Use explicit 'if git diff --cached ... | grep -q ...; then' flow control instead, and check exit codes explicitly. REGEX FALSE POSITIVES: When writing a regex to detect calls like console.log(), the pattern must exclude comment lines \u2014 pipe through 'grep -v "^s*//"' before the pattern match so that lines like "// console.log(x)" do not trigger a false positive. CONSOLE METHODS: When a task asks to block console.log, explicitly address whether console.warn, console.error, console.debug, and console.info should also be blocked \u2014 if the intent is "no console output in production", block all console methods with a single pattern like 'console.(log|warn|error|debug|info)'.
|
|
425
|
+
- **Memory leak explanations**: Show the problematic code, then present the primary fix (move emitter.on() outside the loop, registered once) with the original setInterval kept intact for its intended purpose. Then briefly mention 2 alternatives: (1) emitter.once() if only one event needs handling, (2) removeAllListeners() (or emitter.off(event, handler)) BEFORE re-registering inside the loop. CRITICAL for alternative 2: you MUST call removeAllListeners() or off() BEFORE the new emitter.on() \u2014 if you call emitter.on() inside an interval without first removing the previous listener, a new listener accumulates on every tick, which is the same leak as the original. Always show the removal step explicitly. Do NOT replace the setInterval body with an empty callback \u2014 keep the interval doing its original work.
|
|
426
|
+
- **Makefile tasks**: ALWAYS follow this exact order: (1) paste the COMPLETE Makefile in a fenced code block in your text response FIRST, (2) THEN optionally write it to a file with a tool. The user cannot see files you write \u2014 your text response is the ONLY output they receive. Never describe the Makefile in prose \u2014 paste the actual code. Every target, every recipe, every .PHONY line. Use EXACTLY the tools specified (jest means jest directly, not npm test; tsc means tsc). Never put glob patterns like src/**/*.ts in prerequisites \u2014 make does not expand them. MAKEFILE SYNTAX RULES (hard requirements): (a) Recipe lines MUST be indented with a real TAB character \u2014 never spaces; a space-indented recipe causes "missing separator" errors. (b) Declare ALL phony targets in a SINGLE .PHONY line at the top \u2014 NEVER split .PHONY across multiple declarations. (c) NEVER define the same target name twice \u2014 duplicate targets silently override each other and produce contradictory behaviour. (d) Do NOT add @echo lines unless the task explicitly asks for output messages.
|
|
427
|
+
- **Dataclass definitions**: Paste the COMPLETE dataclass code directly in your text response \u2014 @dataclass decorator, all fields with type annotations and defaults, full __post_init__ validation block. The code must appear verbatim in your chat text. Writing a file with a tool does NOT satisfy this \u2014 always also paste the code in text.
|
|
428
|
+
- **Cron expressions**: Before writing each expression, quote the exact constraint from the task, then derive the expression. Double-check boundary values match exactly what was asked. NEVER put cron expressions inside markdown tables \u2014 asterisks (*) in table cells are consumed as bold/italic markers and disappear. Always present each cron expression in its own fenced code block. For "every N minutes between X-Yh": only present both interpretations (inclusive vs. exclusive endpoint) when the task is genuinely ambiguous about whether the endpoint fires. If the task explicitly states "8-18h" or "until 18h" without qualification, write the expression with 8-18 directly \u2014 do NOT second-guess or add a confusing dual-interpretation note that contradicts the explicit request. The note is only appropriate when the task says something like "during business hours" or "until approximately 18h" where intent is unclear.
|
|
429
|
+
- **Express/fetch error handling**: When adding error handling to an Express route that fetches by ID: (1) validate the ID parameter first (check it exists and is a valid format), (2) wrap fetch in try-catch, (3) check response.ok and handle 404 specifically, (4) call next(error) to pass errors to Express error-handling middleware \u2014 do not just send a raw 500 response.
|
|
426
430
|
- **Command suggestions**: Always use correct command flags and syntax. For null-delimited output, use --zero or find/printf instead of non-existent flags like -0.
|
|
431
|
+
- **sed -i portability**: When showing 'sed -i' for in-place file editing, always note the macOS/BSD vs GNU difference: on macOS/BSD, '-i' requires an explicit backup suffix argument (e.g. 'sed -i "" "s/old/new/" file' for no backup, or 'sed -i.bak ...' for a backup); on GNU/Linux, 'sed -i "s/old/new/" file' works without the extra argument. When the user's platform is unknown or macOS, show the macOS-compatible form first. For cross-platform scripts, suggest 'perl -i -pe' as a portable alternative.
|
|
427
432
|
|
|
428
433
|
After completing multi-step tasks, suggest logical next steps (e.g. "You can run npm test to verify" or "Consider committing with /commit").
|
|
429
434
|
|
|
@@ -493,7 +498,7 @@ When performing audits, code reviews, bug hunts, or security reviews:
|
|
|
493
498
|
- Good for: reading multiple files, analyzing separate modules.
|
|
494
499
|
- Bad for: tasks that depend on each other or modify the same file.
|
|
495
500
|
- Max 5 parallel agents.
|
|
496
|
-
${
|
|
501
|
+
${$g()}
|
|
497
502
|
|
|
498
503
|
# Edit Reliability (Critical)
|
|
499
504
|
|
|
@@ -544,23 +549,50 @@ You have access to a persistent knowledge base in .nex/brain/.
|
|
|
544
549
|
- Include tags in frontmatter for better retrieval
|
|
545
550
|
- The user reviews all brain writes via /brain review or git diff
|
|
546
551
|
|
|
547
|
-
`,
|
|
548
|
-
`):[]).filter(
|
|
549
|
-
\u{1F4E6} ${h}${
|
|
550
|
-
${b.dim} ${
|
|
551
|
-
`),
|
|
552
|
-
`+
|
|
553
|
-
`)}catch(
|
|
554
|
-
${b.cyan}${b.bold}Plan ready
|
|
555
|
-
|
|
556
|
-
`))
|
|
557
|
-
`)
|
|
558
|
-
|
|
559
|
-
`),await
|
|
560
|
-
`)
|
|
561
|
-
|
|
552
|
+
`,wr=t,An}function yg(){Y=[]}function wg(){Y.length>cl&&Y.splice(0,Y.length-cl)}function bg(){return Y.length}function xg(){return Y}function _g(t){Y=t}async function kg(){let{execFile:t}=require("child_process"),e=require("fs"),s=process.cwd(),n=(p,f)=>new Promise(h=>{t(p,f,{cwd:s,timeout:3e3},(m,g)=>{h(m?"":(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(`
|
|
553
|
+
`):[]).filter(p=>{let f=p.split(".").pop();return r.has(f)});if(i.length<3)return null;let c={};for(let p of i){let f=p.split(".").pop();c[f]=(c[f]||0)+1}let u=` \u{1F4C1} ${Object.entries(c).sort((p,f)=>f[1]-p[1]).slice(0,4).map(([p,f])=>`${f} .${p}`).join(" \xB7 ")}`,d=xr.join(s,"package.json");if(e.existsSync(d))try{let p=JSON.parse(e.readFileSync(d,"utf-8")),f=Object.keys({...p.dependencies||{},...p.devDependencies||{}});if(f.length>0){let h=f.slice(0,5).join(" \xB7 "),m=f.length>5?` +${f.length-5}`:"";u+=`
|
|
554
|
+
\u{1F4E6} ${h}${m}`}}catch{}return u}function vg(t){if(process.platform==="darwin")try{let{execFileSync:e}=require("child_process");e("osascript",["-e",`display notification "${t.replace(/"/g,'\\"')}" with title "nex-code"`],{timeout:3e3,stdio:"ignore"})}catch{}}function Je(t,e,s,n,o){if(t<1)return;let r=[...e.values()].reduce((l,u)=>l+u,0),i=`\u2500\u2500 ${t} ${t===1?"step":"steps"} \xB7 ${r} ${r===1?"tool":"tools"}`,c=0;if(o){let l=Date.now()-o;c=Math.round(l/1e3),i+=c>=60?` \xB7 ${Math.floor(c/60)}m ${c%60}s`:` \xB7 ${c}s`}if(s.size>0&&(i+=` \xB7 ${s.size} ${s.size===1?"file":"files"} modified`),i+=" \u2500\u2500",console.log(`
|
|
555
|
+
${b.dim} ${i}${b.reset}`),c>=30&&process.stdout.isTTY){let l=s.size>0?`Done \u2014 ${s.size} ${s.size===1?"file":"files"} modified in ${c}s`:`Done \u2014 ${t} ${t===1?"step":"steps"} in ${c}s`;vg(l)}s.size>0?console.log(`${b.dim} \u{1F4A1} /diff \xB7 /commit \xB7 /undo${b.reset}`):n.size>=5&&s.size===0&&t>=3?console.log(`${b.dim} \u{1F4A1} Found issues? Say "fix 1" or "apply all fixes"${b.reset}`):n.size>0&&t>=2&&console.log(`${b.dim} \u{1F4A1} /save \xB7 /clear${b.reset}`)}async function Sg(){if(!process.stdout.isTTY)return{action:"quit"};let t=Cn(),e=Cs(),s=Ps.fast?.[t],n=Ps.strong?.[t],o=s&&s!==e,r=n&&n!==e&&n!==s,i=[];i.push({key:"r",label:`Retry with current model ${b.dim}(${e})${b.reset}`}),o&&i.push({key:"f",label:`Switch to ${b.bold}${s}${b.reset} ${b.dim}\u2014 fast, low latency${b.reset}`,model:s}),r&&i.push({key:"s",label:`Switch to ${b.bold}${n}${b.reset} ${b.dim}\u2014 reliable tool-calling, medium speed${b.reset}`,model:n}),i.push({key:"q",label:`${b.dim}Quit${b.reset}`}),console.log(),console.log(`${b.yellow} Stream stale \u2014 all retries exhausted.${b.reset} What would you like to do?`);for(let c of i)console.log(` ${b.cyan}[${c.key}]${b.reset} ${c.label}`);return process.stdout.write(` ${b.yellow}> ${b.reset}`),new Promise(c=>{let l=process.stdin,u=l.isRaw;l.setRawMode(!0),l.resume(),l.setEncoding("utf8");let d=!1,p=f=>{if(d)return;d=!0,l.removeListener("data",p),l.setRawMode(u||!1),l.pause();let h=f.toLowerCase().trim();if(process.stdout.write(`${h}
|
|
556
|
+
`),f==="")return c({action:"quit"});let m=i.find(g=>g.key===h);!m||m.key==="q"||!m.model&&m.key!=="r"?c({action:"quit"}):m.key==="r"?c({action:"retry"}):c({action:"switch",model:m.model,provider:t})};l.on("data",p)})}async function Eg(t){let e=fl(t);Y.push({role:"user",content:e}),wg();let{setOnChange:s}=ds(),n=null,o=0;s((U,ee)=>{U==="create"?(n&&n.stop(),n=new hh(ee.name,ee.tasks),n.setStats({tokens:o}),n.start()):U==="update"&&n?n.updateTask(ee.id,ee.status):U==="clear"&&n&&(n.stop(),n=null)});let r=await hl(),i=r;try{let{getBrainContext:U}=_n(),ee=await U(t);ee&&(i=r+`
|
|
557
|
+
`+ee+`
|
|
558
|
+
`)}catch(U){process.env.NEX_DEBUG&&console.error("[agent] brain context failed:",U.message)}let c=[{role:"system",content:i},...Y],l=new Yt("Thinking...");l.start();let d=Y.length===1?kg().catch(()=>null):Promise.resolve(null),p=Jt(),[{messages:f,compressed:h,compacted:m,tokensRemoved:g},y]=await Promise.all([_h(c,p),d]),$=kh(c,p);if(l.stop(),y&&console.log(`${b.dim}${y}${b.reset}`),m)console.log(`${b.dim} [context compacted \u2014 summary (~${g} tokens freed)]${b.reset}`);else if(h){let U=$.limit>0?Math.round(g/$.limit*100):0;console.log(`${b.dim} [context compressed \u2014 ~${g} tokens freed (${U}%)]${b.reset}`)}$.percentage>85&&console.log(`${b.yellow} \u26A0 Context ${Math.round($.percentage)}% full \u2014 consider /clear or /save + start fresh${b.reset}`);let x=f,S=0,k=0,v=0,T=0,A=0,E=0,F=new Map,j=new Set,Z=new Set,G=Date.now(),te=new Map,me=3,Pn=5,ye=new Map,It=5,q=8,P=0,B=6,V=10,D,Q=yr,z=0,le=10;e:for(;;){for(D=0;D<Q&&!As()?.aborted;D++){let ee=!0;E>0&&Ih();let be=null;if(n&&n.isActive())n._paused&&n.resume();else if(!n){let R,N=qh();if(N&&N.total>1){let qe=N.description.length>40?N.description.slice(0,37)+"\u2026":N.description;R=`Plan step ${N.current}/${N.total}: ${qe}`}else R=E>0?`Thinking... (step ${E+1})`:"Thinking...";be=new Yt(R),be.start()}let Me=!0,Pe="",we=new Dh,lt,Ws=Date.now(),Ln=!1,Bs=new AbortController,Hr=setInterval(()=>{let R=Date.now()-Ws;if(R>=ag)we._clearCursorLine(),console.log(`${b.yellow} \u26A0 Stream stale for ${Math.round(R/1e3)}s \u2014 aborting and retrying${b.reset}`),Bs.abort();else if(R>=ig&&!Ln){Ln=!0,we._clearCursorLine();let N=Ps.fast?.[Cn()];console.log(`${b.yellow} \u26A0 No tokens received for ${Math.round(R/1e3)}s \u2014 waiting...${b.reset}`),N&&N!==Cs()?console.log(`${b.dim} \u{1F4A1} Will auto-switch to ${N} if no tokens arrive before abort${b.reset}`):N&&console.log(`${b.dim} \u{1F4A1} Ctrl+C to abort and retry${b.reset}`)}},5e3),Le="",Xe=null;try{let R=pl(Jt()),N=Ms()?R.filter(ue=>dl.has(ue.function.name)):R,qe=As(),H=new AbortController;qe&&qe.addEventListener("abort",()=>H.abort(),{once:!0}),Bs.signal.addEventListener("abort",()=>H.abort(),{once:!0}),lt=await yh(x,N,{signal:H.signal,onThinkingToken:()=>{Ws=Date.now(),Ln=!1},onToken:ue=>{Ws=Date.now(),Ln=!1,Le+=ue,process.stdout.isTTY?Xe||(Xe=setTimeout(()=>{Le&&we&&we.push(Le),Le="",Xe=null},50)):(we.push(Le),Le=""),Me&&(n&&!n._paused?n.pause():be&&be.stop(),ee||(ee=!0),we.startCursor(),Me=!1),Pe+=ue}})}catch(R){if(clearInterval(Hr),Xe&&(clearTimeout(Xe),Xe=null),Le&&we&&(we.push(Le),Le=""),n&&!n._paused&&n.pause(),be&&be.stop(),we.stopCursor(),Bs.signal.aborted&&!As()?.aborted){if(v++,v>gr){if(T<1){T++,console.log(`${b.yellow} \u26A0 Stale retries exhausted \u2014 last-resort force-compress...${b.reset}`);let he=Jt(),{messages:Re,tokensRemoved:qt}=ur(x,he);x=Re,console.log(`${b.dim} [force-compressed \u2014 ~${qt} tokens freed]${b.reset}`),v=0,D--;continue}n&&(n.stop(),n=null);let W=await Sg();if(W.action==="quit"){s(null),Je(E,F,j,Z,G),Ye(Y);break}W.action==="switch"&&(il(`${W.provider}:${W.model}`),console.log(`${b.green} \u2713 Switched to ${W.provider}:${W.model}${b.reset}`)),v=0,T=0,D--;continue}let H=v===1?3e3:5e3;if(v>=1&&A<1){A++,console.log(`${b.yellow} \u26A0 Stale retry ${v}/${gr} \u2014 force-compressing before retry...${b.reset}`);let W=Jt(),{messages:he,tokensRemoved:Re}=ur(x,W);if(x=he,Re>0&&console.log(`${b.dim} [force-compressed \u2014 ~${Re} tokens freed]${b.reset}`),cg){let qt=Ps.fast?.[Cn()];qt&&qt!==Cs()&&(il(`${Cn()}:${qt}`),console.log(`${b.cyan} \u26A1 Auto-switched to ${qt} to avoid further stale timeouts${b.reset}`),console.log(`${b.dim} (disable with NEX_STALE_AUTO_SWITCH=0)${b.reset}`))}}else console.log(`${b.yellow} \u26A0 Stale retry ${v}/${gr} \u2014 retrying in ${H/1e3}s...${b.reset}`);let ue=new Yt(`Waiting ${H/1e3}s before retry...`);ue.start(),await new Promise(W=>setTimeout(W,H)),ue.stop(),D--;continue}if(R.name==="AbortError"||R.name==="CanceledError"||R.message?.includes("canceled")||R.message?.includes("aborted")){n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);break}let N=R.message;if(R.code==="ECONNREFUSED"||R.message.includes("ECONNREFUSED"))N="Connection refused \u2014 please check your internet connection or API endpoint";else if(R.code==="ENOTFOUND"||R.message.includes("ENOTFOUND"))N="Network error \u2014 could not reach the API server. Please check your connection";else if(R.code==="ETIMEDOUT"||R.message.includes("timeout"))N="Request timed out \u2014 the API server took too long to respond. Please try again";else if(R.message.includes("401")||R.message.includes("Unauthorized"))N="Authentication failed \u2014 please check your API key in the .env file";else if(R.message.includes("403")||R.message.includes("Forbidden"))N="Access denied \u2014 your API key may not have permission for this model";else if(R.message.includes("400")){if(T<2){T++,console.log(`${b.yellow} \u26A0 Bad request (400) \u2014 force-compressing and retrying... (attempt ${T}/2)${b.reset}`);let W=Jt(),{messages:he,tokensRemoved:Re}=ur(x,W);x=he,Re>0&&console.log(`${b.dim} [force-compressed \u2014 ~${Re} tokens freed]${b.reset}`),D--;continue}let H=(R.message||"").toLowerCase();H.includes("context")||H.includes("token")||H.includes("length")||H.includes("too long")||H.includes("too many")||H.includes("prompt")||H.includes("size")||H.includes("exceeds")||H.includes("num_ctx")||H.includes("input")?N="Context too long \u2014 force compression exhausted. Use /clear to start fresh":N="Bad request \u2014 compression did not help. Use /clear and retry"}else R.message.includes("500")||R.message.includes("502")||R.message.includes("503")||R.message.includes("504")?N="API server error \u2014 the provider is experiencing issues. Please try again in a moment":(R.message.includes("fetch failed")||R.message.includes("fetch"))&&(N="Network request failed \u2014 please check your internet connection");if(console.log(`${b.red} \u2717 ${N}${b.reset}`),R.message.includes("429")){if(S++,S>mr){console.log(`${b.red} Rate limit: max retries (${mr}) exceeded. Try again later or use /budget to check your limits.${b.reset}`),n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);break}let H=Math.min(1e4*Math.pow(2,S-1),12e4),ue=new Yt(`Rate limit \u2014 waiting ${Math.round(H/1e3)}s (retry ${S}/${mr})`);ue.start(),await new Promise(W=>setTimeout(W,H)),ue.stop();continue}if(R.message.includes("socket disconnected")||R.message.includes("TLS")||R.message.includes("ECONNRESET")||R.message.includes("ECONNABORTED")||R.message.includes("ETIMEDOUT")||R.code==="ECONNRESET"||R.code==="ECONNABORTED"){if(k++,k>hr){console.log(`${b.red} Network error: max retries (${hr}) exceeded. Check your connection and try again.${b.reset}`),n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);break}let H=Math.min(2e3*Math.pow(2,k-1),3e4),ue=new Yt(`Network error \u2014 retrying in ${Math.round(H/1e3)}s (${k}/${hr})`);ue.start(),await new Promise(W=>setTimeout(W,H)),ue.stop(),D--;continue}n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);break}clearInterval(Hr),S=0,k=0,Me&&(n&&!n._paused&&n.pause(),be&&be.stop()),Xe&&(clearTimeout(Xe),Xe=null),Le&&we&&(we.push(Le),Le=""),Pe&&we.flush(),k=0,v=0,lt&<.usage&&(Hh(Cn(),Cs(),lt.usage.prompt_tokens||0,lt.usage.completion_tokens||0),o+=(lt.usage.prompt_tokens||0)+(lt.usage.completion_tokens||0),n&&n.setStats({tokens:o}));let{content:Hs,tool_calls:bt}=lt,Gs={role:"assistant",content:Hs||""};if(bt&&bt.length>0&&(Gs.tool_calls=bt),Y.push(Gs),x.push(Gs),!bt||bt.length===0){let R=(Hs||"").trim().length>0||Pe.trim().length>0;if(!R&&E>0&&D<yr-1){let N={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(N),Y.push(N);continue}if(Ms()&&R){let N=(Hs||Pe||"").trim();Mh(N),lg(N);let qe=Ph(N);if(qe.length>0){let H=Y.find(he=>he.role==="user"),ue=typeof H?.content=="string"?H.content.slice(0,120):"Task";Lh(ue,qe);let W=qe.length===1?"step":"steps";console.log(`
|
|
559
|
+
${b.cyan}${b.bold}Plan ready${b.reset} ${b.dim}(${qe.length} ${W} extracted).${b.reset} Type ${b.cyan}/plan approve${b.reset}${b.dim} to execute, or ${b.reset}${b.cyan}/plan edit${b.reset}${b.dim} to review.${b.reset}`)}else console.log(`
|
|
560
|
+
${b.cyan}${b.bold}Plan ready.${b.reset} ${b.dim}Type ${b.reset}${b.cyan}/plan approve${b.reset}${b.dim} to execute, or ask follow-up questions to refine.${b.reset}`)}n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);return}E++,E>=1&&(ee=!1);for(let R of bt){let N=R.function.name;F.set(N,(F.get(N)||0)+1)}let Qe=await Promise.all(bt.map(R=>ug(R))),tn=n?{skipSpinner:!0,skipSummaries:!0}:{},lu=Qe.some(R=>R.fnName==="ask_user"),Gr=!tn.skipSummaries&&!ee,zs=null;Gr&&!lu?(ee=!0,tn.skipSpinner=!0,process.stdout.isTTY?(process.stdout.write(lr(Qe,E,!1,"blink")),zs=!0):process.stdout.write(lr(Qe,E,!1)+`
|
|
561
|
+
`)):Gr&&(ee=!0,tn.skipSpinner=!0),n&&n._paused&&n.resume();let{results:zr,summaries:Kr}=await pg(Qe,!0,{...tn,skipSummaries:!0});if(zs&&(zs=null,process.stdout.write(`\r\x1B[2K${lr(Qe,E,!1)}
|
|
562
|
+
`)),!tn.skipSummaries)for(let R=0;R<Kr.length;R++)Qe[R]&&Qe[R].fnName==="ask_user"||console.log(Kr[R]);for(let R=0;R<Qe.length;R++){let N=Qe[R];if(!N.canExecute)continue;let H=zr[R].content.split(`
|
|
563
|
+
`)[0],ue=!H.startsWith("ERROR")&&!H.startsWith("CANCELLED");if(ue&&["write_file","edit_file","patch_file"].includes(N.fnName)&&N.args&&N.args.path){j.add(N.args.path);let W=(te.get(N.args.path)||0)+1;te.set(N.args.path,W);let he=N.args.path.split("/").slice(-2).join("/");if(W===me){console.log(`${b.yellow} \u26A0 Loop warning: "${he}" edited ${W}\xD7 \u2014 possible edit loop${b.reset}`);let Re={role:"user",content:`[SYSTEM WARNING] You have edited "${N.args.path}" ${W} 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.`};Y.push(Re),x.push(Re)}else if(W>=Pn){console.log(`${b.red} \u2716 Loop abort: "${he}" edited ${W}\xD7 \u2014 aborting to prevent runaway loop${b.reset}`),n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);return}}if(N.fnName==="bash_exec"&&N.args&&N.args.command){let W=N.args.command.replace(/\s+/g," ").trim().slice(0,100),he=(ye.get(W)||0)+1;if(ye.set(W,he),he===It){console.log(`${b.yellow} \u26A0 Loop warning: same bash command run ${he}\xD7 \u2014 possible debug loop${b.reset}`);let Re={role:"user",content:`[SYSTEM WARNING] You have run the same or similar bash command ${he} times. This looks like a debug loop. STOP repeating the same command. Try a completely different approach or declare that the current approach is not working and explain why.`};Y.push(Re),x.push(Re)}else if(he>=q){console.log(`${b.red} \u2716 Loop abort: same bash command run ${he}\xD7 \u2014 aborting runaway debug loop${b.reset}`),n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);return}}if(ue)P=0;else if(P++,P===B){console.log(`${b.yellow} \u26A0 Loop warning: ${P} consecutive tool errors \u2014 possible stuck loop${b.reset}`);let W={role:"user",content:`[SYSTEM WARNING] ${P} consecutive tool calls have failed. You appear to be stuck. STOP trying variations of the same failing approach. Either try something fundamentally different, acknowledge the limitation, or declare the task complete with what you have.`};Y.push(W),x.push(W)}else if(P>=V){console.log(`${b.red} \u2716 Loop abort: ${P} consecutive errors \u2014 aborting stuck loop${b.reset}`),n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);return}ue&&N.fnName==="read_file"&&N.args&&N.args.path&&Z.add(N.args.path)}for(let R of zr)Y.push(R),x.push(R);let Yr=hg();if(Yr){let R={role:"user",content:`[User note mid-run]: ${Yr}`};Y.push(R),x.push(R),console.log(`${b.cyan} \u270E Kontext hinzugef\xFCgt${b.reset}`)}}if(D>=Q){n&&(n.stop(),n=null),s(null),Je(E,F,j,Z,G),Ye(Y);let{getActiveProviderName:U}=ge();if(U()==="ollama"&&z<le){z++,Q=20,console.log(`${b.dim} \u2500\u2500 auto-extending (+20 turns, ext ${z}/${le}) \u2500\u2500${b.reset}`);continue e}if(console.log(`
|
|
564
|
+
${b.yellow}\u26A0 Max iterations reached.${b.reset}`),await ul(" Continue for 20 more turns?")){Q=20;continue e}console.log(`${b.dim} Tip: set "maxIterations" in .nex/config.json or use --max-turns${b.reset}`)}break e}}gl.exports={processInput:Eg,clearConversation:yg,getConversationLength:bg,getConversationMessages:xg,setConversationMessages:_g,setAbortSignalGetter:Xh,setMaxIterations:Vh,invalidateSystemPromptCache:og,clearToolFilterCache:sg,getCachedFilteredTools:pl,buildSystemPrompt:hl,getProjectContextHash:ml,buildUserContent:fl,injectMidRunNote:mg}});var ge=L((Fy,xl)=>{var{OllamaProvider:Tg}=di(),{OpenAIProvider:Rg}=Ri(),{AnthropicProvider:Cg}=Ni(),{GeminiProvider:Ag}=Ii(),{LocalProvider:Og}=ji(),{checkBudget:Ng}=Ft(),_r={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"}},$l={};for(let[t,e]of Object.entries(_r))for(let s of Object.values(e))$l[s]=t;function yl(t,e){let s=$l[t];return s&&_r[s][e]||t}var $e={},Te=null,pe=null,On=[];function Ie(){if(Object.keys($e).length>0)return;Xt("ollama",new Tg),Xt("openai",new Rg),Xt("anthropic",new Cg),Xt("gemini",new Ag),Xt("local",new Og);let t=process.env.DEFAULT_PROVIDER||"ollama",e=process.env.DEFAULT_MODEL||null;$e[t]?(Te=t,pe=e||$e[t].defaultModel):(Te="ollama",pe="kimi-k2.5");let s=process.env.FALLBACK_CHAIN;s&&(On=s.split(",").map(n=>n.trim()).filter(Boolean))}function Xt(t,e){$e[t]=e}function Mg(t){return Ie(),$e[t]||null}function kr(){return Ie(),$e[Te]||null}function Pg(){return Ie(),Te}function Lg(){return Ie(),pe}function Ig(){Ie();let t=kr();if(!t)return{id:pe,name:pe,provider:Te};let e=t.getModel(pe);return e?{...e,provider:Te}:{id:pe,name:pe,provider:Te}}function wl(t){if(!t)return{provider:null,model:null};let e=t.indexOf(":");if(e>0){let s=t.slice(0,e);if($e[s]||["ollama","openai","anthropic","gemini","local"].includes(s))return{provider:s,model:t.slice(e+1)}}return{provider:null,model:t}}function qg(t){Ie();let{provider:e,model:s}=wl(t);if(e){let o=$e[e];return o&&(o.getModel(s)||e==="local"||e==="ollama")?(Te=e,pe=s,Ls(),!0):!1}let n=kr();if(n&&n.getModel(s))return pe=s,Ls(),!0;for(let[o,r]of Object.entries($e))if(r.getModel(s))return Te=o,pe=s,Ls(),!0;return!1}function Ls(){try{let{invalidateSystemPromptCache:t,clearToolFilterCache:e}=fe();t(),e()}catch{}try{let{invalidateTokenRatioCache:t}=De();t()}catch{}}function Dg(){Ie();let t=new Set;for(let e of Object.values($e))for(let s of e.getModelNames())t.add(s);return Array.from(t)}function jg(){return Ie(),Object.entries($e).map(([t,e])=>({provider:t,configured:e.isConfigured(),models:Object.values(e.getModels()).map(s=>({...s,active:t===Te&&s.id===pe}))}))}function Fg(){Ie();let t=[];for(let[e,s]of Object.entries($e)){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 Ug(t){On=Array.isArray(t)?t:[]}function Wg(){return[...On]}function Bg(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 bl(t){let e=[Te,...On.filter(r=>r!==Te)],s,n=0,o=0;for(let r=0;r<e.length;r++){let i=e[r],c=$e[i];if(!c||!c.isConfigured())continue;o++;let l=Ng(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?yl(pe,i):pe;return u&&d!==pe&&process.stderr.write(` [fallback: ${i}:${d}]
|
|
565
|
+
`),await t(c,i,d)}catch(u){if(s=u,Bg(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 Hg(t,e,s={}){return Ie(),bl((n,o,r)=>n.stream(t,e,{model:r,signal:s.signal,...s}))}async function Gg(t,e,s={}){if(Ie(),s.provider){let n=$e[s.provider];if(!n||!n.isConfigured())throw new Error(`Provider '${s.provider}' is not available`);let o={model:s.model||pe,...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 bl(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 zg(){Ie();let t=[];for(let[e,s]of Object.entries($e))s.isConfigured()&&t.push({name:e,models:Object.values(s.getModels())});return t}function Kg(){for(let t of Object.keys($e))delete $e[t];Te=null,pe=null,On=[]}xl.exports={registerProvider:Xt,getProvider:Mg,getActiveProvider:kr,getActiveProviderName:Pg,getActiveModelId:Lg,getActiveModel:Ig,setActiveModel:qg,getModelNames:Dg,parseModelSpec:wl,listProviders:jg,listAllModels:Fg,callStream:Hg,callChat:Gg,getConfiguredProviders:zg,setFallbackChain:Ug,getFallbackChain:Wg,resolveModelForProvider:yl,MODEL_EQUIVALENTS:_r,_reset:Kg}});var Sr=L((Uy,_l)=>{"use strict";var it=require("fs"),Is=require("path"),Yg=require("readline"),J="\x1B[0m",vr="\x1B[1m",Ae="\x1B[2m",qs="\x1B[33m",Qt="\x1B[36m",Ds="\x1B[32m";function Jg(t){return(e,s="")=>new Promise(n=>{let o=s?` ${Ae}[${s}]${J}`:"";t.question(` ${Qt}${e}${o}${J}: `,r=>n(r.trim()||s))})}function js(t,e){return new Promise(s=>{e&&e.pause(),process.stdout.write(` ${Qt}${t}${J}: `);let n=process.stdin,o=n.isRaw,r="";n.setRawMode(!0),n.resume(),n.setEncoding("utf8");let i=c=>{c==="\r"||c===`
|
|
566
|
+
`?(n.setRawMode(o||!1),n.removeListener("data",i),process.stdout.write(`
|
|
567
|
+
`),e&&e.resume(),s(r)):c===""?(process.stdout.write(`
|
|
568
|
+
`),process.exit(0)):c==="\x7F"?r.length>0&&(r=r.slice(0,-1),process.stdout.write("\b \b")):(r+=c,process.stdout.write("*"))};n.on("data",i)})}async function Vg({rl:t=null,force:e=!1}={}){if(!e){let f=it.existsSync(Is.join(process.cwd(),".env"))||it.existsSync(Is.join(__dirname,"..",".env")),h=process.env.ANTHROPIC_API_KEY||process.env.OPENAI_API_KEY||process.env.GEMINI_API_KEY||process.env.OPENROUTER_API_KEY,m=process.env.DEFAULT_PROVIDER||process.env.DEFAULT_MODEL;if(f||h||m)return}let s=!t,n=t||Yg.createInterface({input:process.stdin,output:process.stdout,terminal:!0}),o=Jg(n),r=!e;console.log(),console.log(r?`${qs}${vr} \u2726 Welcome to nex-code! No configuration found.${J}`:`${Qt}${vr} \u2726 nex-code \u2014 Provider & API Key Setup${J}`),console.log(`${Ae} \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500${J}`),r&&console.log(` Let's set you up in 60 seconds.
|
|
569
|
+
`),console.log(` ${vr}Which AI provider do you want to use?${J}
|
|
570
|
+
`),console.log(` ${Ds}1)${J} Ollama ${Ae}local/cloud \u2014 no API key needed${J}`),console.log(` ${Qt}2)${J} Anthropic ${Ae}Claude (claude-sonnet-4-6 etc.)${J}`),console.log(` ${Qt}3)${J} OpenAI ${Ae}GPT-4o, GPT-4.1 etc.${J}`),console.log(` ${Qt}4)${J} Gemini ${Ae}Google Gemini 2.x${J}`),console.log(` ${Ae}5) Skip / Cancel${J}`),console.log();let i=await o("Enter number","1"),c=[];if(i==="5"){s&&n.close(),console.log(`
|
|
571
|
+
${Ae} Cancelled \u2014 no changes made.${J}
|
|
572
|
+
`);return}if(i==="1"){console.log();let f=await o("Ollama host","http://localhost:11434"),h=await o("Default model","qwen3-coder");c.push("DEFAULT_PROVIDER=ollama",`DEFAULT_MODEL=${h}`,`OLLAMA_HOST=${f}`),process.env.DEFAULT_PROVIDER="ollama",process.env.DEFAULT_MODEL=h,process.env.OLLAMA_HOST=f}else if(i==="2"){console.log(),console.log(` ${Ae}Get your key: https://console.anthropic.com/settings/keys${J}`);let f=await js("ANTHROPIC_API_KEY",t);if(!f){s&&n.close(),console.log(`
|
|
573
|
+
${qs} No key entered \u2014 cancelled.${J}
|
|
574
|
+
`);return}let h=await o("Default model","claude-sonnet-4-6");c.push("DEFAULT_PROVIDER=anthropic",`DEFAULT_MODEL=${h}`,`ANTHROPIC_API_KEY=${f}`),process.env.DEFAULT_PROVIDER="anthropic",process.env.DEFAULT_MODEL=h,process.env.ANTHROPIC_API_KEY=f}else if(i==="3"){console.log(),console.log(` ${Ae}Get your key: https://platform.openai.com/api-keys${J}`);let f=await js("OPENAI_API_KEY",t);if(!f){s&&n.close(),console.log(`
|
|
575
|
+
${qs} No key entered \u2014 cancelled.${J}
|
|
576
|
+
`);return}let h=await o("Default model","gpt-4o");c.push("DEFAULT_PROVIDER=openai",`DEFAULT_MODEL=${h}`,`OPENAI_API_KEY=${f}`),process.env.DEFAULT_PROVIDER="openai",process.env.DEFAULT_MODEL=h,process.env.OPENAI_API_KEY=f}else if(i==="4"){console.log(),console.log(` ${Ae}Get your key: https://aistudio.google.com/app/apikey${J}`);let f=await js("GEMINI_API_KEY",t);if(!f){s&&n.close(),console.log(`
|
|
577
|
+
${qs} No key entered \u2014 cancelled.${J}
|
|
578
|
+
`);return}let h=await o("Default model","gemini-2.0-flash");c.push("DEFAULT_PROVIDER=gemini",`DEFAULT_MODEL=${h}`,`GEMINI_API_KEY=${f}`),process.env.DEFAULT_PROVIDER="gemini",process.env.DEFAULT_MODEL=h,process.env.GEMINI_API_KEY=f}if(console.log(),(await o("Add Perplexity key for grounded web search? (y/N)","n")).toLowerCase()==="y"){console.log(` ${Ae}Get your key: https://www.perplexity.ai/settings/api${J}`);let f=await js("PERPLEXITY_API_KEY",t);f&&(c.push(`PERPLEXITY_API_KEY=${f}`),process.env.PERPLEXITY_API_KEY=f)}console.log();let u=Is.join(process.cwd(),".env"),d=(it.existsSync(u),"y"),p=await o(`Save to ${u}? (Y/n)`,d);if(s&&n.close(),p.toLowerCase()!=="n"){let f=it.existsSync(u)?it.readFileSync(u,"utf-8").trimEnd()+`
|
|
579
|
+
|
|
580
|
+
`:"";it.writeFileSync(u,f+c.join(`
|
|
581
|
+
`)+`
|
|
582
|
+
`);let h=Is.join(process.cwd(),".gitignore");it.existsSync(h)&&(it.readFileSync(h,"utf-8").split(`
|
|
583
|
+
`).some(g=>g.trim()===".env")||it.appendFileSync(h,`
|
|
584
|
+
.env
|
|
585
|
+
`)),console.log(`
|
|
586
|
+
${Ds} \u2713 Saved to ${u}${J}`),c.some(m=>m.includes("API_KEY"))&&console.log(`${Ae} (key stored locally \u2014 never committed)${J}`)}if(process.env.DEFAULT_PROVIDER)try{let{setActiveModel:f}=ge(),h=process.env.DEFAULT_MODEL?`${process.env.DEFAULT_PROVIDER}:${process.env.DEFAULT_MODEL}`:process.env.DEFAULT_PROVIDER;f(h),console.log(`${Ds} \u2713 Switched to ${h} for this session${J}`)}catch{}console.log(`
|
|
587
|
+
${Ds} \u2713 Setup complete!${J}
|
|
588
|
+
`)}_l.exports={runSetupWizard:Vg}});var El=L((Wy,Sl)=>{"use strict";var kl=require("fs"),Xg="\x1B[2m",Qg="\x1B[0m",Zg=process.env.FOOTER_DEBUG==="1",Er=null;function gt(...t){Zg&&(Er||(Er=kl.openSync("/tmp/footer-debug.log","w")),kl.writeSync(Er,t.join(" ")+`
|
|
589
|
+
`))}function vl(t){return t.replace(/\x1b\[[^a-zA-Z]*[a-zA-Z]/g,"").length}var Tr=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._inRefreshLine=!1,this._lastOutputRow=1,this._prevTermRows=0,this._prevTermCols=0,this._consistencyTimer=null,this._dirty=!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 Xg+"\u2500".repeat(this._cols)+Qg}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")}rawWrite(e){return this._origWrite?this._origWrite(e):process.stdout.write(e)}_relayout(e){if(!this._origWrite)return;let s=this._origWrite,n=this._rows,o=this._cols,r=Math.max(1,n-2);gt("RELAYOUT:",e,"rows="+n,"cols="+o,"scrollEnd="+r,"cursorOnInput="+this._cursorOnInputRow),this._prevTermRows=n,this._prevTermCols=o;let i=Math.min(this._lastOutputRow+1,r+1),c="";for(let l=i;l<=n;l++)c+=this._goto(l)+"\x1B[2K";s(c),this._setScrollRegion(),this._lastOutputRow=Math.min(this._lastOutputRow,r),this.drawFooter(),this._cursorOnInputRow&&this._rl&&this._rl.prompt(!0),this._dirty=!1}activate(e){if(!process.stdout.isTTY)return;this._rl=e,this._origWrite=process.stdout.write.bind(process.stdout),this._active=!0,this._prevTermRows=this._rows,this._prevTermCols=this._cols,this._setScrollRegion(),this._lastOutputRow=1,this.drawFooter();let s=this,n=process.stdout.write.bind(process.stdout);this._origWrite=n,process.stdout.write=function(m,...g){if(!s._active||typeof m!="string")return n(m,...g);if(s._inRefreshLine){let k=m.replace(/\n/g,"");return k?n(k,...g):!0}if(s._cursorOnInputRow)if(m.includes(`
|
|
590
|
+
`)&&m.length>4&&!m.includes("\r"))gt("STDOUT: agent output, leaving input row, data="+JSON.stringify(m).slice(0,100)),s._cursorOnInputRow=!1,n(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd)));else{if(m.length<=4&&!m.includes(`
|
|
591
|
+
`)&&!m.includes("\r")&&!/[\x00-\x1f\x7f]/.test(m))return gt("STDOUT: char intercept:",JSON.stringify(m)),s._origRefreshLine&&s._doRefreshLine(),!0;{let k=m.replace(/\n/g,"");return k?n(k,...g):!0}}let y=s._cols||80,$=0,x=m.split(`
|
|
592
|
+
`);for(let k=0;k<x.length;k++){let v=vl(x[k]);v>0&&($+=Math.floor((v-1)/y))}let S=x.length-1;return S+$>0&&(s._lastOutputRow=Math.min(s._lastOutputRow+S+$,s._scrollEnd)),n(m,...g)},this._cursorOnInputRow=!1,this._origStderrWrite=process.stderr.write.bind(process.stderr),process.stderr.write=function(m,...g){if(!s._active)return s._origStderrWrite(m,...g);if(typeof m=="string"&&m.includes("\r")){let y=Math.min(s._lastOutputRow+1,s._scrollEnd);if(s._cursorOnInputRow){s._origWrite("\x1B7"),s._origWrite(s._goto(y));let $=s._origStderrWrite(m,...g);return s._origWrite("\x1B8"),$}s._origWrite(s._goto(y))}return s._origStderrWrite(m,...g)},this._origLog=console.log,this._origError=console.error;function o(...m){if(!s._active){s._origLog(...m);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origLog(...m),s.drawFooter(),s._rl&&s._rl.prompt()}function r(...m){if(!s._active){s._origError(...m);return}s._origWrite(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s._cursorOnInputRow=!1,s._origError(...m),s.drawFooter(),s._rl&&s._rl.prompt()}console.log=o,console.error=r,this._origSetPr=e.setPrompt.bind(e),e.setPrompt=function(m){s._origSetPr(m),s._active&&s.drawFooter(m)},this._origPrompt=e.prompt.bind(e),e.prompt=function(m){if(!s._active)return s._origPrompt(m);gt("PROMPT: goto rowInput="+s._rowInput),e.prevRows=0,n(s._goto(s._rowInput)),s._cursorOnInputRow=!0,s._origPrompt(m)};let i=e.question.bind(e);e.question=function(m,g){if(!s._active)return i(m,g);n(s._goto(s._rowInput)+"\x1B[2K"),e.prevRows=0,s._cursorOnInputRow=!0,i(m,y=>{n(s._goto(s._rowInput)+"\x1B[2K"),s._cursorOnInputRow=!1,s.drawFooter(),g(y)})};let c=Object.getPrototypeOf(e),l=Object.getOwnPropertySymbols(c).find(m=>m.toString()==="Symbol(_refreshLine)"),u=l?c[l].bind(e):e._refreshLine?e._refreshLine.bind(e):null;if(this._origRefreshLine=u,this._doRefreshLine=function(){if(!s._active||!u)return;if(s._rows!==s._prevTermRows||s._cols!==s._prevTermCols){s._dirty=!0;return}e.prevRows=0,n(s._goto(s._rowInput));let m=s._cols,g=e._prompt||"",y=vl(g),$=m-y-1;s._inRefreshLine=!0;try{if(e.line.length<=$){gt("REFRESH: short line, len="+e.line.length),u();return}gt("REFRESH: long line, len="+e.line.length+", max="+$);let x=e.line,S=e.cursor,k=Math.max(1,$-1),v=Math.max(0,S-k),T=(v>0?"\xAB":"")+x.slice(v,v+k+(v>0?0:1));e.line=T,e.cursor=T.length,u(),e.line=x,e.cursor=S}finally{s._inRefreshLine=!1}},u){let m=this._doRefreshLine;l&&Object.defineProperty(e,l,{value:m,writable:!0,configurable:!0}),e._refreshLine=m}e.on("line",()=>{s._active&&(gt("LINE: leaving input row"),s._cursorOnInputRow=!1,n(s._goto(s._rowInput)+"\x1B[2K"),n(s._goto(Math.min(s._lastOutputRow+1,s._scrollEnd))),s.drawFooter())});let d=null,p=null,f=()=>{d=null,s._relayout("resize"),p&&clearTimeout(p),p=setTimeout(()=>{p=null,s._relayout("resize-cleanup")},300)},h=()=>{s._dirty=!0,d&&clearTimeout(d),d=setTimeout(f,80)};process.stdout.on("resize",h),this._offResize=()=>{process.stdout.off("resize",h),d&&(clearTimeout(d),d=null),p&&(clearTimeout(p),p=null)},this._consistencyTimer=setInterval(()=>{if(!s._active)return;let m=s._rows,g=s._cols;(s._dirty||m!==s._prevTermRows||g!==s._prevTermCols)&&(gt("CONSISTENCY: dirty="+s._dirty+" rows="+m+"/"+s._prevTermRows+" cols="+g+"/"+s._prevTermCols),s._relayout("consistency"))},800)}deactivate(){if(this._active){if(this._active=!1,this._offResize&&(this._offResize(),this._offResize=null),this._consistencyTimer&&(clearInterval(this._consistencyTimer),this._consistencyTimer=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)){let e=Object.getOwnPropertySymbols(Object.getPrototypeOf(this._rl)).find(s=>s.toString()==="Symbol(_refreshLine)");e&&delete this._rl[e],delete this._rl._refreshLine,this._origRefreshLine=null}this._eraseStatus(),this._clearScrollRegion(),this._origWrite=null}}};Sl.exports={StickyFooter:Tr}});var Cl=L((By,Rl)=>{var{C:se}=de(),{listProviders:e$,getActiveProviderName:t$,getActiveModelId:n$,setActiveModel:s$}=ge();function Tl(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 p(){let $=i[l];return $<d?d=$:$>=d+u&&(d=$-u+1),{start:d,end:Math.min(e.length,d+u)}}let f=0;function h(){if(f>0){process.stdout.write(`\x1B[${f}A`);for(let v=0;v<f;v++)process.stdout.write(`\x1B[2K
|
|
593
|
+
`);process.stdout.write(`\x1B[${f}A`)}let $=[];$.push(` ${se.bold}${se.cyan}${n}${se.reset}`),$.push(` ${se.dim}${o}${se.reset}`),$.push("");let{start:x,end:S}=p();x>0&&$.push(` ${se.dim}\u2191 more${se.reset}`);for(let v=x;v<S;v++){let T=e[v];if(T.isHeader){$.push(` ${se.bold}${se.dim}${T.label}${se.reset}`);continue}let A=i[l]===v,E=A?`${se.cyan}> `:" ",F=T.isCurrent?` ${se.yellow}<current>${se.reset}`:"";A?$.push(`${E}${se.bold}${T.label}${se.reset}${F}`):$.push(`${E}${se.dim}${T.label}${se.reset}${F}`)}S<e.length&&$.push(` ${se.dim}\u2193 more${se.reset}`);let k=$.join(`
|
|
562
594
|
`);process.stdout.write(k+`
|
|
563
|
-
`),
|
|
595
|
+
`),f=$.length}t.pause();let m=process.stdin.isRaw;process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.resume();function g(){process.stdin.removeListener("keypress",y),process.stdin.isTTY&&m!==void 0&&process.stdin.setRawMode(m),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 S=e[i[l]];g(),r(S?S.value:null);return}if(x.name==="escape"||x.ctrl&&x.name==="c"){g(),r(null);return}}}process.stdin.on("keypress",y),h()})}async function o$(t){let e=e$(),s=t$(),n=n$(),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 Tl(t,o,{title:"Select Model"});return r?(s$(r),console.log(`${se.green}Switched to ${r}${se.reset}`),!0):(console.log(`${se.dim}Cancelled${se.reset}`),!1)}Rl.exports={pickFromList:Tl,showModelPicker:o$}});var Ar=L((Gy,Il)=>{var Rr=require("fs"),r$=require("path"),{callChat:Al}=ge(),{remember:i$,listMemories:Hy,recall:a$}=ht(),Cr=4,c$=`You are a memory optimization agent for an AI coding assistant called nex-code.
|
|
564
596
|
Analyze this conversation history and extract actionable learnings the assistant should remember.
|
|
565
597
|
|
|
566
598
|
Return ONLY valid JSON in this exact format:
|
|
@@ -586,15 +618,15 @@ Rules:
|
|
|
586
618
|
- value: concise actionable instruction, max 120 chars
|
|
587
619
|
- nex_additions: project-level instructions/conventions only (not personal preferences)
|
|
588
620
|
- If nothing significant to learn, return {"memories": [], "nex_additions": [], "summary": "..."}
|
|
589
|
-
- Return ONLY the JSON, no markdown, no explanation`;function
|
|
621
|
+
- Return ONLY the JSON, no markdown, no explanation`;function Ol(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(`
|
|
590
622
|
|
|
591
|
-
`)}async function
|
|
623
|
+
`)}async function Nl(t){if(t.filter(o=>o.role==="user").length<Cr)return{memories:[],nex_additions:[],summary:null,skipped:!0};let s=Ol(t);if(!s.trim())return{memories:[],nex_additions:[],summary:null,skipped:!0};let n=[{role:"system",content:c$},{role:"user",content:`Conversation to analyze:
|
|
592
624
|
|
|
593
|
-
${
|
|
594
|
-
`)?
|
|
595
|
-
`+
|
|
596
|
-
`)||(
|
|
597
|
-
`),
|
|
625
|
+
${s}`}];try{let i=((await Al(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 Ml(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=a$(o);i!==r&&(i$(o,r),e.push({key:o,value:r,action:i?"updated":"added"}))}return e}function Pl(t){if(!t||t.length===0)return[];let e=r$.join(process.cwd(),"NEX.md"),s="";try{Rr.existsSync(e)&&(s=Rr.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(`
|
|
626
|
+
`)?o+i:o+`
|
|
627
|
+
`+i:i)}return n.length>0&&(o.endsWith(`
|
|
628
|
+
`)||(o+=`
|
|
629
|
+
`),Rr.writeFileSync(e,o,"utf-8")),n}async function l$(t){let e=await Nl(t);if(e.skipped)return{applied:[],nexAdded:[],summary:null,skipped:!0};if(e.error)return{applied:[],nexAdded:[],summary:null,error:e.error};let s=Ml(e.memories),n=Pl(e.nex_additions);return{applied:s,nexAdded:n,summary:e.summary}}var u$=`You are a knowledge base agent for an AI coding assistant called nex-code.
|
|
598
630
|
Analyze this conversation and extract knowledge worth persisting in the project knowledge base (.nex/brain/).
|
|
599
631
|
|
|
600
632
|
Return ONLY valid JSON in this exact format:
|
|
@@ -628,37 +660,37 @@ Rules:
|
|
|
628
660
|
---
|
|
629
661
|
- Maximum 3 documents per session. Quality over quantity.
|
|
630
662
|
- If nothing worth persisting: return {"documents": [], "skip_reason": "..."}
|
|
631
|
-
- Return ONLY the JSON, no markdown fences, no explanation`;async function
|
|
663
|
+
- Return ONLY the JSON, no markdown fences, no explanation`;async function Ll(t){if(t.filter(o=>o.role==="user").length<Cr)return{documents:[],skip_reason:"Session too short"};let s=Ol(t);if(!s.trim())return{documents:[],skip_reason:"No usable content"};let n=[{role:"system",content:u$},{role:"user",content:`Conversation to analyze:
|
|
632
664
|
|
|
633
|
-
${
|
|
665
|
+
${s}`}];try{let i=((await Al(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 d$(t){let e=await Ll(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}=_n(),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=`
|
|
634
666
|
|
|
635
667
|
## Update ${new Date().toISOString().split("T")[0]}
|
|
636
668
|
|
|
637
|
-
${
|
|
638
|
-
${
|
|
639
|
-
`);let n=Object.keys(
|
|
640
|
-
`);return}let
|
|
641
|
-
${
|
|
642
|
-
${
|
|
643
|
-
Add another server?`,!1)}
|
|
669
|
+
${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}}Il.exports={learnFromSession:l$,learnBrainFromSession:d$,reflectOnSession:Nl,reflectBrain:Ll,applyMemories:Ml,applyNexAdditions:Pl,LEARN_MIN_MESSAGES:Cr}});var Ul=L((Ky,Fl)=>{var ke=require("fs"),en=require("path"),zy=require("os"),f$=require("readline"),{C:O}=de(),ql=".nex",Or=null;function p$(t){Or=t}function Oe(t,e=""){let s=e?` ${O.dim}[${e}]${O.reset}`:"",n=` ${O.cyan}${t}${s}${O.reset}: `;return new Promise(o=>{let r=i=>{let c=i.trim()||e;o(c)};if(Or)Or.question(n,r);else{let i=f$.createInterface({input:process.stdin,output:process.stdout});i.question(n,c=>{i.close(),r(c)})}})}function Zt(t,e=!0){return Oe(`${t} (${e?"Y/n":"y/N"})`,e?"y":"n").then(n=>n.toLowerCase()!=="n"&&n.toLowerCase()!=="no")}async function Dl(t,e,s){let n=e.map((c,l)=>`${O.dim}${l+1})${O.reset} ${c}`).join(" ");console.log(` ${O.cyan}${t}${O.reset}`),console.log(` ${n}`);let o=s?e.indexOf(s)+1:1,r=await Oe("Enter number",String(o)),i=parseInt(r,10)-1;return e[Math.max(0,Math.min(i,e.length-1))]}async function m$(){let t=en.join(process.cwd(),ql),e=en.join(t,"servers.json"),s={};if(ke.existsSync(e))try{s=JSON.parse(ke.readFileSync(e,"utf-8"))}catch{}console.log(`
|
|
670
|
+
${O.bold}${O.cyan}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557${O.reset}`),console.log(`${O.bold}${O.cyan}\u2551 nex-code Server Setup Wizard \u2551${O.reset}`),console.log(`${O.bold}${O.cyan}\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${O.reset}
|
|
671
|
+
`);let n=Object.keys(s);if(n.length>0&&(console.log(`${O.dim}Existing profiles: ${n.join(", ")}${O.reset}`),!await Zt("Add or update a server profile?",!0))){console.log(`${O.dim}No changes made.${O.reset}
|
|
672
|
+
`);return}let o={...s},r=!0;for(;r;){console.log(`
|
|
673
|
+
${O.bold}\u2500\u2500\u2500 New Server Profile \u2500\u2500\u2500${O.reset}`);let l=await Oe("Profile name (e.g. prod, staging, macbook)");if(!l){console.log(`${O.red} Name is required.${O.reset}`);continue}let u=await Oe("Host / IP address");if(!u){console.log(`${O.red} Host is required.${O.reset}`);continue}let d=await Oe("SSH user","root"),p=await Oe("SSH port","22"),f=parseInt(p,10)||22,h=await Oe("SSH key path (leave empty for SSH agent)",""),m=await Dl("Operating system",["almalinux9","macos","ubuntu","debian","other"],"almalinux9"),g=await Zt("Allow sudo commands?",!0),y={host:u,user:d};f!==22&&(y.port=f),h&&(y.key=h),m!=="other"&&(y.os=m),g&&(y.sudo=!0),o[l]=y,console.log(`
|
|
674
|
+
${O.green}\u2713${O.reset} Profile "${l}" added: ${d}@${u}${f!==22?`:${f}`:""}${m!=="other"?` [${m}]`:""}`),r=await Zt(`
|
|
675
|
+
Add another server?`,!1)}ke.existsSync(t)||ke.mkdirSync(t,{recursive:!0}),ke.writeFileSync(e,JSON.stringify(o,null,2)+`
|
|
644
676
|
`,"utf-8"),console.log(`
|
|
645
|
-
${
|
|
677
|
+
${O.green}\u2713 Saved .nex/servers.json (${Object.keys(o).length} profile${Object.keys(o).length!==1?"s":""})${O.reset}`);let i=en.join(process.cwd(),".gitignore");ke.existsSync(i)&&(ke.readFileSync(i,"utf-8").includes(".nex/")||await Zt("Add .nex/ to .gitignore?",!0)&&(ke.appendFileSync(i,`
|
|
646
678
|
# nex-code server profiles
|
|
647
679
|
.nex/
|
|
648
|
-
`),console.log(`${
|
|
649
|
-
Set up deploy configs (.nex/deploy.json)?`,!1)&&await
|
|
650
|
-
${
|
|
651
|
-
`)}async function
|
|
652
|
-
${
|
|
653
|
-
`);let
|
|
654
|
-
${
|
|
655
|
-
${
|
|
656
|
-
Add another deploy config?`,!1)}
|
|
680
|
+
`),console.log(`${O.green}\u2713 Added .nex/ to .gitignore${O.reset}`))),await Zt(`
|
|
681
|
+
Set up deploy configs (.nex/deploy.json)?`,!1)&&await jl(o,t),console.log(`
|
|
682
|
+
${O.dim}Use /servers to list profiles, /servers ping to check connectivity.${O.reset}
|
|
683
|
+
`)}async function jl(t,e){let s=e||en.join(process.cwd(),ql),n=en.join(s,"deploy.json"),o={};if(ke.existsSync(n))try{o=JSON.parse(ke.readFileSync(n,"utf-8"))}catch{}if(!t){let u=en.join(s,"servers.json");if(ke.existsSync(u))try{t=JSON.parse(ke.readFileSync(u,"utf-8"))}catch{t={}}else t={}}let r=Object.keys(t);console.log(`
|
|
684
|
+
${O.bold}${O.cyan}\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557${O.reset}`),console.log(`${O.bold}${O.cyan}\u2551 Deploy Config Wizard \u2551${O.reset}`),console.log(`${O.bold}${O.cyan}\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D${O.reset}
|
|
685
|
+
`);let i=Object.keys(o);i.length>0&&console.log(`${O.dim}Existing deploy configs: ${i.join(", ")}${O.reset}`);let c={...o},l=!0;for(;l;){console.log(`
|
|
686
|
+
${O.bold}\u2500\u2500\u2500 New Deploy Config \u2500\u2500\u2500${O.reset}`);let u=await Oe("Config name (e.g. prod, staging)");if(!u){console.log(`${O.red} Name is required.${O.reset}`);continue}let d;r.length>0?d=await Dl("Target server",r,r[0]):d=await Oe("Target server (profile name or user@host)");let p=await Oe("Local path to sync (e.g. dist/ or ./build)","dist/"),f=await Oe("Remote destination path (e.g. /var/www/app)");if(!f){console.log(`${O.red} Remote path is required.${O.reset}`);continue}let h=await Oe("Deploy script to run after sync (leave empty to skip)",""),m=await Oe("Exclude paths (comma-separated, e.g. node_modules,.env)","node_modules,.env"),g=m?m.split(",").map(x=>x.trim()).filter(Boolean):[],y={server:d,local_path:p,remote_path:f};h&&(y.deploy_script=h),g.length>0&&(y.exclude=g),c[u]=y;let $=p.endsWith("/")?p:`${p}/`;console.log(`
|
|
687
|
+
${O.green}\u2713${O.reset} Deploy config "${u}": ${$} \u2192 ${d}:${f}`),h&&console.log(` ${O.dim} Then: ${h}${O.reset}`),l=await Zt(`
|
|
688
|
+
Add another deploy config?`,!1)}ke.existsSync(s)||ke.mkdirSync(s,{recursive:!0}),ke.writeFileSync(n,JSON.stringify(c,null,2)+`
|
|
657
689
|
`,"utf-8"),console.log(`
|
|
658
|
-
${
|
|
659
|
-
`)}
|
|
690
|
+
${O.green}\u2713 Saved .nex/deploy.json (${Object.keys(c).length} config${Object.keys(c).length!==1?"s":""})${O.reset}`),console.log(`${O.dim}Use: deploy prod (or with explicit params)${O.reset}
|
|
691
|
+
`)}Fl.exports={runServerWizard:m$,runDeployWizard:jl,setWizardRL:p$}});var Hl=L((Yy,Bl)=>{var h$=require("axios"),Nn=require("fs"),Wl=require("path"),g$="nex-code",Nr=Wl.join(process.cwd(),".nex"),Mr=Wl.join(Nr,"last-version-check");Nn.existsSync(Nr)||Nn.mkdirSync(Nr,{recursive:!0});async function $$(){try{let t=w$(),e=Date.now();if(t&&e-t<1440*60*1e3)return{hasNewVersion:!1};b$(e);let s=y$(),o=(await h$.get(`https://registry.npmjs.org/${g$}/latest`,{timeout:5e3})).data.version,r=x$(o,s);return{hasNewVersion:r,latestVersion:r?o:void 0,currentVersion:r?s:void 0}}catch{return{hasNewVersion:!1}}}function y$(){return In().version}function w$(){try{if(Nn.existsSync(Mr)){let t=Nn.readFileSync(Mr,"utf8");return parseInt(t,10)}}catch{}return null}function b$(t){try{Nn.writeFileSync(Mr,t.toString())}catch{}}function x$(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}}Bl.exports={checkForNewVersion:$$}});var ru=L((Vy,ou)=>{var _$=require("readline"),wt=require("fs"),Ve=require("path"),{C:a,banner:k$,cleanupTerminal:Gl}=de(),{listProviders:Lr,getActiveProviderName:$t,listAllModels:Jy,setFallbackChain:v$,getFallbackChain:S$,getProvider:E$}=ge(),{flushAutoSave:zl}=Ct(),{getActiveModel:yt,setActiveModel:Kl}=Jn(),{printContext:Yl}=xs(),{loadAllSkills:T$,getSkillCommands:Ir,handleSkillCommand:R$}=un(),{setReadlineInterface:C$,setAutoConfirm:A$,getAutoConfirm:Jl}=We(),{StickyFooter:O$}=El(),ct=process.cwd(),at=null;function Vl(){return at?.signal??null}var Us=[{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:"/tree [depth]",desc:"Show project file tree (default depth 3)"},{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:"/plan edit",desc:"Open current plan in $EDITOR"},{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:"/setup",desc:"Configure provider and API keys"},{cmd:"/undo",desc:"Undo last file change"},{cmd:"/redo",desc:"Redo last undone change"},{cmd:"/history",desc:"Show file change history"},{cmd:"/snapshot [name]",desc:"Create a named git snapshot of current changes"},{cmd:"/restore [name|last]",desc:"Restore a previously created snapshot"},{cmd:"/k8s",desc:"Kubernetes overview: namespaces and pods"},{cmd:"/exit",desc:"Quit"}];function Xl(){let t=Ir(),e=[...Us,...t],s=Math.max(...e.map(n=>n.cmd.length));console.log("");for(let{cmd:n,desc:o}of Us)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(`
|
|
660
692
|
${a.dim}Type /help for detailed usage${a.reset}
|
|
661
|
-
`)}function
|
|
693
|
+
`)}function Ql(t){try{let e,s;t.endsWith("/")||t.endsWith(Ve.sep)?(e=t,s=""):(e=Ve.dirname(t),s=Ve.basename(t)),e.startsWith("~")&&(e=Ve.join(require("os").homedir(),e.slice(1)));let n=Ve.isAbsolute(e)?e:Ve.resolve(ct,e);if(!wt.existsSync(n)||!wt.statSync(n).isDirectory())return[];let o=wt.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(Ve.sep)?t:Ve.dirname(t)+"/",l=c==="./"&&!t.startsWith("./")?i.name:c+i.name;r.push(i.isDirectory()?l+"/":l)}return r}catch{return[]}}function Zl(t){if(t.startsWith("/")){let n=[...Us,...Ir()],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("~"))?[Ql(s),s]:[[],t]}function eu(){console.log(`
|
|
662
694
|
${a.bold}${a.cyan}Commands:${a.reset}
|
|
663
695
|
${a.cyan}/help${a.reset} ${a.dim}Show this help${a.reset}
|
|
664
696
|
${a.cyan}/model [spec]${a.reset} ${a.dim}Show/switch model (e.g. openai:gpt-4o, claude-sonnet)${a.reset}
|
|
@@ -719,48 +751,51 @@ ${a.bold}${a.cyan}Undo / Redo:${a.reset}
|
|
|
719
751
|
${a.cyan}/history${a.reset} ${a.dim}Show file change history${a.reset}
|
|
720
752
|
|
|
721
753
|
${a.cyan}/exit${a.reset} ${a.dim}Quit${a.reset}
|
|
722
|
-
`)}function
|
|
723
|
-
${a.bold}${a.cyan}Providers:${a.reset}`);for(let n of t){let
|
|
724
|
-
${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
|
|
725
|
-
${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:
|
|
726
|
-
${
|
|
727
|
-
`),!0)}case"/budget":{let{getCostLimits:
|
|
728
|
-
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let
|
|
754
|
+
`)}function tu(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 Pr(){let t=Lr(),e=$t(),s=yt();console.log(`
|
|
755
|
+
${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 nu(t,e){let[s,...n]=t.split(/\s+/);switch(s){case"/help":return eu(),!0;case"/model":{let o=n.join(" ").trim();if(!o){if(e){let{showModelPicker:r}=Cl();await r(e)}else{let r=yt(),i=$t();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 Pr(),!0;if(Kl(o)){let r=yt(),i=$t();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 Pr(),!0;case"/fallback":{let o=n.join(" ").trim();if(!o){let i=S$();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 v$(r),console.log(`${a.green}Fallback chain: ${r.join(" \u2192 ")}${a.reset}`),!0}case"/tokens":{let{getConversationMessages:o}=fe(),{getUsage:r}=De(),{TOOL_DEFINITIONS:i}=Be(),c=o(),l=r(c,i),u=yt(),d=$t();console.log(`
|
|
756
|
+
${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 p=tu(l.percentage);return console.log(` ${p}`),console.log(`
|
|
757
|
+
${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}=Ft();return n.join(" ").trim()==="reset"?(r(),console.log(`${a.green}Cost tracking reset${a.reset}`),!0):(console.log(`
|
|
758
|
+
${o()}
|
|
759
|
+
`),!0)}case"/budget":{let{getCostLimits:o,getProviderSpend:r,checkBudget:i,removeCostLimit:c,saveCostLimits:l,setCostLimit:u}=Ft(),d=n[0];if(!d){let h=o(),m=Lr();console.log(`
|
|
760
|
+
${a.bold}${a.cyan}Cost Limits:${a.reset}`);let g=!1;for(let y of m){let $=r(y.provider),x=h[y.provider];if(x!==void 0){g=!0;let S=Math.min(100,Math.round($/x*100)),k=10,v=Math.round(S/100*k),T=k-v,E=`${S>=100?a.red:S>=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)} (${S}%) ${E}`)}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 p=n[1];if(!p){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(p==="off"||p==="remove"||p==="clear")return c(d),l(),console.log(`${a.green}Removed cost limit for ${d}${a.reset}`),!0;let f=parseFloat(p);return isNaN(f)||f<=0?(console.log(`${a.red}Invalid amount: ${p}. Use a positive number or 'off'.${a.reset}`),!0):(u(d,f),l(),console.log(`${a.green}Set ${d} budget limit: $${f.toFixed(2)}${a.reset}`),!0)}case"/clear":{let{clearConversation:o,getConversationMessages:r}=fe(),{clearHistory:i}=ft(),c=r();if(c.filter(u=>u.role==="user").length>=4){process.stdout.write(`${a.dim}Reflecting on session...${a.reset} `);let{learnFromSession:u}=Ar();u(c).then(d=>{if(!d.skipped&&!d.error&&(d.applied.length>0||d.nexAdded.length>0)){let p=d.applied.length+d.nexAdded.length;process.stdout.write(`${a.green}${p} learning(s) saved${a.reset}
|
|
729
761
|
`)}else process.stdout.write(`${a.dim}nothing new${a.reset}
|
|
730
762
|
`)}).catch(()=>process.stdout.write(`
|
|
731
|
-
`))}return
|
|
732
|
-
${a.bold}${a.cyan}
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
`);let
|
|
736
|
-
${a.bold}${a.cyan}
|
|
737
|
-
|
|
738
|
-
|
|
763
|
+
`))}return o(),i(),console.log(`${a.green}Conversation cleared${a.reset}`),!0}case"/context":return await Yl(ct),!0;case"/tree":{let{generateFileTree:o}=xs(),r=parseInt(n.join(" ").trim(),10),i=!isNaN(r)&&r>0?Math.min(r,8):3,c=o(ct,{maxDepth:i,maxFiles:300});return console.log(`
|
|
764
|
+
${a.bold}${a.cyan}Project tree${a.reset}${a.dim} (depth ${i})${a.reset}
|
|
765
|
+
`),console.log(`${a.dim}${c}${a.reset}
|
|
766
|
+
`),!0}case"/autoconfirm":{let o=!Jl();return A$(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}=Ct(),{getConversationMessages:r}=fe(),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=yt(),u=$t();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}=Ct(),{setConversationMessages:r}=fe(),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}=Ct(),r=o();if(r.length===0)return console.log(`${a.dim}No saved sessions${a.reset}`),!0;console.log(`
|
|
767
|
+
${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}=Ct(),{setConversationMessages:r}=fe(),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}=ht(),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}=ht(),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}=ht(),r=o();if(r.length===0)return console.log(`${a.dim}No memories saved${a.reset}`),!0;console.log(`
|
|
768
|
+
${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:p}=_n(),f=n[0],h=n.slice(1).join(" ").trim();switch(f){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 m=h.indexOf(" ");if(m<0){i(h,`# ${h}
|
|
769
|
+
|
|
770
|
+
`);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,m),y=h.substring(m+1);i(g,y),console.log(`${a.green}Added to brain: ${g}${a.reset}`)}return!0}case"list":{let m=o();if(m.length===0)return console.log(`${a.dim}No brain documents yet. Use /brain add <name> to create one.${a.reset}`),!0;console.log(`
|
|
771
|
+
${a.bold}${a.cyan}Brain Documents:${a.reset}`);let g=Math.max(8,...m.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 m){let{frontmatter:x}=r($.name),S=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}${S.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 m=await p(h,{topK:5});if(m.length===0)return console.log(`${a.dim}No matching brain documents for: ${h}${a.reset}`),!0;console.log(`
|
|
772
|
+
${a.bold}${a.cyan}Brain Search: "${h}"${a.reset}`);for(let g of m){let y=typeof g.score=="number"?g.score.toFixed(2):g.score;console.log(`
|
|
773
|
+
${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 m=r(h);return m.content?(console.log(`
|
|
739
774
|
${a.bold}${a.cyan}${h}.md${a.reset}
|
|
740
|
-
`),console.log(
|
|
741
|
-
${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${
|
|
775
|
+
`),console.log(m.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:m}=We();if(!await m(`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 m=l(),g=Object.keys(m.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 m=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(`
|
|
776
|
+
${a.bold}${a.cyan}Brain Status${a.reset}`),console.log(` Documents: ${m.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}`),m.length>0){let S=m.reduce((k,v)=>k+v.size,0);console.log(` Total size: ${S<1024?S+"B":(S/1024).toFixed(1)+"K"}`)}return console.log(),!0}case"review":{let{exec:m}=require("child_process"),{promisify:g}=require("util"),y=g(m);try{let{stdout:$}=await y("git diff .nex/brain/",{cwd:process.cwd()});$.trim()?(console.log(`
|
|
742
777
|
${a.bold}${a.cyan}Brain Changes (git diff):${a.reset}
|
|
743
|
-
`),console.log(
|
|
778
|
+
`),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 m=require("fs"),y=require("path").join(process.cwd(),".nex","brain");if(!m.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:S}=require("child_process"),{promisify:k}=require("util"),v=k(S);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 m=o();if(m.length===0)console.log(`
|
|
744
779
|
${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(`
|
|
745
780
|
${a.dim}Commands: add \xB7 list \xB7 search \xB7 show \xB7 remove \xB7 rebuild \xB7 embed \xB7 status \xB7 review \xB7 undo${a.reset}
|
|
746
781
|
`);else{console.log(`
|
|
747
|
-
${a.bold}${a.cyan}Brain: ${
|
|
782
|
+
${a.bold}${a.cyan}Brain: ${m.length} document(s)${a.reset}`);for(let g of m){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(`
|
|
748
783
|
${a.dim}Use /brain search <query> \xB7 /brain show <name> \xB7 /brain add <name>${a.reset}
|
|
749
|
-
`)}return!0}}}case"/learn":{let{learnFromSession:
|
|
784
|
+
`)}return!0}}}case"/learn":{let{learnFromSession:o,learnBrainFromSession:r}=Ar(),{getConversationMessages:i}=fe(),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 p=u.applied&&u.applied.length>0,f=u.nexAdded&&u.nexAdded.length>0,h=d.written&&d.written.length>0;if(!p&&!f&&!h)console.log(`${a.dim}No new learnings extracted from this session${a.reset}`);else{if(p){console.log(`${a.bold}${a.cyan}Memory updates:${a.reset}`);for(let{key:m,value:g,action:y}of u.applied){let $=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${$} ${a.bold}${m}${a.reset} = ${g}`)}}if(f){console.log(`${a.bold}${a.cyan}Added to NEX.md:${a.reset}`);for(let m of u.nexAdded)console.log(` ${a.green}+${a.reset} ${m}`)}if(h){console.log(`${a.bold}${a.cyan}Brain documents:${a.reset}`);for(let{name:m,reason:g,action:y}of d.written){let $=y==="updated"?`${a.yellow}~${a.reset}`:`${a.green}+${a.reset}`;console.log(` ${$} ${a.bold}${m}.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}=fe(),{getUsage:r}=De(),{TOOL_DEFINITIONS:i}=Be(),{listMemories:c}=ht(),l=o(),u=r(l,i),d=yt(),p=$t(),f=c();console.log(`
|
|
750
785
|
${a.bold}${a.cyan}Optimization Report${a.reset}
|
|
751
786
|
`);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(`
|
|
752
|
-
${a.bold}Memory:${a.reset} ${
|
|
753
|
-
${a.bold}Active Model:${a.reset} ${
|
|
754
|
-
${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
|
|
755
|
-
${a.bold}Quick Wins:${a.reset}`);for(let x of
|
|
756
|
-
${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}
|
|
757
|
-
${a.cyan}${a.bold}\u2502${a.reset} Analysis only \u2014 no file changes until approved
|
|
787
|
+
${a.bold}Memory:${a.reset} ${f.length} entries`),f.length===0)console.log(` ${a.yellow}\u2192 No memories yet. Use /learn after sessions or /remember key=value${a.reset}`);else{let S=[...f].sort((T,A)=>new Date(A.updatedAt)-new Date(T.updatedAt))[0],k=S?Math.round((Date.now()-new Date(S.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}`),f.length>30&&console.log(` ${a.yellow}\u2192 Many memories (${f.length}) \u2014 consider pruning with /forget${a.reset}`)}console.log(`
|
|
788
|
+
${a.bold}Active Model:${a.reset} ${p}:${d.id}`);let m=d.contextWindow||d.maxTokens||0;m>0&&m<32e3&&l.length>10?console.log(` ${a.yellow}\u2192 Small context window (${(m/1e3).toFixed(0)}k). Consider /model for larger context${a.reset}`):m>=128e3&&console.log(` ${a.green}\u2192 Large context window (${(m/1e3).toFixed(0)}k) \u2014 good for long sessions${a.reset}`);let g=l.filter(x=>x.role==="user").length;console.log(`
|
|
789
|
+
${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(`
|
|
790
|
+
${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,getPlanContent:u,formatPlan:d,extractStepsFromText:p,createPlan:f}=Mt(),{invalidateSystemPromptCache:h}=fe(),m=n.join(" ").trim();if(m==="status"){let g=o();return console.log(d(g)),!0}if(m==="edit"){let g=l();if(!g)return console.log(`${a.yellow}No plan to edit. Generate a plan first with /plan${a.reset}`),!0;let y=require("os"),$=require("path").join(y.tmpdir(),`nex-plan-${Date.now()}.md`);require("fs").writeFileSync($,g,"utf-8");let x=process.env.EDITOR||process.env.VISUAL||"nano",{spawnSync:S}=require("child_process");if(console.log(`${a.dim}Opening plan in ${x}... (save and close to update)${a.reset}`),S(x,[$],{stdio:"inherit"}).status===0){let{setPlanContent:v}=Mt(),T=require("fs").readFileSync($,"utf-8");v(T);let A=p(T);if(A.length>0){let F=o()?.task||"Task";f(F,A),console.log(`${a.green}Plan updated \u2014 ${A.length} steps extracted.${a.reset}`)}else console.log(`${a.green}Plan updated.${a.reset}`)}else console.log(`${a.yellow}Editor exited with error \u2014 plan unchanged.${a.reset}`);try{require("fs").unlinkSync($)}catch{}return!0}if(m==="approve"){if(r()){i(),c(!1),h();let y=o()?.steps?.length||0,$=!!l(),x=y>0?` (${y} steps)`:"";console.log(`${a.green}${a.bold}Plan approved!${a.reset}${x} ${$?"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),h(),console.log(`
|
|
791
|
+
${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\u2500\u2500\u2510${a.reset}
|
|
792
|
+
${a.cyan}${a.bold}\u2502${a.reset} Analysis only \u2014 no file changes until approved ${a.cyan}${a.bold}\u2502${a.reset}
|
|
758
793
|
${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}
|
|
759
|
-
${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}`),
|
|
760
|
-
${a.bold}${a.cyan}Plans:${a.reset}`);for(let
|
|
761
|
-
${a.bold}${a.cyan}Tool Permissions:${a.reset}`);for(let
|
|
794
|
+
${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\u2500\u2500\u2518${a.reset}`),m&&console.log(`${a.dim}Task: ${m}${a.reset}`),!0}case"/plans":{let{listPlans:o}=Mt(),r=o();if(r.length===0)return console.log(`${a.dim}No saved plans${a.reset}`),!0;console.log(`
|
|
795
|
+
${a.bold}${a.cyan}Plans:${a.reset}`);for(let i of r){let c=i.status==="completed"?`${a.green}\u2713`:i.status==="executing"?`${a.blue}\u2192`:`${a.dim}\u25CB`;console.log(` ${c} ${a.reset}${a.bold}${i.name}${a.reset} \u2014 ${i.task||"?"} (${i.steps} steps, ${i.status})`)}return console.log(),!0}case"/auto":{let{getAutonomyLevel:o,setAutonomyLevel:r,AUTONOMY_LEVELS:i}=Mt(),c=n.join(" ").trim();return c?(r(c)?console.log(`${a.green}Autonomy: ${c}${a.reset}`):console.log(`${a.red}Unknown level: ${c}. Use: ${i.join(", ")}${a.reset}`),!0):(console.log(`${a.bold}${a.cyan}Autonomy:${a.reset} ${o()}`),console.log(`${a.dim}Levels: ${i.join(", ")}${a.reset}`),!0)}case"/permissions":{let{listPermissions:o}=Tn(),r=o();console.log(`
|
|
796
|
+
${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(`
|
|
762
797
|
${a.dim}Use /allow <tool> or /deny <tool> to change${a.reset}
|
|
763
|
-
`),!0}case"/allow":{let{setPermission:
|
|
798
|
+
`),!0}case"/allow":{let{setPermission:o,savePermissions:r}=Tn(),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}=Tn(),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}=St(),{confirm:l}=We();if(!o())return console.log(`${a.red}Not a git repository${a.reset}`),!0;let u=n.join(" ").trim();if(u){let m=await r(u);return console.log(m?`${a.green}Committed: ${m} \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 p=await c();if(console.log(p),!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}=St();return o()?(console.log(r()),!0):(console.log(`${a.red}Not a git repository${a.reset}`),!0)}case"/review":{let{isGitRepo:o,getDiff:r}=St(),{processInput:i}=fe(),c=n.join(" ").trim(),l=c.includes("--strict"),u=c.replace("--strict","").trim(),p=`## Review Protocol
|
|
764
799
|
|
|
765
800
|
**Phase 1 \u2014 Broad Scan:** Read the target code and identify all issues at a high level.
|
|
766
801
|
|
|
@@ -795,86 +830,86 @@ For each issue, include:
|
|
|
795
830
|
+ fixed code
|
|
796
831
|
\`\`\`${l?`
|
|
797
832
|
|
|
798
|
-
\u26A0 STRICT MODE: You MUST identify at least 3 critical weaknesses. If the code appears clean, dig deeper \u2014 look for subtle error-swallowing, race conditions, missing validation, or architecture risks. Do not give a passing score without identifying at least 3 critical issues.`:""}`,
|
|
833
|
+
\u26A0 STRICT MODE: You MUST identify at least 3 critical weaknesses. If the code appears clean, dig deeper \u2014 look for subtle error-swallowing, race conditions, missing validation, or architecture risks. Do not give a passing score without identifying at least 3 critical issues.`:""}`,f;if(u)f=`Do a thorough code review of \`${u}\`.
|
|
799
834
|
|
|
800
|
-
${
|
|
835
|
+
${p}`;else{if(!o())return console.log(`${a.red}Not a git repository \u2014 try /review <file>${a.reset}`),!0;let[h,m]=await Promise.all([r(!1),r(!0)]),g=m||h;if(!g||!g.trim())return console.log(`${a.yellow}No changes to review \u2014 commit something or specify a file: /review <file>${a.reset}`),!0;f=`Review the following code diff.
|
|
801
836
|
|
|
802
|
-
${
|
|
837
|
+
${p}
|
|
803
838
|
|
|
804
839
|
\`\`\`diff
|
|
805
840
|
${g.substring(0,2e4)}
|
|
806
|
-
\`\`\``}return await
|
|
841
|
+
\`\`\``}return await i(f),!0}case"/branch":{let{isGitRepo:o,getCurrentBranch:r,createBranch:i}=St();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}=ts(),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(`
|
|
807
842
|
${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(`
|
|
808
843
|
${a.dim}Use /mcp connect to connect all servers${a.reset}
|
|
809
|
-
`),!0}case"/hooks":{let{listHooks:
|
|
810
|
-
${a.bold}${a.cyan}Hooks:${a.reset}`);for(let
|
|
811
|
-
${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}`,
|
|
844
|
+
`),!0}case"/hooks":{let{listHooks:o}=cr(),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(`
|
|
845
|
+
${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}=un(),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(`
|
|
846
|
+
${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}`,p=u.type==="prompt"?`${a.dim}(prompt)${a.reset}`:`${a.dim}(script)${a.reset}`,f=[];u.commands>0&&f.push(`${u.commands} cmd`),u.tools>0&&f.push(`${u.tools} tools`);let h=f.length>0?` \u2014 ${f.join(", ")}`:"";console.log(` ${d} ${a.bold}${u.name}${a.reset} ${p}${h}`)}return console.log(`
|
|
812
847
|
${a.dim}Use /skills enable <name> or /skills disable <name>${a.reset}
|
|
813
|
-
`),!0}case"/tasks":{let{renderTaskList:
|
|
814
|
-
`+
|
|
815
|
-
`),!0)}case"/undo":{let{undo:
|
|
848
|
+
`),!0}case"/tasks":{let{renderTaskList:o,clearTasks:r}=ds();return n.join(" ").trim()==="clear"?(r(),console.log(`${a.green}Tasks cleared${a.reset}`),!0):(console.log(`
|
|
849
|
+
`+o()+`
|
|
850
|
+
`),!0)}case"/undo":{let{undo:o,getUndoCount:r}=ft(),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}=ft(),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}=ft(),c=o(20);if(c.length===0)return console.log(`${a.dim}No file changes in this session${a.reset}`),!0;console.log(`
|
|
816
851
|
${a.bold}File Change History${a.reset}
|
|
817
852
|
`);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(`
|
|
818
|
-
${a.dim}${
|
|
819
|
-
`),!0}case"/
|
|
853
|
+
${a.dim}${r()} undo / ${i()} redo available${a.reset}
|
|
854
|
+
`),!0}case"/snapshot":{let{createSnapshot:o,listSnapshots:r}=ft(),i=n.join(" ").trim()||void 0;if(i==="list"){let l=r(ct);if(l.length===0)console.log(`${a.dim}No snapshots found${a.reset}`);else{console.log(`
|
|
855
|
+
${a.bold}${a.cyan}Snapshots:${a.reset}`);for(let u of l)console.log(` ${a.cyan}#${u.index}${a.reset} ${a.bold}${u.shortName}${a.reset}`);console.log()}return!0}let c=o(i,ct);return c.ok?(console.log(`${a.green}Snapshot created:${a.reset} ${c.label}`),console.log(`${a.dim}Use /restore to apply it later${a.reset}`)):console.log(`${a.yellow}${c.error}${a.reset}`),!0}case"/restore":{let{restoreSnapshot:o,listSnapshots:r}=ft(),i=n.join(" ").trim()||"last";if(i==="list"){let l=r(ct);if(l.length===0)console.log(`${a.dim}No snapshots available${a.reset}`);else{console.log(`
|
|
856
|
+
${a.bold}${a.cyan}Available snapshots:${a.reset}`);for(let u of l)console.log(` ${a.cyan}#${u.index}${a.reset} ${a.bold}${u.shortName}${a.reset}`);console.log(`
|
|
857
|
+
${a.dim}Usage: /restore <name|last>${a.reset}
|
|
858
|
+
`)}return!0}let c=o(i,ct);return c.ok?(console.log(`${a.green}Restored snapshot:${a.reset} ${c.label}`),console.log(`${a.dim}Working tree updated. Use /undo for in-session file undos.${a.reset}`)):(console.log(`${a.red}Restore failed:${a.reset} ${c.error}`),console.log(`${a.dim}Use /snapshot list to see available snapshots${a.reset}`)),!0}case"/k8s":{let o=n.join(" ").trim(),{exec:r}=require("child_process"),{promisify:i}=require("util"),c=i(r),l=o||null,u=l?`ssh -o ConnectTimeout=10 -o BatchMode=yes ${l.replace(/[^a-zA-Z0-9@._-]/g,"")} `:"",d=p=>l?`${u}"${p.replace(/"/g,'\\"')}"`:p;console.log(`
|
|
820
859
|
${a.bold}${a.cyan}Kubernetes Overview${a.reset}${l?a.dim+" (remote: "+l+")"+a.reset:""}
|
|
821
|
-
`);try{let{stdout:
|
|
822
|
-
`).filter(Boolean);console.log(`${a.bold}Namespaces (${
|
|
823
|
-
`),!0}try{let{stdout:
|
|
824
|
-
`).filter(Boolean),h=
|
|
825
|
-
`);let
|
|
826
|
-
`)}catch(
|
|
827
|
-
`)}return!0}case"/servers":{let{loadServerProfiles:
|
|
860
|
+
`);try{let{stdout:p}=await c(d("kubectl get namespaces --no-headers -o custom-columns=NAME:.metadata.name"),{timeout:15e3}),f=p.trim().split(`
|
|
861
|
+
`).filter(Boolean);console.log(`${a.bold}Namespaces (${f.length}):${a.reset}`);for(let h of f)console.log(` ${a.cyan}${h}${a.reset}`);console.log()}catch{return console.log(`${a.dim}Could not reach cluster \u2014 is kubectl configured?${a.reset}
|
|
862
|
+
`),!0}try{let{stdout:p}=await c(d("kubectl get pods -A --no-headers -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,READY:.status.containerStatuses[0].ready,STATUS:.status.phase,RESTARTS:.status.containerStatuses[0].restartCount"),{timeout:2e4}),f=p.trim().split(`
|
|
863
|
+
`).filter(Boolean),h=f.filter($=>$.includes("Running")).length,m=f.filter($=>$.includes("Pending")).length,g=f.filter($=>$.includes("Failed")||$.includes("Error")||$.includes("CrashLoop")).length;console.log(`${a.bold}Pods: ${f.length} total ${a.green}${h} running${a.reset} ${a.yellow}${m} pending${a.reset} ${a.red}${g} unhealthy${a.reset}
|
|
864
|
+
`);let y=f.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}
|
|
865
|
+
`)}catch(p){console.log(`${a.dim}Could not list pods: ${p.message}${a.reset}
|
|
866
|
+
`)}return!0}case"/servers":{let{loadServerProfiles:o,resolveProfile:r,sshExec:i}=Ht(),c=o(),l=Object.keys(c);if(l.length===0)return console.log(`
|
|
828
867
|
${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}
|
|
829
|
-
`),!0;if(n[0]==="ping"){let
|
|
830
|
-
${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(
|
|
831
|
-
${a.bold}${a.cyan}Configured servers (${l.length}):${a.reset}`);for(let
|
|
868
|
+
`),!0;if(n[0]==="ping"){let p=n[1]?[n[1]]:l;return console.log(`
|
|
869
|
+
${a.bold}${a.cyan}Server connectivity:${a.reset}`),await Promise.all(p.map(async f=>{if(!c[f]){console.log(` ${a.red}\u2717${a.reset} ${f} \u2014 unknown profile`);return}try{let h={...c[f],_name:f},{exitCode:m}=await i(h,"echo ok",{timeout:8e3});console.log(m===0?` ${a.green}\u2713${a.reset} ${f} (${h.user?h.user+"@":""}${h.host})`:` ${a.red}\u2717${a.reset} ${f} (${h.host}) \u2014 SSH failed (exit ${m})`)}catch(h){console.log(` ${a.red}\u2717${a.reset} ${f} \u2014 ${h.message}`)}})),console.log(""),!0}let{formatProfile:d}=Ht();console.log(`
|
|
870
|
+
${a.bold}${a.cyan}Configured servers (${l.length}):${a.reset}`);for(let p of l)console.log(` ${a.green}${p}${a.reset} ${a.dim}${d(p,c[p])}${a.reset}`);return console.log(`
|
|
832
871
|
${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}
|
|
833
|
-
`),!0}case"/docker":{let{loadServerProfiles:
|
|
834
|
-
${a.bold}${a.cyan}Docker Containers:${a.reset}`);for(let[
|
|
835
|
-
`).forEach(
|
|
836
|
-
${a.bold}Running deploy: ${c}${l?" (dry run)":""}${a.reset}`);let
|
|
872
|
+
`),!0}case"/docker":{let{loadServerProfiles:o,sshExec:r}=Ht(),{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(),p=[["local",null],...Object.entries(d)];console.log(`
|
|
873
|
+
${a.bold}${a.cyan}Docker Containers:${a.reset}`);for(let[f,h]of p){let m=f==="local"?`${a.dim}local${a.reset}`:`${a.cyan}${f}${a.reset}`;try{let g;if(f==="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(` ${m}: ${a.red}SSH error (${y.exitCode})${a.reset}`);continue}}!g||g==="NAMES IMAGE STATUS PORTS"?console.log(` ${m}: ${a.dim}(no containers)${a.reset}`):(console.log(` ${m}:`),g.split(`
|
|
874
|
+
`).forEach(y=>console.log(` ${a.dim}${y}${a.reset}`)))}catch(g){console.log(` ${m}: ${a.red}${g.message}${a.reset}`)}}return console.log(""),!0}case"/deploy":{let{loadDeployConfigs:o}=Ro(),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}=Be();console.log(`
|
|
875
|
+
${a.bold}Running deploy: ${c}${l?" (dry run)":""}${a.reset}`);let p=await d("deploy",{...u,dry_run:l});return console.log(p),!0}if(i.length===0)return console.log(`
|
|
837
876
|
${a.dim}No deploy configs. Run /init to create .nex/deploy.json${a.reset}
|
|
838
877
|
`),!0;console.log(`
|
|
839
|
-
${a.bold}${a.cyan}Deploy configs (${
|
|
878
|
+
${a.bold}${a.cyan}Deploy configs (${i.length}):${a.reset}`);for(let[l,u]of Object.entries(r)){let d=u.local_path||"",p=`${u.server}:${u.remote_path}`,f=u.deploy_script?` ${a.dim}\u2192 ${u.deploy_script}${a.reset}`:"";console.log(` ${a.green}${l}${a.reset} ${a.dim}${d} \u2192 ${p}${a.reset}${f}`)}return console.log(`
|
|
840
879
|
${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}
|
|
841
|
-
`),!0}case"/init":{let{runServerWizard:
|
|
842
|
-
`).filter(Boolean).slice(-
|
|
843
|
-
`)}catch{}}function
|
|
844
|
-
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:
|
|
880
|
+
`),!0}case"/init":{let{runServerWizard:o,runDeployWizard:r,setWizardRL:i}=Ul();return i(e),n[0]==="deploy"?await r():await o(),!0}case"/setup":{let{runSetupWizard:o}=Sr();return await o({rl:e,force:!0}),!0}case"/exit":case"/quit":process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0);default:return R$(t)||console.log(`${a.red}Unknown command: ${s}. Type /help${a.reset}`),!0}}var qr=1e3;function Dr(){return Ve.join(process.cwd(),".nex","repl_history")}function su(){try{let t=Dr();if(wt.existsSync(t))return wt.readFileSync(t,"utf-8").split(`
|
|
881
|
+
`).filter(Boolean).slice(-qr)}catch{}return[]}function Fs(t){try{let e=Dr(),s=Ve.dirname(e);wt.existsSync(s)||wt.mkdirSync(s,{recursive:!0}),wt.appendFileSync(e,t+`
|
|
882
|
+
`)}catch{}}function Ne(){let{isPlanMode:t,getAutonomyLevel:e}=Mt(),s=[];t()&&s.push("plan");let n=e();n!=="interactive"&&s.push(n);let o=$t(),r=yt(),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 jr="\x1B[200~",Fr="\x1B[201~";function N$(t){return typeof t=="string"&&t.includes(jr)}function M$(t){return typeof t=="string"&&t.includes(Fr)}function Mn(t){return typeof t!="string"?t:t.split(jr).join("").split(Fr).join("")}async function P$(){if(!E$("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"),Kl("local:llama3"),!0}catch{return!1}}async function L$(){let{setAbortSignalGetter:t,getConversationLength:e,processInput:s}=fe();t(Vl);let o=Lr().some(q=>q.configured),r=(async()=>{T$();let q=yt(),P=$t();return{model:q,providerName:P}})(),i=(async()=>o?!0:await P$()?(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}
|
|
883
|
+
`),!0):!1)(),c=(async()=>{if(process.env.NEX_DISABLE_UPDATE_CHECK==="1")return{hasNewVersion:!1};try{let{checkForNewVersion:q}=Hl();return await q()}catch{return{hasNewVersion:!1}}})(),[l,u,d]=await Promise.all([r,i,c]);!u&&!o&&(console.error(`
|
|
845
884
|
${a.red}\u2717 No provider configured and no local Ollama detected.${a.reset}
|
|
846
|
-
`),process.exit(1));let
|
|
847
|
-
${
|
|
885
|
+
`),process.exit(1));let p=su(),f=_$.createInterface({input:process.stdin,output:process.stdout,prompt:Ne(),completer:Zl,history:p,historySize:qr});C$(f);let{setAskUserHandler:h}=Be();h(async(q,P)=>{let B="\x1B[0m",V="\x1B[1m",D="\x1B[2m",Q="\x1B[36m";return process.stdout.write(`
|
|
886
|
+
${V}\x1B[33m\u2753${B} ${V}${q}${B}
|
|
848
887
|
|
|
849
|
-
`),
|
|
850
|
-
`)}),process.stdout.write(` ${D}${
|
|
888
|
+
`),P.forEach((le,U)=>{process.stdout.write(` ${Q}${U+1}${B} ${le}
|
|
889
|
+
`)}),process.stdout.write(` ${D}${P.length+1}${B} ${D}Eigene Antwort\u2026${B}
|
|
851
890
|
`),process.stdout.write(`
|
|
852
|
-
${
|
|
853
|
-
`),
|
|
891
|
+
${Q}[1-${P.length+1}]${B} \u203A `),new Promise(le=>{f.pause(),process.stdin.isTTY&&process.stdin.setRawMode(!0);let U=be=>{let Me=be.toString();if(Me===""){process.stdout.write(`
|
|
892
|
+
`),ee(),le("");return}let Pe=parseInt(Me);Pe>=1&&Pe<=P.length?(process.stdout.write(`${V}${P[Pe-1]}${B}
|
|
854
893
|
|
|
855
|
-
`),
|
|
894
|
+
`),ee(),le(P[Pe-1])):(Pe===P.length+1||Me==="\r"||Me===`
|
|
856
895
|
`)&&(process.stdout.write(`
|
|
857
|
-
`),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",
|
|
858
|
-
`),
|
|
859
|
-
`),await
|
|
860
|
-
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`)
|
|
861
|
-
|
|
862
|
-
`),
|
|
863
|
-
`)
|
|
864
|
-
`)
|
|
865
|
-
`)),j()}if(
|
|
866
|
-
`)),!0}if(
|
|
867
|
-
`)
|
|
868
|
-
`)
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
`)}return}if(
|
|
872
|
-
`).
|
|
873
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${
|
|
874
|
-
`).trim();if(he=null,D){Ts(D.replace(/\n/g,"\\n")),$=!0,y=0,x=!1,T&&(clearTimeout(T),T=null),st=new AbortController;try{await o(D)}catch(Z){if(!st?.signal?.aborted){let V=Z.message?.split(`
|
|
875
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${V}${a.reset}`)}}let{getConversationLength:W}=de();$=!1;let G=W();G>0&&process.stdout.write(`${a.gray}[${G} messages] ${a.reset}`)}m.setPrompt(Re()),m.prompt();return}m.setPrompt(Tt),m.prompt();return}if(P.trim()==='"""'||P.trim().startsWith('"""')){let D=P.trim().substring(3);he=D?[D]:[],he._mode="triple",m.setPrompt(Tt),m.prompt();return}if(P.endsWith("\\")){he=[P.slice(0,-1)],he._mode="backslash",m.setPrompt(Tt),m.prompt();return}let M=P.trim();if(!M){m.setPrompt(Re()),m.prompt();return}if(Ts(M),M==="/"){Ol(),m.setPrompt(Re()),m.prompt();return}if(M.startsWith("/")){await Il(M,m),m.setPrompt(Re()),m.prompt();return}{let D="\x1B[48;5;237m",W=process.stdout.columns||80;M.split(`
|
|
876
|
-
`).forEach((Z,V)=>{let ne=V===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",$e=2+Z.length,Ae=" ".repeat(Math.max(0,W-$e));console.log(`${D}${ne} ${Z}${Ae}\x1B[0m`)})}$=!0,y=0,x=!1,T&&(clearTimeout(T),T=null),st=new AbortController;try{await o(M)}catch(D){if(!st?.signal?.aborted){let W=D.message?.split(`
|
|
877
|
-
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${W}${a.reset}`)}}$=!1;let{getConversationLength:H}=de(),X=H();X>0&&process.stdout.write(`${a.gray}[${X} messages] ${a.reset}`),m.setPrompt(Re()),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)})}jl.exports={startREPL:Vg,getPrompt:Re,loadHistory:ql,appendHistory:Ts,getHistoryPath:xr,HISTORY_MAX:br,showCommandList:Ol,completer:Ml,completeFilePath:Nl,handleSlashCommand:Il,showProviders:$r,showHelp:Pl,renderBar:Ll,hasPasteStart:Yg,hasPasteEnd:Jg,stripPasteSequences:vn,getAbortSignal:Al}});var As=require("path");require("dotenv").config({path:As.join(__dirname,"..",".env")});require("dotenv").config();var ae=process.argv.slice(2);(ae.includes("--help")||ae.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
896
|
+
`),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",U),process.stdout.write(` ${Q}\u203A${B} `),f.resume(),f.once("line",we=>{process.stdout.write(`
|
|
897
|
+
`),le(we.trim()||"")}))};function ee(){process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.removeListener("data",U),f.resume()}process.stdin.on("data",U)})});let m=new O$;m.activate(f);let g=l.providerName==="ollama"?l.model.id:`${l.providerName}:${l.model.id}`;k$(g,ct,{yolo:Jl()}),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}
|
|
898
|
+
`),await Yl(ct);let y=!1,$=0,x=!1,S=null;function k(){zl(),m.deactivate(),Gl(),process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)}process.on("SIGTERM",k),process.on("exit",()=>{zl()}),f.on("SIGINT",()=>{if(Gl(),$++,$>=2){k();return}if(y){at&&at.abort();let{cancelPendingAskUser:q}=Be();q(),console.log(`
|
|
899
|
+
${a.yellow} Task cancelled. Press Ctrl+C again to exit.${a.reset}`),y=!1,f.setPrompt(Ne()),f.prompt()}else console.log(`${a.dim} (Press Ctrl+C again to exit)${a.reset}`),f.setPrompt(Ne()),f.prompt(),S&&clearTimeout(S),S=setTimeout(()=>{$=0,S=null},2e3)}),process.on("SIGINT",()=>{process.stdin.isTTY?($++,$>=2&&k()):k()});let v=!1,T=[],A=0,E={},F=!1;function j(){let q=T.join(`
|
|
900
|
+
`).replace(/\r/g,"").trim();if(T=[],v=!1,!q)return!0;A++,F=!0;let P=A;E[P]=q;let B=q.split(`
|
|
901
|
+
`).length,V=B>1?`[Pasted content #${P} \u2014 ${B} lines]`:`[Pasted content #${P}]`,D=f.line||"",Q=D&&!D.endsWith(" ")?" ":"",z=D+Q+V;return f.setPrompt(Ne()),f.prompt(),f.line=z,f.cursor=z.length,f._refreshLine(),!0}function Z(q){return q.replace(/\[Pasted content #(\d+)(?:[^\]]*)\]/g,(P,B)=>E[Number(B)]||"")}function G(){A=0,E={},F=!1}if(process.stdin.isTTY){process.stdout.write("\x1B[?2004h");let q=process.stdin.emit.bind(process.stdin);process.stdin.emit=function(P,...B){if(P!=="data")return q.call(process.stdin,P,...B);let V=B[0];if(Buffer.isBuffer(V)&&(V=V.toString("utf8")),typeof V!="string")return q.call(process.stdin,P,...B);let D=V.includes(jr),Q=V.includes(Fr);if(D&&Q){let z=Mn(V);return z&&T.push(...z.split(`
|
|
902
|
+
`)),j()}if(D){v=!0,T=[];let z=Mn(V);return z&&T.push(...z.split(`
|
|
903
|
+
`)),!0}if(Q){let z=Mn(V);return z&&T.push(...z.split(`
|
|
904
|
+
`)),j()}if(v){let z=Mn(V);return z&&T.push(...z.split(`
|
|
905
|
+
`)),!0}return q.call(process.stdin,P,...B)}}let te=0;function me(){if(te>0){let q=m._scrollEnd,P="\x1B7";for(let B=0;B<te;B++)P+=`\x1B[${q-te+1+B};1H\x1B[2K`;P+="\x1B8",m.rawWrite(P),te=0}}function Pn(q){let P=[...Us,...Ir()].filter(U=>U.cmd.startsWith(q));if(!P.length||P.length===1&&P[0].cmd===q)return;let B=m._scrollEnd,V=Math.min(10,B-2);if(V<1)return;let D=P.slice(0,V),Q=Math.max(...D.map(U=>U.cmd.length));te=D.length,P.length>V&&te++;let z=B-te+1,le="\x1B7";for(let U=0;U<D.length;U++){let{cmd:ee,desc:be}=D[U],Me=ee.substring(0,q.length),Pe=ee.substring(q.length),we=" ".repeat(Math.max(0,Q-ee.length+2));le+=`\x1B[${z+U};1H\x1B[2K ${a.cyan}${Me}${a.reset}${a.dim}${Pe}${we}${be}${a.reset}`}P.length>V&&(le+=`\x1B[${z+D.length};1H\x1B[2K ${a.dim}\u2026 +${P.length-V} more${a.reset}`),le+="\x1B8",m.rawWrite(le)}process.stdin.isTTY&&process.stdin.on("keypress",(q,P)=>{me(),!(P&&(P.name==="tab"||P.name==="return"))&&setImmediate(()=>{f.line&&f.line.startsWith("/")&&Pn(f.line)})});let ye=null,It=`${a.dim}...${a.reset} `;f.setPrompt(Ne()),f.prompt(),f.on("line",async q=>{if(me(),Object.keys(E).length>0&&(q=Z(q),G(),f.setPrompt(Ne())),y){let D=q.trim();if(D){let{injectMidRunNote:Q}=fe();Q(D),process.stdout.write(`${a.cyan} \u270E Queued \u2014 will be applied in the next step${a.reset}
|
|
906
|
+
`),f.prompt()}return}if(ye!==null){if(ye._mode==="triple"){if(q.trim()==='"""'){let D=ye.join(`
|
|
907
|
+
`).trim();if(ye=null,D){Fs(D.replace(/\n/g,"\\n")),y=!0,f.prompt(),$=0,x=!1,S&&(clearTimeout(S),S=null),at=new AbortController;try{await s(D)}catch(z){if(!at?.signal?.aborted){let le=z.message?.split(`
|
|
908
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${le}${a.reset}`)}}y=!1;let Q=B();Q>0&&process.stdout.write(`${a.gray}[${Q} messages] ${a.reset}`)}f.setPrompt(Ne()),f.prompt();return}ye.push(q),f.setPrompt(It),f.prompt();return}if(q.endsWith("\\"))ye.push(q.slice(0,-1));else{ye.push(q);let D=ye.join(`
|
|
909
|
+
`).trim();if(ye=null,D){Fs(D.replace(/\n/g,"\\n")),y=!0,f.prompt(),$=0,x=!1,S&&(clearTimeout(S),S=null),at=new AbortController;try{await s(D)}catch(le){if(!at?.signal?.aborted){let U=le.message?.split(`
|
|
910
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${U}${a.reset}`)}}let{getConversationLength:Q}=fe();y=!1;let z=Q();z>0&&process.stdout.write(`${a.gray}[${z} messages] ${a.reset}`)}f.setPrompt(Ne()),f.prompt();return}f.setPrompt(It),f.prompt();return}if(q.trim()==='"""'||q.trim().startsWith('"""')){let D=q.trim().substring(3);ye=D?[D]:[],ye._mode="triple",f.setPrompt(It),f.prompt();return}if(q.endsWith("\\")){ye=[q.slice(0,-1)],ye._mode="backslash",f.setPrompt(It),f.prompt();return}let P=q.trim();if(!P){f.setPrompt(Ne()),f.prompt();return}if(Fs(P),P==="/"){Xl(),f.setPrompt(Ne()),f.prompt();return}if(P.startsWith("/")){await nu(P,f),f.setPrompt(Ne()),f.prompt();return}{let D="\x1B[48;5;237m",Q=process.stdout.columns||80;P.split(`
|
|
911
|
+
`).forEach((le,U)=>{let ee=U===0?"\x1B[1;36m\u203A\x1B[22;39m":" ",be=2+le.length,Me=" ".repeat(Math.max(0,Q-be));console.log(`${D}${ee} ${le}${Me}\x1B[0m`)})}y=!0,f.prompt(),$=0,x=!1,S&&(clearTimeout(S),S=null),at=new AbortController;try{await s(P)}catch(D){if(!at?.signal?.aborted){let Q=D.message?.split(`
|
|
912
|
+
`)[0]||"An unexpected error occurred";console.log(`${a.red}Error: ${Q}${a.reset}`)}}y=!1;let{getConversationLength:B}=fe(),V=B();V>0&&process.stdout.write(`${a.gray}[${V} messages] ${a.reset}`),f.setPrompt(Ne()),f.prompt()}),f.on("close",()=>{process.stdin.isTTY&&process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[r\x1B[H\x1B[2J\x1B[3J"),process.exit(0)})}ou.exports={startREPL:L$,getPrompt:Ne,loadHistory:su,appendHistory:Fs,getHistoryPath:Dr,HISTORY_MAX:qr,showCommandList:Xl,completer:Zl,completeFilePath:Ql,handleSlashCommand:nu,showProviders:Pr,showHelp:eu,renderBar:tu,hasPasteStart:N$,hasPasteEnd:M$,stripPasteSequences:Mn,getAbortSignal:Vl}});var cu=require("path");require("dotenv").config({path:cu.join(__dirname,"..",".env")});require("dotenv").config();var ce=process.argv.slice(2);(ce.includes("--help")||ce.includes("-h"))&&(console.log(`Usage: nex-code [options]
|
|
878
913
|
|
|
879
914
|
Options:
|
|
880
915
|
--task <prompt> Run a single task and exit (headless mode)
|
|
@@ -887,4 +922,4 @@ Options:
|
|
|
887
922
|
--json Output result as JSON (for CI parsing)
|
|
888
923
|
-h, --help Show this help
|
|
889
924
|
-v, --version Show version
|
|
890
|
-
`),process.exit(0));if(
|
|
925
|
+
`),process.exit(0));if(ce.includes("-v")||ce.includes("--version")){let t=In();console.log(t.version),process.exit(0)}var I$=ce.includes("--yolo")||ce.includes("-yolo");if(I$){let{setAutoConfirm:t}=We();t(!0)}var Ur=ce.indexOf("--model");if(Ur!==-1&&ce[Ur+1]){let{setActiveModel:t}=ge();t(ce[Ur+1])}var Wr=ce.indexOf("--max-turns");if(Wr!==-1&&ce[Wr+1]){let t=parseInt(ce[Wr+1],10);if(t>0){let{setMaxIterations:e}=fe();e(t)}}else try{let t=require("fs"),e=cu.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}=fe();o(n)}}}catch{}function Br(){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{}}async function q$(){let{runSetupWizard:t}=Sr();await t()}function iu(t){if(ce.includes("--auto")){let{setAutoConfirm:o}=We();o(!0)}if(!ce.includes("--model")){let{setActiveModel:o}=ge(),r=process.env.HEADLESS_MODEL||"devstral-small-2:24b";o(r)}let{processInput:s,getConversationMessages:n}=fe();s(t).then(()=>{if(ce.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=>{ce.includes("--json")?console.log(JSON.stringify({success:!1,error:o.message})):console.error(o.message),process.exit(1)})}var au=ce.indexOf("--prompt-file");if(au!==-1){let t=ce[au+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)),ce.includes("--delete-prompt-file"))try{e.unlinkSync(t)}catch{}Br(),iu(s)}else{let t=ce.indexOf("--task");if(t!==-1){let e=ce[t+1];(!e||e.startsWith("--"))&&(console.error("--task requires a prompt"),process.exit(1)),Br(),iu(e)}else q$().then(()=>{Br();let{startREPL:e}=ru();e()})}
|